0

I am trying to connect my app to Mysql database using JSON and PHP. The PHP script returns a JSON array which determine the status of the light (true or false).

I tried to put the JSON code, which open the URL connection and get the status,in separate class. As a result, I can call it whenever I need to use it.

The problem is that the variable res does have a value inside the JSON class but when I tried to access it from the main Activity using JSON object, it is empty. Can any one direct me to the right solution to solve this problem?

Main activity

public class MainActivity extends AppCompatActivity {
public TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  t = (TextView) findViewById(R.id.t1);
  Json j = new Json();
  j.execute("http://127.0.0.1/web/test.php");
  t.setText(j.res);
 }
}

Json class

public class Json extends AsyncTask<String, String, String> {
String result = "";

public String res="";

@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
    InputStream isr = null;
    try {
        String URL = params[0];
        java.net.URL url = new URL(URL);
        URLConnection urlConnection = url.openConnection();
        isr = new BufferedInputStream(urlConnection.getInputStream());
    } catch (Exception e) {
        Log.e("log_tag", "error in http conection" + e.toString());
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");

        }
        isr.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("Log", "failed " + e.toString());
    }
    return null;
}

JSONObject json;
protected void onPostExecute(String result2) {

    try {

        String password1 = "";
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
            json = jArray.getJSONObject(i);
            res=json.getString("status");

            break;
        }
    } catch (Exception e) {

    }
  }
}
3
  • t.setText(j.res); is happening before Async Task completes execution. All UI manipulation should happen through onPostExecute Jun 16, 2016 at 13:42
  • @muthana1990 yes you should do that and not return null in doinback ground as shown in my answer Jun 16, 2016 at 13:46
  • i have updated my ans, if that makes sense. Jun 16, 2016 at 13:50

2 Answers 2

0

You cannot return value from an AsyncTask to main thread like that. There are 2 possible solutions

1) Make your text view as a global variable and in you AsyncTask override onPostExecute(). Inside your post execute you can update your text view with data from server.

2) make a listener (interface). Your activity should implement it and again override onPostExecute() and call that listener with the json data, finally in your callback update your views with data from json.

protected void onPostExecute(String result2) {
    try {
        String password1 = "";
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
            json = jArray.getJSONObject(i);
            res=json.getString("status");
            break;
        }
        // UPDATE your views here, or make a callback to your class
        // via a listener and json data as a parameter and update 
        // your views there. Async tasks can cause memory leaks. 
        // Be careful with them.
    } catch (Exception e) {
    }
}

Hope it helps.

(PS - Just a tip, dont catch generic exceptions, it's a bad practice)

Also, you can pass a string from doInBackground to onPostExecute which is decided on the 3rd parameter of your AsyncTask<String, String, String>. so since you are telling it that the object be of String type you can return null; replace null with a String generated in your doInBackground call.

public class Json extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... params) {
        InputStream isr = null;
        String result;
        try {
            String URL = params[0];
            java.net.URL url = new URL(URL);
            URLConnection urlConnection = url.openConnection();
            isr = new BufferedInputStream(urlConnection.getInputStream());
        } catch (Exception e) {
            Log.e("log_tag", "error in http conection" + e.toString());
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");

            }
            isr.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("Log", "failed " + e.toString());
        }
        return result;
    }

    JSONObject json;
    protected void onPostExecute(String result) {
        try {
            String password1 = "";
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                json = jArray.getJSONObject(i);
                res=json.getString("status");

                break;
            }
        } catch (JSONArrayException ignored) {
        }
    }
}

I did not run this code. Maybe you can check and verify!

2
  • I tried to use the first solution and I declared the textView as global variable but it does not suggest when I tried to use it inside onPostExecute().
    – jack
    Jun 16, 2016 at 14:15
  • so the catch is, you can use 1 if your AsyncTask is an inner class and 2 if its a different file.. stackoverflow.com/questions/9963691/… try this out, it will be fun Jun 16, 2016 at 14:30
0

execution is in another thread and it may be execute the line t.setText(j.res); before executing the request if you want to use the result in the activity you cand override onpostExecute in the activity not in the Json class as following :

new Json(){
@Override
protected void onPostExecute(String result2) {
//use string result as you want here   
}
}.execute("http://127.0.0.1/web/test.php");

and return your result in doInBackGround . not return null

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.