0
votes

i want to retrieve data from mysql database in android and show in textview

it shows an error

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.learnersarena.practicemysql, PID: 23452 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.learnersarena.practicemysql.BackgroundAsyncTask.onPostExecute(BackgroundAsyncTask.java:110) at com.example.learnersarena.practicemysql.BackgroundAsyncTask.onPostExecute(BackgroundAsyncTask.java:26) at android.os.AsyncTask.finish(AsyncTask.java:632) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5349) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

this is the background asynctask code

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
you never initialize your TextView so your tv variable is always null , and when you want to setText on that TextView you get this, initiate it somewhere in your codeRussell Ghana
so how can i solve this problem ?Muhammad Aizaz
you have to have a xml layout file and define your TextView in that file, and initiate your textview throw id which your TextView have inside layout file, or you can create dynamic TextView, and bind it to your UI programmaticallyRussell Ghana
i have 3 java classes 2 have xml file and one is not BackgroundAsyncTask is a java file no xml fileMuhammad Aizaz

3 Answers

1
votes

Your solution is here.

In your onPostExecute() method initialize the 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);
}
0
votes

BackgroundAsyncTask in your application is a thread other than UI thread so if you need to update any view you can create an public and static method in your Activity/Fragment and call this method from using runOnUiThread() method as:

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

OR

make use of Handler's check this to know more about Handler's

0
votes

Change the constructor of BackgroundAsyncTask from:

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

to

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

So when you initialize the BackgroundAsyncTask in your activity, instead of:

new BackgroundAsyncTask(this)

write

new BackgroundAsyncTask(this, tv)

where tv is your activity's TextView that you want to update.