2015-01-21 212 views
0

我使用ListActivity和我解析JSON并把它放在我的自定义适配器ListActivity即显示它,空指针异常

DonorAdapter.java 

package com.example.serverlogin; 

import java.util.ArrayList; 

import android.content.Context; 

import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ImageView; 
import android.widget.TextView; 

public class DonorAdapter extends ArrayAdapter<Donor> { 

ArrayList<Donor> donorList; 
LayoutInflater vi; 
int Resource; 
ViewHolder holder; 

public DonorAdapter (Context context , int resource ,ArrayList<Donor> objects) 
{ 
    super(context, resource, objects); 
    vi = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    Resource = resource; 
    donorList = objects; 

} 
@Override 
public View getView(int position ,View convertView,ViewGroup parent) 
{ 
    View v = convertView; 
    if(v==null) 
    { 
     holder = new ViewHolder(); 
     v = vi.inflate(Resource, null); 
     holder.imageview = (ImageView) v.findViewById(R.id.iv1); 
     holder.name = (TextView) v.findViewById(R.id.tv1); 
     holder.phoneNo = (TextView) v.findViewById(R.id.tv2); 
     holder.remark =(TextView) v.findViewById(R.id.tv3); 
     holder.id =(TextView) v.findViewById(R.id.tv4); 
     holder.location=(TextView) v.findViewById(R.id.tv5); 
     holder.officeLocation =(TextView) v.findViewById(R.id.tv6); 
     holder.officePhone =(TextView) v.findViewById(R.id.tv7); 
     holder.resPhone =(TextView) v.findViewById(R.id.tv8); 
     holder.cellPhone=(TextView) v.findViewById(R.id.tv9); 
     holder.email =(TextView) v.findViewById(R.id.tv10); 
     holder.birthdate =(TextView) v.findViewById(R.id.tv11); 
     holder.gender = (TextView) v.findViewById(R.id.tv12); 
     holder.lastBloodDonation=(TextView) v.findViewById(R.id.tv13); 
    } 

    else{ 
     holder = (ViewHolder) v.getTag(); 

    } 

    //holder.imageview.setImageResource(R.drawable.ic_launcher); 
    holder.name.setText(donorList.get(position).getFname()+" "+donorList.get(position).getLname()); 
    String text =""; 
    /*if(donorList.get(position).getRemark()== null) 
     text =""; 
    else 
     text = donorList.get(position).getRemark();*/ 

    holder.remark.setText(donorList.get(position).getRemark()); 
    holder.id.setText(Integer.toString(donorList.get(position).getDonor_id())); 
    holder.location.setText(donorList.get(position).getLocation()); 
    holder.officeLocation.setText(donorList.get(position).getOfficeLocation()); 
    holder.officePhone.setText(donorList.get(position).getOfficePhone()); 
    holder.resPhone.setText(donorList.get(position).getResPhone()); 
    holder.cellPhone.setText(donorList.get(position).getCellPhone()); 
    holder.email.setText(donorList.get(position).getEmail()); 
    holder.birthdate.setText(donorList.get(position).getBirthDate()); 
    holder.gender.setText(donorList.get(position).getGender()); 
    holder.lastBloodDonation.setText(donorList.get(position).getLastBlooddonation()); 

    return v; 

} 

static class ViewHolder { 
    public ImageView imageview; 
    public TextView name; 
    public TextView phoneNo; 
    public TextView remark; 
    public TextView id; 
    public TextView location; 
    public TextView officeLocation; 
    public TextView officePhone; 

    public TextView resPhone; 
    public TextView cellPhone; 
    public TextView email; 
    public TextView birthdate; 
    public TextView gender; 
    public TextView lastBloodDonation; 


} 


} 

Donors.java

在logcat的
package com.example.serverlogin; 

import java.io.InputStreamReader; 
import java.util.ArrayList; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 
import org.json.JSONArray; 
import org.json.JSONObject; 


    import android.net.ConnectivityManager; 
    import android.net.NetworkInfo; 
    import android.os.AsyncTask; 
    import android.os.Bundle; 
import android.app.Activity; 
import android.app.ListActivity; 
    import android.app.ProgressDialog; 
import android.content.Context; 
    import android.util.Log; 
    import android.view.Menu; 
    import android.view.View; 
    import android.widget.ListView; 
    import android.widget.Toast; 

public class Donors extends ListActivity { 
Boolean success = false ; 
String url=""; 

ArrayList <Donor> donorsList = new ArrayList<Donor>(); 
DonorAdapter adapter; 
int count =0; 

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


    try{ 
      ConnectivityManager c =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);     
      NetworkInfo n =c.getActiveNetworkInfo(); 
      if (n!= null && n.isConnected()){ 

       url = "http://192.168.1.100/my/donors.json"; 

       new Background().execute(url); 
      } 
      }catch(Exception e){} 

    adapter = new DonorAdapter(getApplicationContext(),R.layout.row,donorsList); 

    setListAdapter(adapter); 


} 

@Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
    // TODO Auto-generated method stub 
    super.onListItemClick(l, v, position, id); 

    DisplayToast(donorsList.get(position).getFname()); 


} 



class Background extends AsyncTask<String,Void,Boolean> 
{ 
    ProgressDialog dialog; 

    String check = ""; 
    int count=0; 

    @Override 
    protected void onPreExecute() 
    { 
     super.onPreExecute(); 
     dialog = new ProgressDialog(Donors.this); 
     dialog.setMessage("Loading, please wait"); 
     dialog.setTitle("Connecting server"); 
     dialog.show(); 
     dialog.setCancelable(false); 


     DisplayToast("Calling Background"); 

    } 



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

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpGet httpget = new HttpGet(arg0[0]); 
     HttpResponse response; 
     Log.d("url",arg0[0]); 
     try{ 

      response = httpclient.execute(httpget); 

      if(response!=null) 
      { 
       /*if(response.getStatusLine().getStatusCode()==200) 
       { 
        HttpEntity entity = response.getEntity(); 

        if (entity != null) 
        { 
         InputStream instream = entity.getContent(); 
         check = convertStreamToString(instream); 
         if(check.equals("")) 
         { 
          check = "no data from file"; 
         } 


        } 

       }*/ 



       /* 
       Gson gson = new Gson(); 
       JsonReader jsonReader = new JsonReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
       jsonReader.beginObject(); 

       Log.d("gson","json"); 
       while (jsonReader.hasNext()) { 
         //get the element name 
         String name = jsonReader.nextName(); 
         Log.d("gson2","json"); 
         if (name.equals("success")) { 
         success = jsonReader.nextBoolean(); 
         } 
         //if the element name is the list of countries then start the array 
         else if(name.equals("donors")){ 
         jsonReader.beginArray(); 
         while (jsonReader.hasNext()) { 
         //parse every element and convert that to a country object 
         Donor d = gson.fromJson(jsonReader, Donor.class); 
         Log.d("gson2",d.getAddress()); 
         Log.d("gson2",d.getBirthDate()); 
         Log.d("gson2",d.getBloodGrp()); 
         Log.d("gson2",d.getCellPhone()); 
         Log.d("gson2",d.getCity()); 
         Log.d("gson2",d.getCountry()); 
         Log.d("gson2",d.getEmail()); 
         Log.d("gson2",d.getGender()); 
         Log.d("gson2",d.getLastBlooddonation()); 






         //add the country object to the list 
         donorsList.add(d); 
         count++; 
         Log.d("Inner count",Integer.toString(count)); 
         } 
         Log.d("In count",Integer.toString(count)); 
         jsonReader.endArray(); 
         } 
        } 
       jsonReader.endObject(); 
       jsonReader.close(); 
       */ 

       //My Logic 

       HttpEntity entity = response.getEntity(); 
       String data = EntityUtils.toString(entity); 


       JSONObject jsono = new JSONObject(data); 
       JSONArray jarray = jsono.getJSONArray("donors"); 
       String t =""; 
       for (int i = 0; i < jarray.length(); i++) { 
        JSONObject object = jarray.getJSONObject(i); 

        Donor d = new Donor(); 
        d.setDonor_id(object.getInt("donor_id")); 
        d.setFname(object.getString("fname")); 
        d.setMname(object.getString("mname")); 
        d.setLname(object.getString("lname")); 
        d.setAddress(object.getString("address")); 
        // edit req 
        d.setLocation(object.getString("location")); 
        d.setCountry(object.getString("country")); 
        d.setState(object.getString("state")); 
        d.setCity(object.getString("city")); 
        d.setOfficeLocation(object.getString("officeLocation")); 
        d.setOfficePincode(object.getInt("officePincode")); 
        d.setOfficePhone(object.getString("officePhone")); 
        d.setResPhone(object.getString("resPhone")); 
        d.setCellPhone(object.getString("cellPhone")); 
        //d.setEmail(object.getString("cellPhone")); 


        if(object.has("email")) 
        d.setEmail(object.getString("email")); 


        d.setBirthDate(object.getString("birthDate")); 
        d.setBloodGrp(object.getString("bloodGrp")); 
        d.setGender(object.getString("gender")); 


        if(object.has("remark")) 
        d.setRemark(object.getString("remark")); 
        d.setLastBlooddonation(object.getString("lastBlooddonation")); 
        donorsList.add(d); 

        Log.d("do in backgroung",Integer.toString(count++)); 
       } 
       return true; 



      } 



     } catch(Exception e) 
     { 
      Log.d("---////////////---", e.toString()); 
     } 


     return false; 
    } 

    public void onPostExecute(Boolean result) 
    { 

     dialog.cancel(); 
     adapter.notifyDataSetChanged(); 
     if(result == false) 
      Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show(); 
     //DisplatToast(s); 
     //btn1.setText(s); 
    } 


} 


private void DisplayToast(String msg) 
{ 
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show(); 

} 








} 

和错误是

01-21 02:48:58.553: E/AndroidRuntime(1343): FATAL EXCEPTION: main 
01-21 02:48:58.553: E/AndroidRuntime(1343): Process:  com.example.serverlogin, PID: 1343 
01-21 02:48:58.553: E/AndroidRuntime(1343): java.lang.NullPointerException 
01-21 02:48:58.553: E/AndroidRuntime(1343):  at  com.example.serverlogin.DonorAdapter.getView(DonorAdapter.java:62) 

问题出在哪里请有人帮助我。我非常感谢所有人。我是Android新手。

回答

0
if(v==null) 
    { 
     holder = new ViewHolder(); 
     v = vi.inflate(Resource, null); 
     holder.imageview = (ImageView) v.findViewById(R.id.iv1); 
     holder.name = (TextView) v.findViewById(R.id.tv1); 
     holder.phoneNo = (TextView) v.findViewById(R.id.tv2); 
     holder.remark =(TextView) v.findViewById(R.id.tv3); 
     holder.id =(TextView) v.findViewById(R.id.tv4); 
     holder.location=(TextView) v.findViewById(R.id.tv5); 
     holder.officeLocation =(TextView) v.findViewById(R.id.tv6); 
     holder.officePhone =(TextView) v.findViewById(R.id.tv7); 
     holder.resPhone =(TextView) v.findViewById(R.id.tv8); 
     holder.cellPhone=(TextView) v.findViewById(R.id.tv9); 
     holder.email =(TextView) v.findViewById(R.id.tv10); 
     holder.birthdate =(TextView) v.findViewById(R.id.tv11); 
     holder.gender = (TextView) v.findViewById(R.id.tv12); 
     holder.lastBloodDonation=(TextView) v.findViewById(R.id.tv13); 

     v.setTag(holder); <==== add this line 
    } 
+0

谢谢.....错误消失 – user3651256 2015-01-21 08:19:22

+0

请upvote并标记为正确 – 2015-01-21 08:19:46