ProgressDialog没有在主线程中开始

时间:2014-12-29 15:40:06

标签: android multithreading progressdialog

我制作了一个可以将一些数据上传到我的数据库的应用程序。在Activity中,用户将输入要上载的数据,我创建了一个ProgressDialog。 ProgressDialog是在onClick()方法中创建的。

理论上,它将被创建,因为我没有尝试在主UI线程以外的线程中创建ProgerssDialog。 但是,它没有被显示出来。我不知道为什么。

package com.example.demoapp;

import android.widget.*;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private EditText planID, name, number, address, handsetValue, planAmount, validity, pass, confirm_pass;
private Button call;
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private String response;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    prefs = getSharedPreferences("PREF", MODE_PRIVATE);

    boolean startup = prefs.getBoolean("FIRST_STARTUP", true);
    if(startup)
    {
    planID = (EditText) findViewById(R.id.planIDET);
    name = (EditText) findViewById(R.id.nameET);
    number = (EditText) findViewById(R.id.contactET);
    address = (EditText) findViewById(R.id.addressET);
    handsetValue = (EditText) findViewById(R.id.handsetValueET);
    planAmount = (EditText) findViewById(R.id.planAmountET);
    validity = (EditText) findViewById(R.id.validityET);
    pass = (EditText) findViewById(R.id.editText1);
    confirm_pass = (EditText) findViewById(R.id.editText2);

    call = (Button) findViewById(R.id.submit_Button);

    planID.setText("");
    name.setText("");
    number.setText("");
    address.setText("");
    handsetValue.setText("");
    planAmount.setText("");
    validity.setText("");
    pass.setText("");
    confirm_pass.setText("");


    call.setOnClickListener(this);
    }

    else
    {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }


}


@Override
public void onClick(View v) {

    if(pass.getText().toString().equals(confirm_pass.getText().toString()))
    {
        ProgressDialog  progress = ProgressDialog.show(v.getContext(), "Please wait...", "Connecting to server", true, true);

        String query = "INSERT INTO user_info (name, password, address, plan_id, contact, handset_value, plan_amount, validity) "
            + "VALUES('" + name.getText() + "','"+ pass.getText() +"','" + address.getText() + "','" + planID.getText() + "','" + number.getText() + "','" + handsetValue.getText() + "','" + planAmount.getText() + "','" + validity.getText() + "');";


    ConnectDBThread connect = new ConnectDBThread(query, Resources.INSERT);
    Thread t1 = new Thread(connect);
    t1.start();
    //####################################//
    Log.i("onClick() ThreadName",String.valueOf(Thread.currentThread().getId()));

    while(true)
    {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e)
        {e.printStackTrace();}



        if(Resources.serverResponse!=null)
        {
            Toast.makeText(this, "Registered Successfully", Toast.LENGTH_LONG).show();
            Log.i("SERVER", Resources.serverResponse);
            prefs = getSharedPreferences("PREF", MODE_PRIVATE);
            editor = prefs.edit();
            editor.putBoolean("FIRST_STARTUP", false);
            editor.putString("USERNAME", name.getText().toString());
            editor.putString("USERPASS", pass.getText().toString());
            editor.commit();

            //--- PROGRESSBAR STOPPED
            progress.dismiss();

            break;

        }

    }//LOOP
    }

    else
        Toast.makeText(this, "Password mismatch!", Toast.LENGTH_LONG).show();

}// onClick()


}

这里,ConnectDBThread是Runnable接口的一个实现,它连接到服务器并发布查询和数据。

如果我在onClick()中的If语句之外创建了ProgressDialog,则app首先执行查询。完成查询后,它会显示ProgressDialog。

请帮帮我。 谢谢。

1 个答案:

答案 0 :(得分:0)

我认为问题在于ProgressDialog的上下文。从设计角度来看,我认为最好将ProgressDialog声明为实例变量。

public class YourClass{

  private ProgressDialog progressDialog; // instance variable
  ....
}

然后在click方法中创建它:

// I believe the main issue is with the context you bind to the progressDialog
// provide the activity as context as an Activity extends Context
progressDialog= ProgressDialog.show(this, "Please wait...", "Connecting to server", true, true);

最后不要在onClick方法中放置像这样的while循环。它会导致按钮变粘,这是不希望的,也会使UI无响应。将您的ConnectDBThread设置为 AsyncTask ,并在 doInBackground 中完成后台处理后,通过 onPostExecute 更新用户界面(如关闭对话框)。

这是一个建议的解决方案:

public class InsertTask extends AsyncTask<String, Void, String> {

     ProgressDialog dialog;
     Context ctx;

     public InsertTask(Context ctx){
        this.ctx = ctx;
     }

     protected void onPreExecute(Void result) {
         // do UI work here
         dialog = ProgressDialog.show(ctx, "Please wait...", "Connecting to server", true, true);

     }

     protected Void doInBackground(String... args) {


        // do insert operation here ... 
        String username  = args[0];
        String password = args[1];

        ......      
        String query = .... // generate the query
        String serverResponse = doDBInsert(query); // create a method to run the query and return response

        return serverResponse;
     }

     protected void onPostExecute(String result) {
         // do UI work here
         // display your serverResponse(result) somewhere if needed
         if(dialog!=null && dialog.isShowing()){
            dialog.dismiss();
         }
     }
 }

在onClick方法中:

//If check condition is met (password = confirm password)
 new InsertTask(getApplicationContext()).execute(username, password, address ...);