-1

I have a application in which i am fetching data from server and updating the view accordingly. My code is as follows:

public class NotificationActivity extends Activity{
    String userid;
    String ordernumber; 
    TextView txtLabelOrderNumber;
    TextView txtLabelAmountReceived;
    TextView txtLabelDeliveredBy;
    String amountreceived;
    String orderno;
    String deliveredby;
    String productname;
    String brand;
    String quantity;
    String price;
    TableLayout table_layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);
        Intent intent = getIntent(); 
        Bundle extras = intent.getExtras(); 
        JSONObject json;
        txtLabelOrderNumber = (TextView)findViewById(R.id.txtLabelOrderNumber);
        txtLabelAmountReceived = (TextView)findViewById(R.id.txtLabelAmountReceived);
        txtLabelDeliveredBy = (TextView)findViewById(R.id.txtLabelDeliveredBy);
        table_layout = (TableLayout) findViewById(R.id.tableLayout1);
        TableRow tr_head = new TableRow(this);
        tr_head.setId(10);
        tr_head.setBackgroundColor(Color.GRAY);
        tr_head.setLayoutParams(new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));

        TextView label_productname = new TextView(this);
        label_productname.setText("Name");
        label_productname.setTextColor(Color.WHITE);
        label_productname.setPadding(5, 5, 5, 5);
        tr_head.addView(label_productname);// add the column to the table row here

        TextView label_brand = new TextView(this);
        label_brand.setText("Brand"); // set the text for the header 
        label_brand.setTextColor(Color.WHITE); // set the color
        label_brand.setPadding(5, 5, 5, 5); // set the padding (if required)
        tr_head.addView(label_brand); // add the column to the table row here

        TextView label_quantity = new TextView(this);
        label_quantity.setText("Qty"); // set the text for the header 
        label_quantity.setTextColor(Color.WHITE); // set the color
        label_quantity.setPadding(5, 5, 5, 5); // set the padding (if required)
        tr_head.addView(label_quantity); // add the column to the table row here

        TextView label_amount = new TextView(this);
        label_amount.setText("Amount"); // set the text for the header 
        label_amount.setTextColor(Color.WHITE); // set the color
        label_amount.setPadding(5, 5, 5, 5); // set the padding (if required)
        tr_head.addView(label_amount); // add the column to the table row here
        table_layout.addView(tr_head);

        try {
            json = new JSONObject(extras.getString( "com.parse.Data" ));
            Iterator itr = json.keys();
            while (itr.hasNext()) {
                String key = (String) itr.next();
                if(key.equals("ordernumber"))
                {   
                    ordernumber = json.getString(key);
                    Toast.makeText(getApplicationContext(), "key:"+json.getString(key), Toast.LENGTH_LONG).show();
                    Thread thread = new Thread(new Runnable(){
                        @Override
                        public void run() {
                            try {
                                getOrderDetails(ordernumber);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });

                    thread.start(); 

                }
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }

    private void getOrderDetails(String ordernumber)
    {   

        String result="";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://example.comy/getorderdetails.php");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("ordernumber", ordernumber));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            result=inputStreamToString(response.getEntity().getContent()).toString();
            System.out.println("result: "+result);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try{
            JSONArray jArray = new JSONArray(result);

            for(int i=0;i<jArray.length();i++){
                final TableRow row = new TableRow(this);
                final TextView labelproductname = new TextView(this);
                final TextView labelquantity = new TextView(this);
                final TextView labelbrand = new TextView(this);
                final TextView labelprice = new TextView(this);
                JSONObject json_data = jArray.getJSONObject(i);
                amountreceived =json_data.getString("amountreceived");
                orderno =json_data.getString("ordernumber");
                deliveredby =json_data.getString("deliveredby");
                productname =json_data.getString("productname");
                brand =json_data.getString("brand");
                quantity =json_data.getString("quantity");
                price =json_data.getString("price");
                System.out.println("amountreceived: "+amountreceived);
                if(i==0)
                {   
                    runOnUiThread(new Runnable() {
                        public void run() {

                            txtLabelOrderNumber.append(" "+orderno);
                            txtLabelAmountReceived.append(" "+amountreceived);
                            txtLabelDeliveredBy.append(" "+deliveredby);

                        }
                    });
                }
                runOnUiThread(new Runnable() {
                    public void run() {


                        row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                                LayoutParams.WRAP_CONTENT));
                        labelproductname.setText(productname);
                        labelproductname.setPadding(2, 0, 5, 0);
                        row.addView(labelproductname);
                        labelbrand.setText(brand);
                        labelbrand.setPadding(2, 0, 5, 0);
                        row.addView(labelbrand);    
                        labelquantity.setText(quantity);
                        labelquantity.setPadding(2, 0, 5, 0);
                        row.addView(labelquantity);
                        labelprice.setText(price);
                        labelprice.setPadding(2, 0, 5, 0);
                        row.addView(labelprice);
                        table_layout.addView(row);
                    }
                });

            }

        }catch(JSONException e){
            e.printStackTrace();
        }

    }
    private StringBuilder inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();

        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) { 
                total.append(line); 
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Return full string
        return total;
    }

}

The getorderdetails.php returns the following data in json format:

 result: [{"amount":"400","ordernumber":"1-20140715171341","amountreceived":"400","deliveredby":"alok","productname":"biscuit","brand":"parle","quantity":"20","price":"200"},{"amount":"400","ordernumber":"1-20140715171341","amountreceived":"400","deliveredby":"alok","productname":"atta","brand":"pilsbury","quantity":"1","price":"200"}]

The problem is that right now same data gets repeated in table layout.

enter image description here

That is productname atta is repeated in table layout.

When i print the productname before runOnUiThread() function it prints distinct name but when i fetch the productname inside runOnUiThread() i get the same result.

How to make the textview of table layout distinct inside ui thread?

Illegal Argument
  • 10,090
  • 2
  • 44
  • 61
Pankaj Khurana
  • 3,243
  • 10
  • 50
  • 79

1 Answers1

0

Why do you need to put the code inside the thread. you are just setting the value here.

 if(i==0)
                {   
                    runOnUiThread(new Runnable() {//why are you using this
                        public void run() {

                            txtLabelOrderNumber.append(" "+orderno);
                            txtLabelAmountReceived.append(" "+amountreceived);
                            txtLabelDeliveredBy.append(" "+deliveredby);

                        }
                    });
                }
                runOnUiThread(new Runnable() {//why are you using this
                    public void run() {


                        row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                                LayoutParams.WRAP_CONTENT));
                        labelproductname.setText(productname);
                        labelproductname.setPadding(2, 0, 5, 0);
                        row.addView(labelproductname);
                        labelbrand.setText(brand);
                        labelbrand.setPadding(2, 0, 5, 0);
                        row.addView(labelbrand);    
                        labelquantity.setText(quantity);
                        labelquantity.setPadding(2, 0, 5, 0);
                        row.addView(labelquantity);
                        labelprice.setText(price);
                        labelprice.setPadding(2, 0, 5, 0);
                        row.addView(labelprice);
                        table_layout.addView(row);
                    }
                });

The code inside the thread is executed independently on the contrary the pointer moves ahead incrementing the value of i and till labelproductname.setText(productname); this line executes we have the next Json object value as "atta". Use debugger to understand the flow your code is following.. Your loop is getting executed while your runnable threads execute later so last saved value in string productname and other is set.
As an solution just put


 if(i==0)
                {   
                  /*  runOnUiThread(new Runnable() {
                        public void run() {*/

                            txtLabelOrderNumber.append(" "+orderno);
                            txtLabelAmountReceived.append(" "+amountreceived);
                            txtLabelDeliveredBy.append(" "+deliveredby);

                  /*      }
                    });*/
                }
             /*   runOnUiThread(new Runnable() {
                    @SuppressLint("NewApi") public void run() {

*/
                        row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                                LayoutParams.WRAP_CONTENT));
                        labelproductname.setText(productname);
                        labelproductname.setPadding(2, 0, 5, 0);
                        row.addView(labelproductname);
                        labelbrand.setText(brand);
                        labelbrand.setPadding(2, 0, 5, 0);
                        row.addView(labelbrand);    
                        labelquantity.setText(quantity);
                        labelquantity.setPadding(2, 0, 5, 0);
                        row.addView(labelquantity);
                        labelprice.setText(price);
                        labelprice.setPadding(2, 0, 5, 0);
                        row.addView(labelprice);
                        table_layout.addView(row);
                   /* }
                });*/

            }

Hope this satisfies with what you are looking for.

enter image description here

MOSO
  • 393
  • 2
  • 9
  • Thanks moso for replying. The reason for putting the code inside ui thread was that i was getting following error: Only the original thread that created a view hierarchy can touch its views and after searching for the issue found out that it can be resolved by putting the code inside ui thread. I agree with you that loop is getting executed while runnable threads execute later. I am working on resolving this. – Pankaj Khurana Jul 25 '14 at 09:56
  • I've tested at my end its working fine here at my side. I've hardcoded you result json and ran the code and got the result. Check my edit – MOSO Jul 25 '14 at 10:02
  • Hey did you got your problem solved? Understood the problem you were facing. Did a small work around if you need let me know i'll edit my post @PankajKhurana – MOSO Jul 25 '14 at 12:59
  • Yes i found out a workaround to resolve this. I will post the answer later. – Pankaj Khurana Jul 25 '14 at 16:38