1

Hi I am a new programmer and I am trying to parse this output into my android listview, I have used php which is connected to mysql to produce this output :

{"id":"2","name":"Username : garrett","password":"Password : important"}{"id":"1","name":"Username : darrel","password":"Password : pass1234"}

I know there are quite a number of questions asked about this same topic, but I just can't seem to find the answer! really sorry if this is a simple question. Thanks in advance!

And here is my java code, its currently displaying my output into a textView. But only the first user.

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
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.json.JSONException;
import org.json.JSONObject;


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class Users extends Activity {
/** Called when the activity is first created. */

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
@Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

    }
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://172.30.54.153/databases/");
    TextView textView = (TextView)findViewById(R.id.textView1);
    TextView textView2 = (TextView)findViewById(R.id.textView2);

  try {

   HttpResponse response = httpclient.execute(httppost);
   String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
   JSONObject object = new JSONObject(jsonResult);

   String name = object.getString("name");
  String password = object.getString("password");
  textView.setText(name + " - " + password);

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


   }
private StringBuilder inputStreamToString(InputStream is) {
    String rLine = "";
    StringBuilder answer = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    try {
     while ((rLine = rd.readLine()) != null) {
      answer.append(rLine);
       }
    }

    catch (IOException e) {
        e.printStackTrace();
     }
    return answer;
   }
}

My PHP code.

 <?php 


 require 'connect.inc.php';

 $query = "SELECT `id` , `username`, `password` FROM `users` ORDER BY `id`";

 if ($query_run = mysql_query($query)) {

 while($query_row = mysql_fetch_assoc($query_run)) {
 $username = $query_row['username'];
 $password = $query_row ['password'];
 $id = $query_row ['id'];
 //echo $username .'`s password is : '. $password.'<br>';
 $data = array('id'=>$id , 'name'=> 'Username : '. $username ,'password'=>'Password : '.$password);
 print(json_encode($data));
 //print(json_encode($password));
 }


 }else{
 echo mysql_error();
 }

 ?>
Darrel
  • 56
  • 1
  • 2
  • 8
  • your json is not correct, it should have been like this [ { "id": "2", "name": "Username : garrett", "password": "Password : important" }, { "id": "1", "name": "Username : darrel", "password": "Password : pass1234" } ] – Naveen Mar 22 '13 at 03:41
  • hi may i know how i can get the square brackets and commas? my php code is this if ($query_run = mysql_query($query)) { while($query_row = mysql_fetch_assoc($query_run)) { $username = $query_row['username']; $password = $query_row ['password']; $id = $query_row ['id']; //echo $username .'`s password is : '. $password.'
    '; $data = array('id'=>$id , 'name'=> 'Username : '. $username ,'password'=>'Password : '. $password); print(json_encode($data)); //print(json_encode($password)); } }else{ echo mysql_error(); } ?>
    – Darrel Mar 22 '13 at 06:13
  • this is unreadable, add it to your question – Naveen Mar 22 '13 at 06:14
  • oops sorry, okay I've added it in – Darrel Mar 22 '13 at 06:22

2 Answers2

1

Return an json array of objects from your server. Change this

JSONObject object = new JSONObject(jsonResult);

to this

JSONArray objects = new JSONArray(jsonResult);

then iterate the jsonArray and build a jsonObject for each array item

for (int i = 0; i < objects.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);

    // do something here

}
gpasci
  • 1,420
  • 11
  • 16
1

php

$final_data = array();    
if ($query_run = mysql_query($query)) 
    { 
        $i=0;
        while($query_row = mysql_fetch_assoc($query_run)) 
        { 
            $username = $query_row['username']; 
            $password = $query_row ['password']; 
            $id = $query_row ['id']; 
            //echo $username .'`s password is : '. $password.'<br>'; 
            $data = array('id'=>$id , 'name'=> 'Username : '. $username ,'password'=>'Password : '. $password); 
            $final[$i]=$data;
            $i++;
            //print(json_encode($data)); 
            //print(json_encode($password)); 
        } 
        print(json_encode($final_data));
    }else{
     echo mysql_error(); 
    }

java part

String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONArray mArray = new JSONArray(jsonResult);
for (int i = 0; i < mArray.length(); i++) {
    JSONObject object = mArray.getJSONObject(i);

    String name = object.getString("name");
    String password = object.getString("password");
    textView.setText(name + " - " + password);
}
Naveen
  • 1,703
  • 13
  • 22
  • thanks so much for the code, i managed to get my php part right, so that the output is in correct json format, but as for the java part, im getting the last row in my sql table into my textview, do you know how I can populate a listview with all this data now instead of using a textview? – Darrel Mar 22 '13 at 06:55
  • http://www.mkyong.com/android/android-listview-example/ This is a very simple example of how to use a list view. Try to implement it. It you get any problem then you can always post another question in SO. – Naveen Mar 22 '13 at 07:12
  • hi just like to check if php can be used to connect to msSql the same way it connects to mySql? – Darrel Mar 27 '13 at 01:06
  • I have never done it but http://php.net/manual/en/function.mssql-connect.php might help – Naveen Mar 28 '13 at 02:47