-1

我的整个应用程序是基于 php 连接和 mysql 数据处理。由于加载数据需要一些时间,目前用户看不到正在发生的事情,他们去点击按钮,认为没有发生任何事情,而无需等待数据加载。

作为解决方案,我想用进度条添加“请等到数据加载”。

我该如何对以下代码执行此操作。

我尝试了异步任务和教程,但无法掌握它。

谢谢你,

  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;
    }

    }



}

日志猫

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)
4

3 回答 3

0

使用带有进度对话框的 Asynctask。

于 2012-08-16T09:24:22.420 回答
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);

它会起作用的。

于 2012-08-16T09:55:25.290 回答
0

您的代码有几个问题:

  1. 我猜你的代码失败了 - 你请求对话框显示但没有 OnCreateDialog 返回对话框显示,所以你得到:

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.爪哇:141))。

您需要在 Activity 类中覆盖 onCreateDialog()

@Override
protected Dialog onCreateDialog(int id) {

ProgressDialog progress; 
progress = new ProgressDialog(this);
progress.setMessage("Loading data, please wait");
return progress;
}
  1. 要开始显示对话框,请在 ProgressTask.preExecute() 中使用此代码:

    { int taskId=1; //只是例子

    显示对话框(任务 ID);}

  2. 关闭对话框 - 在 ProgressTask.postExecute() 中使用 dismissDialog(taskId);

  3. 主流中的 HTTP 连接会导致异常。您必须使用 ProgressTask.doInBackground() 来执行 http 连接。

  4. 您不应修改 .doInBackground 中的 UI 元素。在 AsyncTask 的 .preExecute() 和/或 .postExecute() 中修改 Activity 的 listAdapter 和其他 UI 元素。它包含在 Google 的 AsyncTask 使用教程中。

完整的代码示例涵盖了我在此处提供的所有提到的问题:Android,synctask not shown the list after progressDialog

于 2012-12-13T23:52:39.797 回答