muthana1990 muthana1990 - 5 months ago 12
JSON Question

Passing JSON data to the main activity

I am trying to connect my app to Mysql database using JSON and Php. The Php script return 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) {

}
}
}

Answer

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, its a bad practice)

Comments