我的整个应用程序基于php连接和mysql数据处理。由于加载数据需要花费一些时间,目前用户无法看到正在发生的事情,他们会去点击按钮,认为没有发生任何事情,也无需等待数据加载。
作为解决方案,我想用进度条添加“请等到数据加载”。
我如何对以下代码执行此操作。
我尝试过使用Async任务和教程,但是不要理解它。
谢谢,
public class Activity_YourFriendsWith_Class extends Activity {
public String PREFS_NAME = "MyPrefsFile";
public String PREFS_USERID = "prefsUserId";
private static final String TAG_Name = "fname";
private static final String TAG_LName = "lname";
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yourfriendswith);
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String userId = pref.getString(PREFS_USERID, "");
Button back = (Button) findViewById(R.id.addback);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(getApplication(), Activity_MyProfile_Class.class);
startActivity(intent);
finish();
}
});
Button addfrnds = (Button) findViewById(R.id.addfrnds);
addfrnds.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inti = new Intent();
inti.setClass(Activity_YourFriendsWith_Class.this,
Activity_AddFreinds_Class.class);
startActivity(inti);
}
});
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user_id", userId));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://hopscriber.com/friendshopscriber.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
ProgressTask task = new ProgressTask();
task.execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog pd;
private Activity activity;
public void LoadDataTask(Activity activity){
this.activity = activity;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(activity,
"Please wait", "Loading datas", true);
}
@Override
protected Boolean doInBackground(String... arg0) {
// TODO Auto-generated method stub
// parse json data
try {
ArrayList<HashMap<String, String>> placelist = new ArrayList<HashMap<String, String>>();
JSONArray jArray = new JSONArray(result);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Name, json_data.getString("fname"));
map.put(TAG_LName, json_data.getString("lname"));
placelist.add(map);
}
}
ListView list = (ListView) findViewById(R.id.frndslist);
ListAdapter adapter = new SimpleAdapter(activity, placelist,
R.layout.listrow_yourfriendswith, new String[] { TAG_Name,
TAG_LName }, new int[] {
R.id.fname, R.id.lname });
list.setAdapter(adapter);
} catch (JSONException e1) {
ListView list = (ListView) findViewById(R.id.frndslist);
list.setEmptyView(findViewById(R.id.fempty));
}
return null;
}
}
}
logcat的
08-16 16:26:52.748: E/AndroidRuntime(905): java.lang.RuntimeException: Unable to start activity ComponentInfo{hopscriber.com/hopscriber.com.Activity_YourFriendsWith_Class}: java.lang.NullPointerException
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.os.Handler.dispatchMessage(Handler.java:99)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.os.Looper.loop(Looper.java:130)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-16 16:26:52.748: E/AndroidRuntime(905): at java.lang.reflect.Method.invokeNative(Native Method)
08-16 16:26:52.748: E/AndroidRuntime(905): at java.lang.reflect.Method.invoke(Method.java:507)
08-16 16:26:52.748: E/AndroidRuntime(905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-16 16:26:52.748: E/AndroidRuntime(905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-16 16:26:52.748: E/AndroidRuntime(905): at dalvik.system.NativeStart.main(Native Method)
08-16 16:26:52.748: E/AndroidRuntime(905): Caused by: java.lang.NullPointerException
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.Dialog.<init>(Dialog.java:141)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.AlertDialog.<init>(AlertDialog.java:63)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ProgressDialog.<init>(ProgressDialog.java:80)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ProgressDialog.<init>(ProgressDialog.java:76)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ProgressDialog.show(ProgressDialog.java:101)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ProgressDialog.show(ProgressDialog.java:90)
08-16 16:26:52.748: E/AndroidRuntime(905): at hopscriber.com.Activity_YourFriendsWith_Class$ProgressTask.onPreExecute(Activity_YourFriendsWith_Class.java:132)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.os.AsyncTask.execute(AsyncTask.java:391)
08-16 16:26:52.748: E/AndroidRuntime(905): at hopscriber.com.Activity_YourFriendsWith_Class.onCreate(Activity_YourFriendsWith_Class.java:81)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-16 16:26:52.748: E/AndroidRuntime(905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
答案 0 :(得分:0)
使用Asynctask With Progress对话框。
答案 1 :(得分:0)
将全局对象视为
public ProgressDialog progress;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yourfriendswith);
progress = new ProgressDialog(this);
........................
而不是,
public ProgressDialog progress = new ProgressDialog(this);
它会起作用。
答案 2 :(得分:0)
您的代码有几个问题:
08-16 16:26:52.748:E / AndroidRuntime(905):引起:java.lang.NullPointerException 08-16 16:26:52.748:E / AndroidRuntime(905):在android.app.Dialog。 (Dialog.java:141))。
您需要覆盖Activity类
中的onCreateDialog()@Override
protected Dialog onCreateDialog(int id) {
ProgressDialog progress;
progress = new ProgressDialog(this);
progress.setMessage("Loading data, please wait");
return progress;
}
要开始显示对话框,请在ProgressTask.preExecute()中使用此代码:
{ int taskId = 1; //只是示例
的ShowDialog(TASKID); }
要关闭对话框 - 在ProgressTask.postExecute()中使用dismissDialog(taskId);
主流中的HTTP连接将导致异常。您必须使用ProgressTask.doInBackground()来执行http连接。
您不应该从.doInBackground修改UI元素。在AsyncTask的.preExecute()和/或.postExecute()中修改Activity和其他UI元素的listAdapter。它包含在AsyncTask使用的Google教程中。
完整的代码示例,涵盖了我在此提供的所有上述问题:Android, synctask not showing the list after progressDialog