2016-04-05 9 views
0

Ich erstelle eine App, die die Kontaktliste in einer Listenansicht anzeigt. Das Problem ist, dass ich die Fehler folgende wenn ich meine app laufen und ich bin zu kämpfen, es zu beheben:Angezeigter Fehler: Versuch, die Interface-Methode 'int java.util.List.size()' für eine Nullobjekt-Referenz aufzurufen

04-05 13:41:48.868 2488-2488/? E/AndroidRuntime: FATAL EXCEPTION: main 
              Process: com.kksworld.jsonparsing, PID: 2488 
              java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference 
               at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337) 
               at android.widget.ListView.setAdapter(ListView.java:491) 
               at com.kksworld.jsonparsing.MainActivity$JSONTask.onPostExecute(MainActivity.java:120) 
               at com.kksworld.jsonparsing.MainActivity$JSONTask.onPostExecute(MainActivity.java:48) 
               at android.os.AsyncTask.finish(AsyncTask.java:651) 
               at android.os.AsyncTask.-wrap1(AsyncTask.java) 
               at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) 
               at android.os.Handler.dispatchMessage(Handler.java:102) 
               at android.os.Looper.loop(Looper.java:148) 
               at android.app.ActivityThread.main(ActivityThread.java:5417) 
               at java.lang.reflect.Method.invoke(Native Method) 
               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 

Hier ist mein Code:

MainActivity.java

package com.kksworld.jsonparsing; 
import android.content.Context; 
import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 
import com.kksworld.jsonparsing.models.ContactModel; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 

public class MainActivity extends AppCompatActivity { 

private ListView listView; 

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

    listView = (ListView)findViewById(R.id.lvContacts) 
    } 


public class JSONTask extends AsyncTask<String,String,List<ContactModel>>{ 

    @Override 
    protected List<ContactModel> doInBackground(String... params) { 

     HttpURLConnection httpURLConnection = null; 
     BufferedReader bufferedReader = null; 

     try { 
      URL url = new URL(params[0]); 
      httpURLConnection = (HttpURLConnection) url.openConnection(); 
      httpURLConnection.connect(); 
      InputStream inputStream = httpURLConnection.getInputStream(); 
      // Through this we can read the data line by line 
      bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
      StringBuffer stringBuffer = new StringBuffer(); 
      String line = ""; 
      while ((line = bufferedReader.readLine()) != null) { 
       stringBuffer.append(line); 
      } 

      String finalJSON = stringBuffer.toString(); 
      JSONArray mainArray = new JSONArray(finalJSON); 
      JSONObject parentObject = mainArray.getJSONObject(0); 
      JSONArray parentArray = parentObject.getJSONArray("contacts"); 

      List<ContactModel> contactModelList = new ArrayList<>(); 

      // For parsing a list of items you have to use for loop 
      for(int i=0;i<11;i++) { 
       JSONObject finalObject = parentArray.getJSONObject(i); 
       ContactModel contactModel = new ContactModel(); 
       contactModel.setName(finalObject.getString("name")); 
       contactModel.setPhone(finalObject.getString("phone")); 
       contactModel.setEmail(finalObject.getString(("email"))); 
       contactModel.setOfficePhone(finalObject.getString(("officePhone"))); 
       contactModel.setLatitude((float) finalObject.getDouble("latitude")); 
       contactModel.setLongitude((float) finalObject.getDouble("longitude")); 
       // Adding the finalObject in the List 
       contactModelList.add(contactModel); 

      } 
      return contactModelList; 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } finally { 
      if (httpURLConnection != null) { 
       httpURLConnection.disconnect(); 
       try { 
        if (bufferedReader != null) { 
         bufferedReader.close(); 
        } 
       }catch(IOException e){ 
        e.printStackTrace(); 
       } 
      } 
     } 
     return null; 
    } 

    // Value returned by doInBackGround will be passed here... 

    @Override 
    protected void onPostExecute(List<ContactModel> result) { 
     super.onPostExecute(result); 

     ContactAdapter contactAdapter = new ContactAdapter(getApplicationContext(),R.layout.row,result); 
     listView.setAdapter(contactAdapter); 
    } 
} 

public class ContactAdapter extends ArrayAdapter{ 

    private List<ContactModel> contactModelList; 
    private int resource; 
    private LayoutInflater inflater; 

    public ContactAdapter(Context context, int resource, List<ContactModel> objects) { 
     super(context, resource, objects); 
     contactModelList=objects; 
     this.resource=resource; 
     inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     if(convertView == null) 
     { 
      convertView = inflater.inflate(resource,null); 
     } 
     TextView textViewName; 
     TextView textViewEmail; 
     TextView textViewPhone; 
     TextView textViewOfficePhone; 

     textViewName = (TextView)convertView.findViewById(R.id.textViewInsertName); 
     textViewEmail= (TextView)convertView.findViewById(R.id.textViewInsertEmail); 
     textViewPhone= (TextView)convertView.findViewById(R.id.textViewInsertPhone); 
     textViewOfficePhone = (TextView)convertView.findViewById(R.id.textViewInsertOfficeNumber); 

     textViewName.setText(contactModelList.get(position).getName()); 
     textViewEmail.setText(contactModelList.get(position).getEmail()); 
     textViewPhone.setText(contactModelList.get(position).getPhone()); 
     textViewOfficePhone.setText(contactModelList.get(position).getOfficePhone()); 

     return convertView; 
    } 
} 


@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_refresh) { 
     new JSONTask().execute("some_url"); 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

}

Könnte jemand bitte helfen.

+0

Meine Vermutung ist, dass die Antwort von Ihrem HTTP-Aufruf nicht als JSON analysiert wird und wahrscheinlich eine JSONException in Ihrer AsyncTask auslöst, was dazu führt, dass Ihre Aufgabe null liefert ..., die Sie dann Ihrem ContactAdapter zuführen und die NullPointerException auslöst. –

+0

jede Chance, dass contactModelList von doInBackground() an onPostExecute() übergeben wird, ist null? – notsopopularguy

+0

Die genaue Erklärung, wie Sie die NullPointerException bei ArrayAdapter.getCount() erhalten, finden Sie hier. http://stackoverflow.com/questions/36212453/my-object-is-not-null-but-im-getting-a-null-pointer-exception/36212723#36212723 –

Antwort

9

Extract diese Linie

List<ContactModel> contactModelList = new ArrayList<>(); 

vor dem try-Block und statt return null; Verwendung return contactModelList;

Sieht aus wie Ihre Parsing fehlschlägt und Sie übergeben ein null Objekt onPostExecute().

+0

Toller Arbeiter !! Es funktionierte. Vielen Dank. –

1

Das Listenobjekt, das Sie an den Adapter übergeben haben, ist null. Wenn der Adapter also list.Size() aufruft, wird eine Nullzeigerausnahme ausgelöst.

Verwenden Sie einen Debugger, setzen Sie einen Haltepunkt irgendwo um com.kksworld.jsonparsing.MainActivity $ JSONTask.onPostExecute (MainActivity.java:48), und arbeiten Sie sich von dort rückwärts, wenn Sie es nicht herausfinden können.

Man geht davon aus, dass Ihre JSON-Analyse irgendwie fehlgeschlagen ist.

Verwandte Themen