Question

I am facing a problem in my adapter when i try to set the text of the TextView after retrieving the data from mySQL, Doinbackground() + jsonParsing is successful

when it enters onPostexecute, i try to set the text of the price to "any thing" it shows a null pointer exception there.

if I comment the price.setText("anything"); the app will run normal and i get 2 json object instances from the URL and create two objects in my listview but of course with none of the retrieved data.

This is also happening with all TextViews setText() .

Code is here:

     public class Search extends Activity  {
 public static  String IP=Mysynch.IP;
static String url="http://"+IP+":80/senior/getStoreItemtoJson.php";
 String Scatid; 
String Sitemid;
String Suserid;
String Sdescription;
String Sprice;
String Squantity;
String Showmanyorders;
String Sprocessingtime;
String Sdeliverytime;
String Sdateadded;
String Sbrand;
String Ssale;
String Sbrandnew;
String Ssecondhand;
Activity activity;
List<Itemclass> list=new ArrayList<Itemclass>();
TextView  price;


TextView  desc;
TextView  quantity;


 ListView listview;
ViewGroup viewgroup;
Itemclass itemclass;Itemclass currentitem ;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    System.out.println(url);
    setContentView(R.layout.search);


        (new myAsynctask()).execute();

        System.out.println("Create");
       }



         public class myAsynctask extends AsyncTask<String, Void, Boolean>
      {
protected void onPreExecute()
{
    System.out.println("pre");
}

protected Boolean  doInBackground(final String... args) {
    System.out.println("Enter background");
    //this client handles the download and upload of the info
         DefaultHttpClient httpclient=new DefaultHttpClient(new BasicHttpParams());
         // Here we pass the url 
         HttpPost httppost=new HttpPost(url);
         httppost.setHeader("Content-type","application/json");
         InputStream inputstream=null;
         String result=null;

         try{
        HttpResponse response=httpclient.execute(httppost);  
        HttpEntity entity=response.getEntity();
        inputstream=entity.getContent();
        BufferedReader reader=new BufferedReader(new InputStreamReader(inputstream,"UTF-                 8"),8);
        StringBuilder Sbuilder=new StringBuilder();
        String line=null;
        while((line=reader.readLine())!=null){
            Sbuilder.append(line+'\n');
        }
             result=Sbuilder.toString();


         }

         catch(Exception e){
             e.printStackTrace();

         }finally{
             try{if(inputstream !=null )
            inputstream.close();     

             }
             catch(Exception e){
                 e.printStackTrace();
             }
         };
         System.out.println("finish conx + json");

         JSONArray jsonArray;
         try{
             //jibit awal json object ili howi b2albo kil shi
             JSONObject jsonobj=new JSONObject(result); 
           // String s= jsonobj.getString("success");
             //System.out.println(s);
           //String e=  jsonobj.getString("error");
           //System.out.println(e);
           jsonArray=jsonobj.getJSONArray("item");
             //how to get all objects into a json array
            // query array fiya kil el names ta3on el quote object eli jibti fo2
            //create a list
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonline=jsonArray.getJSONObject(i);
                Scatid=jsonline.getString("catid");
                Sitemid=jsonline.getString("itemid");
                Suserid=jsonline.getString("userid");
                Sdescription=jsonline.getString("description");
                Sprice=jsonline.getString("price");
                Squantity=jsonline.getString("quantity");
                Showmanyorders=jsonline.getString("howmanyorders");
                Sprocessingtime=jsonline.getString("processingtime");
                Sdeliverytime=jsonline.getString("deliverytime");
                Sdateadded=jsonline.getString("dateadded");
                Sbrand=jsonline.getString("brand");
                Ssale=jsonline.getString("sale");
                Sbrandnew=jsonline.getString("brandnew");
                Ssecondhand=jsonline.getString("secondhand");


            Itemclass item=new Itemclass(Scatid, Sitemid, Suserid, Sdescription, Sprice,      Squantity, Showmanyorders, 
                    Sprocessingtime, Sdeliverytime, Sdateadded, Sbrand, Ssale, Sbrandnew, Ssecondhand);
            list.add(item);
            System.out.println("*******"+Sprice);
            }

         }catch(JSONException e ){
             e.printStackTrace();
         }
         System.out.println("*****************************************");
    return true;

}

protected void onPostExecute(final Boolean success)
{


    System.out.print("enter post");
    if(success){
        System.out.print(" enter initialize list"); 
        listview=(ListView)findViewById(R.id.listView1);
        ArrayAdapter<Itemclass> adapter = new MyListAdapter();

        listview.setAdapter(adapter);
        System.out.print("initialize list");        }
}
    }

              private class MyListAdapter extends ArrayAdapter<Itemclass> {
public MyListAdapter() {
    super(Search.this, R.layout.searchlistitems, list);
}

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

    // Make sure we have a view to work with (may have been given null)
    View itemView = convertView;
    if (itemView == null) {


            itemView   =getLayoutInflater().inflate(R.layout.searchlistitems,
           parent, false);


         }

    currentitem = list.get(position);
    price=(TextView)findViewById(R.id.tvSearchprice);
    desc=(TextView)findViewById(R.id.tvsearchDescr);
    quantity=(TextView)findViewById(R.id.tvSearchquantity);

    System.out.println("position===>>>>"+position);
// price.setText("any thing");//<======== my problem is here


    // Fill the view
//ImageView imageView = (ImageView)itemView.findViewById(R.id.item_icon);
//imageView.setImageResource(currentCar.getIconID());





//desc.setText(currentitem.description);

    //      quantity.setText(currentitem.quantity);

           System.out.println("desc===>>>>"+currentitem.description);
    return itemView;
}               
     }


         }
Was it helpful?

Solution

As you inflate a layout in getView method with this:

itemView = getLayoutInflater().inflate(R.layout.searchlistitems, parent, false);

you use this inflated view to retrieve your child views as follows:

price = (TextView) itemView.findViewById(R.id.tvSearchprice); // use itemView
desc = (TextView) itemView.findViewById(R.id.tvsearchDescr);
quantity = (TextView) itemView.findViewById(R.id.tvSearchquantity);  

However, I'd suggest you to use a ViewHolder pattern to have better performance for your adapter. Here is a great topic: Performance Tips for Android’s ListView and a simple tutorial: Android ViewHolder Pattern Example. It will avoid the frequent call of findViewById() during the ListView scrolling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top