简体   繁体   中英

java.lang.NullPointerException in a listview and remote database

I'm reading from a remote database to write in a ListView witch contains imageview and text.

I have the java.lang.NullPointerException error.
I tried to solve it but I couldn't.

In the for loop of the doInBackground method, the array String are ok and I can write the result in the logcat but out of the for loop I can't.

Thanks.

package com.example.alztrimakis;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

public class contact extends Activity {

ListView list;
LazyImageLoadAdapter adapter;

JSONParser jParser = new JSONParser();
private static final String TAG_nom = "nom";
private static final String TAG_prenom = "prenom";
private static final String TAG_relation = "relation";
private static final String TAG_SUCCESS = "success";
private static final String TAG_photo = "photo";
private static final String TAG_pers = "idpersonne";
 SharedPreferences pref;

 String [] tabphoto, tabnom, tabprenom, tabrelation, tabidpers;
private ProgressDialog pDialog;
String idp ;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contact);

    list=(ListView)findViewById(R.id.listViewcontact);

    loadReps verif = new loadReps();
    verif.execute();
    Log.d("load","ok");
    Log.d("tabphoto",tabphoto.toString());
    Log.d("tabnom",tabnom.toString());
    Log.d("tabprenom",tabprenom.toString());
    Log.d("tabrelation",tabrelation.toString());
    Log.d("tabidpers",tabidpers.toString());

    // Create custom adapter for listview
    adapter= new LazyImageLoadAdapter(this, tabphoto, tabnom, tabprenom, tabrelation);
    Log.d("adapter","ok");
    //Set adapter to listview
    list.setAdapter(adapter);

}
 public void onItemClick(int mPosition)
{
    String tempValues = tabphoto[mPosition];
    String idperss = tabidpers[mPosition];

    Toast.makeText(contact.this, 
            "Image URL : "+tempValues+" dest "+idperss, 
            Toast.LENGTH_LONG)
    .show();
}

// Image urls used in LazyImageLoadAdapter.java file

class loadReps extends  AsyncTask<String, String, String> {


     JSONObject tt;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(contact.this);
            pDialog.setMessage("Chargement...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
            Log.d("onpreExec","ok");
        }
        @Override
        protected String doInBackground(String... args) {

            Log.d("back","ok");
            pref = getSharedPreferences("memtrimakis",0);
             idp = pref.getString("idpatient", "no");       
            if (idp != "no")
            {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("idpatient",idp));
            IWebServices webServices = new WebServices();
            try {
            String result = webServices.getResult("affcontacts.php",nameValuePairs);
            JSONObject json = new JSONObject(result);
            Log.d("rep:", json.toString());
                int success = json.getInt(TAG_SUCCESS);
                selectip ipaddresse =new selectip();
                if (success == 1) {
                    tabphoto = new String[json.length()];
                    tabnom = new String[json.length()];
                    tabprenom = new String[json.length()];
                    tabrelation = new String[json.length()];
                    tabidpers = new String[json.length()];
                for (int i=0; i<json.length();i++)
                     {
                    tt = (JSONObject) json.get(String.valueOf(i));
                    tabphoto[i] = ipaddresse.adresseip().toString()+"img/"+tt.getString(TAG_photo);
                    tabnom[i]= tt.getString(TAG_nom);
                    tabprenom[i]= tt.getString(TAG_prenom);;
                    tabrelation[i]= tt.getString(TAG_relation);
                    tabidpers[i]= tt.getString(TAG_pers);
                     }


                }
                }

            catch (Exception e) {
                 e.printStackTrace();
            }
            }
                return null;
            }
        @Override
            protected void onPostExecute(String file_url) {


                Log.d("post","ok");
                runOnUiThread(new Runnable() {
                    @Override

                    public void run() {
                        for (int j=0; j<tabphoto.length;j++)
{Log.d("tabphotob"+j,tabphoto[j]);}


                    }
                });
                if(pDialog != null)
                    pDialog.dismiss();  
                }

 }

}

this is the logcat

05-17 16:35:39.665: E/AndroidRuntime(2865): FATAL EXCEPTION: main
05-17 16:35:39.665: E/AndroidRuntime(2865): java.lang.RuntimeException: Unable to start     activity ComponentInfo{com.example.alztrimakis/com.example.alztrimakis.contact}: java.lang.NullPointerException
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.os.Looper.loop(Looper.java:137)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.app.ActivityThread.main(ActivityThread.java:5103)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at java.lang.reflect.Method.invoke(Method.java:525)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at dalvik.system.NativeStart.main(Native Method)
05-17 16:35:39.665: E/AndroidRuntime(2865): Caused by: java.lang.NullPointerException
05-17 16:35:39.665: E/AndroidRuntime(2865):     at com.example.alztrimakis.contact.onCreate(contact.java:47)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.app.Activity.performCreate(Activity.java:5133)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-17 16:35:39.665: E/AndroidRuntime(2865):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
05-17 16:35:39.665: E/AndroidRuntime(2865):     ... 11 more

Async tasks are asynchronous. The results are not available yet when execute() returns, and your NPE comes when you try to access uninitialized tabphoto array.

Move the code that works with the async task results to the task's onPostExecute() .

NPE because the tabphoto, tabnom, tabprenom, tabrelation arrays aren't initialized` before assigning to the adapter. This happens because Asynctasks are asynchronous ergo, might still be running whilst you try to access the results. Make sure you construct the adapter in the onPostExecute() as done below:

package com.example.alztrimakis;


import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

public class contact extends Activity {

ListView list;
LazyImageLoadAdapter adapter;

JSONParser jParser = new JSONParser();
private static final String TAG_nom = "nom";
private static final String TAG_prenom = "prenom";
private static final String TAG_relation = "relation";
private static final String TAG_SUCCESS = "success";
private static final String TAG_photo = "photo";
private static final String TAG_pers = "idpersonne";
 SharedPreferences pref;

 String [] tabphoto, tabnom, tabprenom, tabrelation, tabidpers;
private ProgressDialog pDialog;
String idp ;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contact);

    list=(ListView)findViewById(R.id.listViewcontact);

    loadReps verif = new loadReps();
    verif.execute();
    Log.d("load","ok");
    Log.d("tabphoto",tabphoto.toString());
    Log.d("tabnom",tabnom.toString());
    Log.d("tabprenom",tabprenom.toString());
    Log.d("tabrelation",tabrelation.toString());
    Log.d("tabidpers",tabidpers.toString());



}
 public void onItemClick(int mPosition)
{
    String tempValues = tabphoto[mPosition];
    String idperss = tabidpers[mPosition];

    Toast.makeText(contact.this, 
            "Image URL : "+tempValues+" dest "+idperss, 
            Toast.LENGTH_LONG)
    .show();
}

// Image urls used in LazyImageLoadAdapter.java file

class loadReps extends  AsyncTask<String, String, String> {


     JSONObject tt;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(contact.this);
            pDialog.setMessage("Chargement...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
            Log.d("onpreExec","ok");
        }
        @Override
        protected String doInBackground(String... args) {

            Log.d("back","ok");
            pref = getSharedPreferences("memtrimakis",0);
             idp = pref.getString("idpatient", "no");       
            if (idp != "no")
            {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("idpatient",idp));
            IWebServices webServices = new WebServices();
            try {
            String result = webServices.getResult("affcontacts.php",nameValuePairs);
            JSONObject json = new JSONObject(result);
            Log.d("rep:", json.toString());
                int success = json.getInt(TAG_SUCCESS);
                selectip ipaddresse =new selectip();
                if (success == 1) {
                    tabphoto = new String[json.length()];
                    tabnom = new String[json.length()];
                    tabprenom = new String[json.length()];
                    tabrelation = new String[json.length()];
                    tabidpers = new String[json.length()];
                for (int i=0; i<json.length();i++)
                     {
                    tt = (JSONObject) json.get(String.valueOf(i));
                    tabphoto[i] = ipaddresse.adresseip().toString()+"img/"+tt.getString(TAG_photo);
                    tabnom[i]= tt.getString(TAG_nom);
                    tabprenom[i]= tt.getString(TAG_prenom);;
                    tabrelation[i]= tt.getString(TAG_relation);
                    tabidpers[i]= tt.getString(TAG_pers);
                     }


                }
                }

            catch (Exception e) {
                 e.printStackTrace();
            }
            }
                return null;
            }
        @Override
            protected void onPostExecute(String file_url) {


                Log.d("post","ok");
                runOnUiThread(new Runnable() {
                    @Override

                    public void run() {
                        for (int j=0; j<tabphoto.length;j++)
{Log.d("tabphotob"+j,tabphoto[j]);}


                    }
                });
 // Create custom adapter for listview
        adapter= new LazyImageLoadAdapter(contact.this, tabphoto, tabnom, tabprenom, tabrelation);
        Log.d("adapter","ok");
        //Set adapter to listview
        list.setAdapter(adapter);
                    if(pDialog != null)
                        pDialog.dismiss(); 


                }

 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM