2017-08-28 6 views
1

Tout va bien avec ce code mais parfois il ajoute des données à listview, parfois non. S'il te plaît, dis-moi ce qui me manque. Je l'ai essayé dans différents projets. Toujours le même résultat. fonctionne parfois, parfois non. Y at-il un autre moyen de se connecter facilement avec le serveur. J'ai commencé la programmation Android il y a quelques semaines.Volley va chercher des données mais parfois il affiche des données dans listview, parfois non

private List<product> productFeed= new ArrayList<product>(); 

double qty = 0; 
double item_sub_total = 0; 
double item_price = 0; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 







    RequestQueue queue = Volley.newRequestQueue(this); 

    // Toast.makeText(getApplicationContext(), "After Request Q", Toast.LENGTH_SHORT).show(); 
    Log.i("Error","Before try"); 
    JsonObjectRequest myReq = new JsonObjectRequest(Request.Method.GET, 
      "http://localhost/product.php", null, new Response.Listener<JSONObject>() { 
     @Override 
     public void onResponse(JSONObject response) { 

      try { 
       Log.i("Error","In try"); 
       // Toast.makeText(getApplicationContext(),"In Try",Toast.LENGTH_SHORT).show(); 

       JSONArray productList = response.getJSONArray("products"); 
       //Toast.makeText(getApplicationContext()," Try 1",Toast.LENGTH_SHORT).show(); 

       Log.i("Error", String.valueOf(productList.length())); 
       //Toast.makeText(getApplicationContext(),productList.length(),Toast.LENGTH_SHORT).show(); 
       for (int i = 0; i < productList.length(); i++) { 
        JSONObject temp = productList.getJSONObject(i); 

        String name = temp.getString("name"); 
        Double price = temp.getDouble("price"); 
        String imageURL = temp.getString("image"); 
        Log.i("Product", name); 
        productFeed.add(new product(name,price,imageURL)); 
        // Toast.makeText(getApplicationContext(),"3.1",Toast.LENGTH_SHORT).show(); 

        // Log.i("Error",name); 

       } 

      } catch (JSONException e) { 
       Log.i("Error","In Catch"); 
       Toast.makeText(getApplicationContext(),"In Catch",Toast.LENGTH_SHORT).show(); 
       e.printStackTrace(); 
      } 
     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      Log.i("Error", error.toString()); 
     } 
    }); 
    //Toast.makeText(getApplicationContext(),"Before My Req",Toast.LENGTH_SHORT).show(); 

    myReq.setRetryPolicy(new DefaultRetryPolicy(1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 

    queue.add(myReq); 
    Log.i("Error","2"); 

    ArrayAdapter<product> adapter = new customAdapter(); 

    ListView myFirstListView = (ListView) (findViewById(R.id.productList)); 

    myFirstListView.setAdapter(adapter); 
    Log.i("Error","3"); 
    myFirstListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { 

      product currentItem = productFeed.get(position); 

     } 
    }); 

} 

    class customAdapter extends ArrayAdapter<product> 
    { 
     public customAdapter() { 
      super(MainActivity.this, R.layout.item,productFeed); 
     } 


     @Override 
     public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) { 
      Log.i("Error","4"); 
      if (convertView == null) 
       convertView = getLayoutInflater().inflate(R.layout.item,parent,false); 

      final product currentItem = productFeed.get(position); 
      ImageView add = (ImageView) convertView.findViewById(R.id.add); 
      ImageView minus = (ImageView) convertView.findViewById(R.id.minus); 
      ImageView addtocart = (ImageView)convertView.findViewById(R.id.addtocart); 
      ImageView productImage = (ImageView)convertView.findViewById(R.id.productImage); 

      final TextView product = (TextView)convertView.findViewById(R.id.product); 
      final TextView price = (TextView)convertView.findViewById(R.id.price); 
      final TextView subtotal = (TextView)convertView.findViewById(R.id.sub_total); 
      final TextView quantity = (TextView)convertView.findViewById(R.id.quantity); 
      //final long qty[]=new long[position]; 
      /* for(int j=0;j<qty.length;j++) 
      { 
       qty[j]=0; 
       Log.i("Array", String.valueOf(qty[j])); 
      } 
      // Toast.makeText(getApplicationContext(),String.valueOf(qty.length), Toast.LENGTH_SHORT).show(); 
      */ //Log.i("Length",String.valueOf(qty.length)); 
      add.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        String q= (String) quantity.getText(); 
        Double d = Double.parseDouble(q); 
        qty=d; 
        qty++; 
        // Toast.makeText(getApplicationContext(),String.valueOf(position),Toast.LENGTH_SHORT).show(); 
        Double sub_total =currentItem.getPrice(); 


        // Log.i("Error",) 
        item_sub_total = qty*sub_total; 
        quantity.setText(String.valueOf(qty)); 
        subtotal.setText(String.valueOf(item_sub_total)); 
       } 
      }); 

      minus.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        String q= (String) quantity.getText(); 
        Double d = Double.parseDouble(q); 
        qty=d; 

        if(qty !=0) 
        { 

         double sub_total =currentItem.getPrice(); 
         qty--; 
         item_sub_total = qty*sub_total; 
         quantity.setText(String.valueOf(qty)); 
         subtotal.setText(String.valueOf(item_sub_total)); 

        } 

       } 
      }); 
      addtocart.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        Toast.makeText(getApplicationContext(),currentItem.getImageURL(),Toast.LENGTH_SHORT).show(); 
       } 
      }); 


      product.setText(currentItem.getName()); 
      price.setText(String.valueOf(currentItem.getPrice())); 
      quantity.setText("0"); 
      subtotal.setText(""); 
     //  productImage.setImageResource(currentItem.getImageID()); 
      // Toast.makeText(MainActivity.this,currentItem.getImageURL().toString(),Toast.LENGTH_SHORT).show(); 
      //Log.i("image",currentItem.getImageURL()); 
      Picasso.with(MainActivity.this).load(currentItem.getImageURL()).into(productImage); 
      //ImageRequest imageRequest = new ImageRequest(currentItem.imageURL); 
      return convertView; 

     } 


    } 

} 

Répondre

1

Une fois que vous ajoutez des éléments à vous productFeed devez appeler:

adapter.notifyDataSetChanged(); 
0

Le problème semble être que vous ne savez pas si l'analyse syntaxique est complètement terminé.
Comme myFirstListView.setAdapter(adapter); est en dehors de la méthode
onResponse(JSONObject response). Donc, vous ne savez pas si vous liste est vide ou plein lorsque vous appelez myFirstListView.setAdapter(adapter);

Raison:

Les deux parcours dans différents fil donc il y a des chances que vous appelez myFirstListView.setAdapter(adapter) avant même l'ensemble l'analyse est effectuée. C'est pourquoi vous ne voyez parfois aucun résultat dans votre liste.

Solution

1) Il existe deux solutions méthode soit déplacer myFirstListView.setAdapter (adaptateur) à l'intérieur onResponse().
2) Ou vous envoyez un message de diffusion lorsque l'analyse est terminée. Et recevoir des messages de diffusion et définir l'adaptateur à l'intérieur de la méthode onReceive() d'un récepteur.
(Cette approche aidera à l'avenir même si vous avez une disposition pas seulement une liste)