从AsyncTask更新视图

时间:2018-12-23 13:29:25

标签: android android-asynctask

我想从android中的mysql数据库中检索数据并在textview中显示

显示错误

  

E / Android运行时:致命异常:主要                     进程:com.example.learnersarena.practicemysql,PID:23452                     java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ void android.widget.TextView.setText(java.lang.CharSequence)”                         在com.example.learnersarena.practicemysql.BackgroundAsyncTask.onPostExecute(BackgroundAsyncTask.java:110)                         在com.example.learnersarena.practicemysql.BackgroundAsyncTask.onPostExecute(BackgroundAsyncTask.java:26)                         在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:5349)                         在java.lang.reflect.Method.invoke(本机方法)                         在java.lang.reflect.Method.invoke(Method.java:372)                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:908)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

这是后台异步任务代码

public class BackgroundAsyncTask extends AsyncTask<String, Void, String> {
Context ctx;
TextView tv;

BackgroundAsyncTask(Context ctx) {
    this.ctx = ctx;
}
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    String insert_url="http://192.168.10.3:81/android_exam_practice/insert.php";
    String select_url="http://192.168.10.3:81/android_exam_practice/select.php";
    String method=params[0];
    if(method.equals("insert"))
    {
        String name=params[1];
        String email=params[2];
        try {
            URL url=new URL(insert_url);
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream outputStream=httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String data= URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
                    URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            outputStream.close();
            InputStream inputStream=httpURLConnection.getInputStream();
            inputStream.close();
            return "data inserted ";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else if(method.equals("select"))
    {
 //   String Name=params[1];
   // String Email=params[2];
        try {
            URL url=new URL(select_url);
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("post");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            //OutputStream outputStream=httpURLConnection.getOutputStream();
            //BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            //String data =URLEncoder.encode("");
            InputStream inputStream=httpURLConnection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String response ="";
            String line ="";
            while((line=bufferedReader.readLine())!=null)
            {
                response+=line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return null;
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String aVoid) {
    super.onPostExecute(aVoid);
   // Toast.makeText(ctx, aVoid, Toast.LENGTH_SHORT).show();
    tv.setText(aVoid);
}

}

3 个答案:

答案 0 :(得分:1)

您的解决方案在这里。

在您的onPostExecute()方法中初始化textview

@Override
protected void onPostExecute(String aVoid) {
    super.onPostExecute(aVoid);
   // Toast.makeText(ctx, aVoid, Toast.LENGTH_SHORT).show();
    tv = findViewById(R.id.textView); 
    tv.setText(aVoid);
}

答案 1 :(得分:0)

应用程序中的

BackgroundAsyncTask 是UI线程以外的线程,因此,如果您需要更新任何视图,则可以创建 public static 活动/片段中的方法,并通过以下方式使用 runOnUiThread()方法调用该方法:

runOnUiThread(new Runnable() {
    public void run() {
         // call your method here.
    }
});

OR

使用处理程序的 check this to know more about Handler's

答案 2 :(得分:0)

从以下位置更改BackgroundAsyncTask的构造函数:

BackgroundAsyncTask(Context ctx) {
    this.ctx = ctx;
}

BackgroundAsyncTask(Context ctx, TextView tv) {
    this.ctx = ctx;
    this.tv = tv;
}

因此,当您在活动中初始化BackgroundAsyncTask时,请执行以下操作:

new BackgroundAsyncTask(this)

new BackgroundAsyncTask(this, tv)

其中tv是您要更新的活动TextView