setting text in EditText causig app crash

3151 views android
1

I am programming app in Android Studio. I am taking json file from server, then extarcting it to strings and want to show in EditText to let it be modificable.

Here my code

 protected String doInBackground(String... atr) {
        new Thread(new Runnable() {
            public void run() {
                int success;
                try {
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("pid", pid));
                    params.add(new BasicNameValuePair("name", table_name));


                    JSONObject json = jsonParser.makeHttpRequest(url_product_details, "GET", params);
                    Log.d("Single Product Details", json.toString());

                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        JSONArray productObj = json.getJSONArray(TAG_PRODUCT);
                        JSONObject product = productObj.getJSONObject(0);

                        String _name = product.getString("name");
                        name.setText(_name, EditText.BufferType.EDITABLE);

                        if(!product.isNull("price")) {
                            Integer _price = product.getInt("price");
                            price.setText(_price, EditText.BufferType.EDITABLE);
                        }
                        if(!product.isNull("quantity")) {
                            Integer _quantity = product.getInt("quantity");
                            quantity.setText(_quantity, EditText.BufferType.EDITABLE);
                        }
                        if(!product.isNull("promotion")) {
                            Integer _promotion = product.getInt("promotion");
                            promotion.setText(_promotion, EditText.BufferType.EDITABLE);
                        }
                    } else {
                        Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                        i.putExtra(TAG_PID, pid);
                        i.putExtra("list_name", table_name);
                        startActivity(i);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return null;
    }

unfortunetly when i am trying like this app crashes when i try upload text to EditText. I confirmed that EditText isn't null, Strings too. There is no error message what impede this problem. Have anybody some idea? I looked everywhere (mayby i can't search xD) and didn't find anything resonable.

answered question

You can't do it in doInbackground() . You need to do it on onPostExecute() method

1 Answer

12

First thing, unwrap your code from that Thread. doInBackground() is already asynchronous, so there's it's redundant. Either use a Thread or an AsyncTask, not both.

Second thing, Views, such as EditText, can only be modified on the main or UI Thread. When you run setText(), or any other methods on View, it needs to be on the main Thread.

If this is inside an Activity, you can use:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //appropriate setText()
    }
});

Otherwise, you'll need to use a Handler. Create a global variable:

private Handler handler = new Handler(Looper.getMainLooper());

and instead of using runOnUiThread(), use handler.post(), with the same syntax (just replace runOnUiThread with handler.post).

However, there's also a third thing. You shouldn't really be handling your JSON String in the background. You should only be retrieving the String at that point. Your logic should go in onPostExecute(), which already executes on the main Thread for you.

Your code should look like this:

@Override
protected String doInBackground(String... atr) {
    try {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("pid", pid));
        params.add(new BasicNameValuePair("name", table_name));

        JSONObject json = jsonParser.makeHttpRequest(url_product_details, "GET", params);
        Log.d("Single Product Details", json.toString());

        int success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
            return json; //return the JSON String on success
        } else {
            Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
            i.putExtra(TAG_PID, pid);
            i.putExtra("list_name", table_name);
            startActivity(i);
            finish();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null; //return null for any other result
}

@Override
protected void onPostExecute(String result) {
    if (result != null) { //make sure result isn't null
        JSONArray productObj = result.getJSONArray(TAG_PRODUCT);
        JSONObject product = productObj.getJSONObject(0);

        String _name = product.getString("name");
        name.setText(_name, EditText.BufferType.EDITABLE);

        if (!product.isNull("price")) {
            Integer _price = product.getInt("price");
            price.setText(_price, EditText.BufferType.EDITABLE);
        }
        if (!product.isNull("quantity")) {
            Integer _quantity = product.getInt("quantity");
            quantity.setText(_quantity, EditText.BufferType.EDITABLE);
        }
        if (!product.isNull("promotion")) {
            Integer _promotion = product.getInt("promotion");
            promotion.setText(_promotion, EditText.BufferType.EDITABLE);
        }
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.