简体   繁体   中英

How to get php json_encode($array) in to android to manipulate it data?

How to get php json_encode($array) in to android to manipulate it data?

I have a php that encode a array in json_encode($array); and when i

echo json_encode($array);

i get:

[{"id":"1","name":"player1","score":"20","quarter":"Q - 1"},{"id":"2","name":"player2","score":"18","quarter":"http:\\/\\/localhost\\/win.jpg"}]

Now in android i want to get that array from the php and put it in a array that let me take for example from index 0 with the key name the string value that it contains and then set that string to a textView text. In iphone i only do this code:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

(data is my local url "http://localhost/my.php")

and then i can easy take the data from the dictionary with valueForKey:name and objectAtIndex:0 and put it string to a textfield.

Please complete code implementation in java so i can understand. Because i'm new in java and i'm losing my head with a lot of erros and hours trying to do this in different ways.

Thanks to the one that resolve my problem.

Receive the response to a string using org.apache.http.client.HttpClient.

HttpClient httpclient = new DefaultHttpClient();
try {
    HttpPost httppost = new HttpPost(this.getURL());
    // attach the request with post data
    List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
    pairs.add(new BasicNameValuePair("username", username)); 
    pairs.add(new BasicNameValuePair("password", password));        
    httppost.setEntity(new UrlEncodedFormEntity(pairs));
    //send request to server
    HttpResponse response = httpclient.execute(httppost);
    //trace response
    InputStream is = response.getEntity().getContent();
    //convert response to string
    BufferedReader myReader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
    StringBuilder sb = new StringBuilder();
    sb.append(myReader.readLine() + "\n");
    String line="";
    while ((line = myReader.readLine()) != null) {
        sb.append(line + "\n");
    }
    result = sb.toString();
} catch (Exception e) {
    e.printStackTrace();
}

Then you can use org.json.JSONObject or org.json.JSONArray.

JSONObject json_data= new JSONObject(result);
int userId = Integer.parseInt(json_data.getString("user_id"));
JSONArray arrJson = json_data.getJSONArray("data");

There are many third-party classes that make most of the jobs automatically. WE do not need to invent the wheel. easily use Retrofit or Volley. There working nicely in my project. They take care of many things on your behalf. define a class to package all properties of each player object in a sigle object and then use retrofit API: maybe following hint will help you:

public interface QuestionAPI {
    @GET("player.php")//you can call php file directly
    public void getFeed(Callback <List<PlayerObject>> playerobject);
}

This error happens because you are sending the json array without its name.

After you store json array do this:

echo json_encode(array('acdata'=>$acdata));



eg:
while($row = $stmt->fetch ()){
 $acdata[] = array(
     'acid' => $acid,
     'address' => $address,
     'companyname' => $companyname,
     'dateofpurchase' => $dateofpurchase,
     'ac_type' => $ac_type
);
}
header('Content-type: application/json');
echo json_encode(array('acdata'=>$acdata));

Then in android retrieve it by:

JSONObject jsonRootObject = new JSONObject(result);
JSONArray jsonArray = jsonRootObject.optJSONArray("acdata");
JSONObject jsonObject = jsonArray.getJSONObject(1);
name = jsonObject.optString("acid");

//acid is the name of the key in json

//put it in loop to get all the values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM