Alex Bond Alex Bond - 1 month ago 8
Android Question

How to pass a variable from JSONArray

I have code that receives a variable from an external JSON array

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.Toast;

public class ListviewActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

String json_str = getJsonData();

try{
JSONArray jArray = new JSONArray(json_str);

JSONObject json = null;
json = jArray.getJSONObject(0);

String date=json.getString("data");

Toast.makeText(getBaseContext(), date, Toast.LENGTH_SHORT).show();

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

}

private String getJsonData(){
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());

String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("url_php_file_with_JSON");

try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return str;
}
}

//comparison variable (from String date=json.getString("data")) with an other static variable


How to correctly display variable String date = json.getString ( "data") for comparison in other functions?

While it is displayed in the function receiving a variable using Toast.makeText, and I have to work with it in other areas of the java file

Answer

You need to make your String a global variable, like follows:

public class ListviewActivity extends Activity {

    private String date;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        String json_str = getJsonData();

        try{
            JSONArray jArray = new JSONArray(json_str);

                JSONObject json = null;
                json = jArray.getJSONObject(0);

               date=json.getString("data");

            Toast.makeText(getBaseContext(), date, Toast.LENGTH_SHORT).show();

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

    }

    // The rest of your code
}

That way, you can use it freely anywhere in your class.