php - 更新 ui 线程内表格布局的 TextView 时出现问题

标签 php android mysql android-tablelayout

我有一个应用程序,我在其中从服务器获取数据并相应地更新 View 。 我的代码如下:

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;
    }

}

getorderdetails.php 以 json 格式返回以下数据:

 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"}]

问题是现在相同的数据在表格布局中重复。

enter image description here

即产品名称 atta 在表格布局中重复。

当我在 runOnUiThread() 函数之前打印产品名称时,它会打印不同的名称,但是当我在 runOnUiThread() 中获取产品名称时,我会得到相同的结果。

如何在ui线程内使表格布局的textview清晰?

最佳答案

为什么需要将代码放在线程内。您只需在这里设置值即可。

 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);
                    }
                });
<小时/>

线程内的代码是独立执行的,相反,指针向前移动,递增 i 的值,直到 labelproductname.setText(productname); 这行代码执行,我们得到下一个 Json 对象值: “阿塔”。 使用调试器来了解您的代码所遵循的流程。您的循环正在执行,而您的可运行线程稍后执行,因此最后保存在字符串产品名和其他值中的值已设置。
作为解决方案,只需放置

<小时/>
 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);
                   /* }
                });*/

            }

希望这能满足您的需求。

enter image description here

关于php - 更新 ui 线程内表格布局的 TextView 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24950177/

相关文章:

php - 尽快启动并运行高级 PHP?

php - Zend_Http_Client SSL 异常

javascript - 如何在谷歌地图上显示方向后隐藏其他标记

android - 用户输入数据后立即验证 EditText 内容

android - LocalBroadcastManager 是否按照事件发送的顺序传递事件?

java - 从主表实体引用主数据实体的外键列数错误

mysql - 如何根据返回值执行不同的查询?

php - 如何判断变量是否为空?

android - 如何在 Android 中禁用 RecyclerView 项目?

mysql - 从数据库中获取最近一年的数据