【问题标题】:NullPointerException: Attempt to invoke virtual method AlertDialog.setTitle(java.lang.CharSequence) on a null object reference [duplicate]NullPointerException:尝试在空对象引用上调用虚拟方法 AlertDialog.setTitle(java.lang.CharSequence) [重复]
【发布时间】:2015-06-05 15:51:33
【问题描述】:

这是错误:

04-01 10:37:47.077 2310-2326/zonup.asyc D/Create 响应: {"success":"false","msg":"请输入邮箱!!!"} 04-01 10:37:47.084
2310-2310/zonup.asyc D/AndroidRuntime: 关闭虚拟机 04-01 10:37:47.084 2310-2310/zonup.asyc E/AndroidRuntime: 致命 例外:主要 进程:zonup.asyc,PID:2310 java.lang.NullPointerException:尝试调用虚拟方法“void android.app.AlertDialog.setTitle(java.lang.CharSequence)” 空对象引用 在 zonup.asyc.MainActivity$SignmeUp.onPostExecute(MainActivity.java:122) 在 zonup.asyc.MainActivity$SignmeUp.onPostExecute(MainActivity.java:70) 在 android.os.AsyncTask.finish(AsyncTask.java:632) 在 android.os.AsyncTask.access$600(AsyncTask.java:177) 在 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:135) 在 android.app.ActivityThread.main(ActivityThread.java:5221) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

public class MainActivity extends ActionBarActivity {

protected String stmail;
protected EditText editText;
protected Button button;
AlertDialog alertDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText=(EditText) findViewById(R.id.editText);
    stmail=editText.getText().toString();
    button=(Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new SignmeUp().execute();
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
class SignmeUp extends AsyncTask<String, String, String> {

    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Thanks for your Sign up...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
            }
        });
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email", stmail));



        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest("http://api.php","GET", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            String success = json.getString("success");

            if (stmail != null & success == "true") {
                Toast.makeText(MainActivity.this, "Youre Email Posted..", Toast.LENGTH_SHORT).show();
            } else {

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

        return null;
    }

    @SuppressWarnings("deprecation")
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done

        editText.setText("");
        alertDialog.setTitle("Info");

        alertDialog.setMessage("You have been subscribed o the ");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // here you can add functions

            }
        });

        alertDialog.show();

    }

}
}

【问题讨论】:

  • 放置 AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);以上 alertDialog.setTitle("Info");行
  • 移除 super.onPreExecute();
  • 你在哪里初始化了 AlertDialog?
  • 我已经粘贴了完整的代码@shvet

标签: java android android-asynctask nullpointerexception


【解决方案1】:

使用 AlertDialog.Builder 而不是使用 AlertDialog。由于 AlertDialog 已被弃用。您还需要显示进度对话框。

 @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Thanks for your Sign up...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

onPostExecute 方法dismiss 中的进度条。同时使用 AlertDialog.Builder。

 protected void onPostExecute(String file_url) {
        // dismiss the dialog once done

     if(pDialog.isShowing()){
       pDialog.dismiss();
      }
        editText.setText("");
      AlertDailog.Builder builder = new AlertDialog.Builder(Activity.this);
             builder.setText("");
             builder.setMessege("");
             builder.create().show();
        });

【讨论】:

  • @manikanta 你试过我的解决方案了吗?
  • 工作谢谢@shvet
【解决方案2】:

您在dialog.setTitle("Info") 上有一个空指针异常,但看起来您确实应该调用pDialog.setTitle("Info"),因为您在onPreExecute 中初始化的对话框是pDialog 而不是alertDialog

【讨论】:

    【解决方案3】:

    你试着给你编码

    你试试 onPreExecute 方法

      private ProgressDialog PD; 
    
            if(PD == null){
    
        //
                            PD = new ProgressDialog(SplashScreenActivity.this);
                            PD.setMessage("Please Wait..");
                            PD.setIndeterminate(false);
                            PD.setCancelable(true);
                            PD.show();
                    }
    

    然后你在方法 onPostExecute 中关闭 PrpgressDialog

    if(PD.isShowing()){
                        PD.dismiss();
                        goNext();
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多