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.

Eko Junaidi Salam
  • 1,663
  • 1
  • 18
  • 26
Salar Rastari
  • 2,280
  • 5
  • 22
  • 35

2 Answers2

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.

Community
  • 1
  • 1
Vijay
  • 3,152
  • 3
  • 24
  • 33
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

Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30