gpt4 book ai didi

java - 将 progressDialog 添加到 JSON Parser 类并为 MainActivity 返回方法

转载 作者:行者123 更新时间:2023-11-29 05:03:26 26 4
gpt4 key购买 nike

我有一个 JSONparser 类来获取数据并将数据发送到服务器,它工作正常,但是在没有 wifi 连接的情况下测试它时,该过程需要更长的时间。是否可以将流程对话框放入我的类中,因为我将此类称为每个需要发送或接收数据的 Activity 。

我尝试了一些不同的事情,例如在任务之前和之后应用设置 LinearLayout 的可见性,例如:

loading.setVisibility(View.VISIBLE);
/// DO TASK
loading.setVisibility(View.GONE);

但无论如何屏幕​​都会卡住并加载数据。

我曾尝试在 HTTP 请求的开头添加一个 processDialog,并在任务完成后再次将其删除,但我收到空引用错误。

我觉得错误可能出在类本身,因为我是 Java 的新手,我目前只真正了解基础知识,所以只是学习。

这是我的 JSONParser 类

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static String root = "**MY SERVER**";
private View loading = null;

public JSONParser() {

}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
params.add(new BasicNameValuePair("APP_ID", "**APPTOKEN**"));
// Making HTTP request
try {
// check for request method
if(method.equalsIgnoreCase("POST")){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(this.root + url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}else if(method.equalsIgnoreCase("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader( is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}

}

说实话我并没有写所有的类(class),我跟着一个tutorial并根据我的需要修改类(class)。

该类可以在任何 Activity 中调用,这是类的想法是这样的:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONParser jsonParser = new JSONParser();
loading.setVisibility(View.VISIBLE);
JSONObject json = jsonParser.makeHttpRequest("login.php", "POST", params);
try {
Boolean success = json.getBoolean("ok");
loading.setVisibility(View.GONE);
if (success) {
Log.d("LOGIN","LOGIN SUCCESSFUL");
finish();
} else {
String err_msg = json.getString("error");
Toast toast = Toast.makeText(getApplicationContext(), err_msg, Toast.LENGTH_LONG);
toast.show();

}
} catch (JSONException e) {
e.printStackTrace();
}

如果问题出在类上,我敢肯定,您能否解释一下如何修改它以合并 progressDialog。

更新在下面答案的帮助下,我设法使用 PostAsync 类添加了一个进程对话框。屁股,我已经修改了这个类,使其更加动态,是否可以处理我当前 Activity 的返回,或者我只能在 PostAcync 类中处理返回。

例如:基本的 PostAcync 类将由 New PostAcync.execute(param,param) 调用;但我修改了它,使其具有通用性,可以用于任何 Activity ;所以不,我会调用这个类并通过以下方式执行任务:

PostAsync post = new  PostAsync();
post.context = ThisActivity.this;
post.message = "Attempting to login";
post.execute("login.php", email, password);

所以现在我添加了 Dialog Builder 的 Context 来运行我可以根据任务添加不同的消息第一个参数始终是网页。

有没有办法可以在上面添加一个回调,比如

JSONObject response = post.repsonse;
//then process the data here as I could using the ajax success callback in jQuery

最佳答案

我其实wrote a blog post最近使用了此 JSONParser 类的更新版本,其中包含如何将其与显示 ProgressDialog 的 AsyncTask 一起使用的示例。

对于您的情况,您可以像这样使用 AsyncTask:

调用 AsyncTask,传递电子邮件和密码:

new PostAsync().execute(email, password);

按如下方式定义您的 AsyncTask,其中包括一个 ProgressDialog:

class PostAsync extends AsyncTask<String, String, JSONObject> {

JSONParser jsonParser = new JSONParser();

private ProgressDialog pDialog;

private static final String LOGIN_URL = "http://www.example.com/login.php.php";

@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected JSONObject doInBackground(String... args) {

try {

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", args[0]));
params.add(new BasicNameValuePair("password", args[1]));

Log.d("request", "starting");

JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);

if (json != null) {
Log.d("JSON result", json.toString());

return json;
}

} catch (Exception e) {
e.printStackTrace();
}

return null;
}

protected void onPostExecute(JSONObject json) {

if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}

if (json != null) {
try {
Boolean success = json.getBoolean("ok");
if (success) {
Log.d("LOGIN","LOGIN SUCCESSFUL");
finish();
} else {
String err_msg = json.getString("error");
Toast toast = Toast.makeText(MainActivity.this.getApplicationContext(), err_msg, Toast.LENGTH_LONG);
toast.show();

}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

}

这是 JSONParser 类的更新版本,它使用 HttpURLConnection 而不是已弃用的 DefaultHttpClient:

import android.util.Log;
import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

public class JSONParser {

String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONParser() {

}

public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

sbParams = new StringBuilder();
for (int i = 0; i < params.size(); i++) {

NameValuePair nvp = params.get(i);
try {
sbParams.append("&").append(nvp.getName()).append("=")
.append(URLEncoder.encode(nvp.getValue(), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();

conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.setRequestProperty("Accept-Charset", charset);

conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);

conn.connect();

paramsString = sbParams.toString();

wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();

} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET

if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}

try {
urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();

conn.setDoOutput(false);

conn.setRequestMethod("GET");

conn.setRequestProperty("Accept-Charset", charset);

conn.setConnectTimeout(15000);

conn.connect();

} catch (IOException e) {
e.printStackTrace();
}

}

try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}

Log.d("JSON Parser", "result: " + result.toString());

} catch (IOException e) {
e.printStackTrace();
}

conn.disconnect();

// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON Object
return jObj;
}
}

关于java - 将 progressDialog 添加到 JSON Parser 类并为 MainActivity 返回方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31253519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com