0

how r u

I need to access a database and read data from a table then get the values of it so I create a php file to print a database in JSON format to access data:

<?php
try{
    $db=new PDO('mysql:host=localhost;dbname='database','table','password');
    $row=$db->prepare('select * from users' );
    $row->execute();
    $json_data=array();
    foreach($row as $rec)
    {
        $json_array['userId']=$rec['userId'];
        $json_array['user']=$rec['user'];
        $json_array['pass']=$rec['pass'];
        $json_array['name']=$rec['name'];
        $json_array['family']=$rec['family'];
        $json_array['gender']=$rec['gender'];
        $json_array['birthday']=$rec['birthday'];

        array_push($json_data,$json_array);
    }
    echo json_encode($json_data);
} catch(PDOExcetion $e)
{
    print "Error: " . $e->getMessage()."<br/>";
    die();
}
?>

and this is the output:

[
    {"userId":"1","user":"saly","pass":"666","name":"SalyR","family":"manson","gender":"male","birthday":"1988\/11\/10"},
    {"userId":"1","user":"foo","pass":"2657","name":"foo","family":"rocki","gender":"male","birthday":"13989\/2\/07"},
    {"userId":"1","user":"mil","pass":"63495","name":"milo","family":"toufa","gender":"male","birthday":"13987\/04\/21"},
    {"userId":"1","user":"soos","pass":"03468","name":"soro","family":"radi","gender":"female","birthday":"13990\/08\/09"}
]

I wanna get access to specified value like 'userId' and 'name' and 'birthday'.

I use three methods to get values:

1) getJSONFromDatabase method gets a database URL and returns an JSON String.

public String getJSONFromDatabase(String getDatabaseURL) {
        HttpClient client = new DefaultHttpClient();
        HttpPost method = new HttpPost(getDatabaseURL);
        String result = "";

        try {
            HttpResponse response = client.execute(method);
            int code = response.getStatusLine().getStatusCode();
            InputStream stream = response.getEntity().getContent();
            result = inputstreamToString(stream);
            Log.i("LOG", "Code :" + code);
        } catch (IOException e) {
            Log.e("Database", "Error Connect to Database!");
            e.printStackTrace();
        }
        return result;
    }

2) inputstreamToString method gets an Inputstream and read all lines.

private String inputstreamToString(InputStream getStream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(getStream));
        StringBuilder builder = new StringBuilder();
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        } catch (IOException e) {
            Log.e("Reader", "Error reading stream!");
            e.printStackTrace();
        }
        return "";
    }

3) jsonToString method gets JSON String with a String value that we want to get.

public String jsonToString(String getJSONString, String value) {
        String userId = "";
        try {
            JSONObject object = new JSONObject(getJSONString);
            userId = object.getString(value);
            return userId;

        } catch (JSONException e) {
            Log.e("JSON", "Error converting!");
            e.printStackTrace();
        }
        return "";
    }

so I call methods like this:

String databaseURL = "http://192.168.56.1/saly/getDatabaseTable.php";
String jsonFormat = getJSONFromDatabase(databaseURL);
String userId = jsonToString(jsonFormat, "userId");
String name= jsonToString(jsonFormat, "name");
String birthday= jsonToString(jsonFormat, "birthday");

at the end I get this errors in Log:

JSON: Error converting!  

JSON: Error converting!  

JSON: Error converting!

when I remove [ ] and write one line just like this JSON String, it works properly, just one line!:

{
    "userId":"1",
    "user":"saly",
    "pass":"666",
    "name":"SalyR",
    "family":"manson",
    "gender":"male",
    "birthday":"1988\/11\/10"
}

but it's not gonna work for me because when I print all table of database in JSON format the whole data will print.

I wrote too much and sorry for that, I tried explanation every things. would you gyus please help me where I wrong?

thank you.

3
  • Did you use loop for print results? Commented Apr 11, 2015 at 9:36
  • use Gson it would a lot easier than writing all this code Commented Apr 11, 2015 at 9:37
  • 2
    If you are getting json array from server then you should parse it as json array not as json object. Commented Apr 11, 2015 at 9:39

2 Answers 2

1

You have to parse it as jsonArray. The following snip will help you.

JSONArray jsonarray = new JSONArray(str);//str= your json string.


for(int i=0; i<jsonarray.length(); i++){
    JSONObject obj = jsonarray.getJSONObject(i);

    String name = obj.getString("name");
    String url = obj.getString("url");

    System.out.println(name);
    System.out.println(url);
}   

Here is the answer for this question.

Sign up to request clarification or add additional context in comments.

1 Comment

with this code I just can get latest line values in JSON string!
1
User.java

it's the user class.

public class User {

private String userId = "";
private String user = "";
private String pass = "";
private String name = "";
private String family = "";
private String gender = "";
private String birthday = "";

public String getUserId() {
    return userId;
}
public void setUserId(String userId) {
    this.userId = userId;
}
public String getUser() {
    return user;
}
public void setUser(String user) {
    this.user = user;
}
public String getPass() {
    return pass;
}
public void setPass(String pass) {
    this.pass = pass;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getFamily() {
    return family;
}
public void setFamily(String family) {
    this.family = family;
}
public String getGender() {
    return gender;
}
public void setGender(String gender) {
    this.gender = gender;
}
public String getBirthday() {
    return birthday;
}
public void setBirthday(String birthday) {
    this.birthday = birthday;
}

@Override
public String toString() {
    // TODO Auto-generated method stub
    return userId+" "+user+ " "+pass+ " "+name+" "+family+" "+ gender+ " "+ " ";
}


}

you can run this as a test, this example shows how easy it would be to deal with JSON by using Gson library

public class SIx {

public static void main(String[] args) {

    ArrayList<User> list = new ArrayList<User>();

    System.out.println("#### Object ####");

    for (int i = 0; i < 4; i++) {
        User user = new User();
        user.setUserId("UserId_"+i);
        user.setUser("User_"+i);
        user.setPass("Pass_"+i);
        user.setName("Name_"+i);
        user.setGender("Gender_"+i);
        user.setFamily("Family_"+i);
        user.setBirthday("Birthday_"+i);
        list.add(user);
        System.out.println(user.toString());
    }

    String string = (new Gson()).toJson(list);

    System.out.println();
    System.out.println();

    System.out.println(string);

    System.out.println();
    System.out.println();

    ArrayList<User> newList = (new Gson()).fromJson(string,  new TypeToken<ArrayList<User>>() {}.getType());

    for (int i = 0; i < newList.size(); i++) {
        User user = newList.get(i);
        System.out.println("UserId_:  "+user.getUserId());
        System.out.println("User_:  "+user.getUser());
        System.out.println("Pass_:  "+user.getPass());
        System.out.println("Name_:  "+user.getName());
        System.out.println("Gender_:  "+user.getGender());
        System.out.println("Family_:  "+user.getFamily());
        System.out.println("Birthday_:  "+user.getBirthday());
        System.out.println();
    }

}
}

output

enter image description here

3 Comments

thank you so much @Pankaj Nimgade I use Android Studio how can i define SIx class?
@SalarRastari, you are welcom, used eclips to make this file just to run this file to show you how you can use GSON
@SalarRastari, in Android studio you should be using code inside Six class you don't have to make that class but you will have to make User.java

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.