I created an array with PHP. I need help how to read it, with Android app.
Encoded array looks like this:
["id","string 1","string 2","string 3","string 3","string 4"]
I have to be able to read all of it's elements, with Android application.
It's created with PHP with code like next:
$res = array();
$res[] = $data['id'];
$res[] = $data['string 1'];
$res[] = $data['string 2'];
$res[] = $data['string 3'];
$res[] = $data['string 4'];
return json_encode($res);
Can you please help me how to solve this?
For your example, you can use the following code to parse the response in Android. I have hardcoded the response that you are getting in the code, so you get the idea. Also I have written it in onCreate of my activity, you may write this wherever is suitable for your app.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String strJson="[\"id\",\"string 1\",\"string 2\",\"string 3\",\"string 3\",\"string 4\"]"; // This is your response, with escaped " and used as a String
try {
//Get the instance of JSONArray that contains Strings
JSONArray jsonArray = new JSONArray(strJson);
for(int i=0; i < jsonArray.length(); i++){
String data = (String)jsonArray.get(i);
Log.d("MyData",data);
}
} catch (JSONException e) {e.printStackTrace(); // Not a good idea. But left it for now}
}
If you monitor the logcat with filter MyData you will find the output as:
D/DATAIS: id
D/DATAIS: string 1
D/DATAIS: string 2
D/DATAIS: string 3
D/DATAIS: string 3
D/DATAIS: string 4
There are a lot of tutorials in web that deals with how to parse JSON in Android. You can study them to get a better idea.
I solved it, when I added names to elements of PHP array:
$res = array();
$res[0] = $data['id'];
$res[1] = $data['string 1'];
$res[2] = $data['string 2'];
$res[3] = $data['string 3'];
$res[4] = $data['string 4'];
And on Android side:
JSONObject mainObject = new JSONObject(ret);
String str1 = mainObject.optString("1").toString();
String str2 = mainObject.optString("2").toString();
String str3 = mainObject.optString("3").toString();
String str4 = mainObject.optString("4").toString();
Thank you all on help.