1

I am stuck in a really tricky situation. So, what I am trying to do is to get JSON object from my localhost database. When I am entering url (http://localhost./embrace/test_get.php?nr=1) to my browser, it echoes:

{
 "nr": "1",
 "pav": "MANTAS"
}

I've already checked this JSON, and it seems that is valid. Also, I spent almost all day by searching for solutions in StackOverflow, but none of them worked. So, here is my code:

 public class MainScreenActivity extends Activity implements OnClickListener {
 EditText laukas;
 Button mygtukas;
 InputStream is = null;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main_screen);
 laukas = (EditText)findViewById(R.id.editText1);
 mygtukas = (Button)findViewById(R.id.button1);
 mygtukas.setOnClickListener(this);
 }
 @Override
 public void onClick(View v){
 String lokacija = "http://localhost./embrace/test_get.php?nr=1"; /* dont be mad about localhost, i have working adress which i've tested via pc and android browser, it's just because stackoverflow policy */
 URL url = null;
 try {
 url = new URL(lokacija);
 } catch (MalformedURLException e) {
 // TODO Auto-generated catch block
 Log.d("KLAIDA",e.toString());
 }
 HttpURLConnection conn = null;
 try {
 conn = (HttpURLConnection) url.openConnection();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 Log.d("KLAIDA",e.toString());
 }
 try {
 conn.setRequestMethod("GET");
 } catch (ProtocolException e2) {
 // TODO Auto-generated catch block
 e2.printStackTrace();
 }
 conn.setDoInput(true);
 try {
 conn.connect();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 Log.d("KLAIDA",e.toString());
 }
 try {
 is = conn.getInputStream();
 } catch (IOException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }
 String contentAsString = null; 
 try {
 contentAsString = readIt(is, 500);
 //is.close();
 if(contentAsString != null){
 //textView.setText(contentAsString);
 } //else textView.setText("nuliukas");
 } catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 Log.d("KLAIDA",e.toString());
 } catch (IOException e) {
 // TODO Auto-generated catch block
 Log.d("KLAIDA",e.toString());
 }
 conn.disconnect();
 int sum = 0;
 for(int i =0;i<contentAsString.length();i++){
 if(contentAsString.charAt(i)==('"'))
 sum++;
 }
 try {
 JSONObject b = new JSONObject();
 b.getJSONObject(contentAsString); // CRASH HERE
 } catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 Toast.makeText(MainScreenActivity.this,sum+"",Toast.LENGTH_SHORT).show();
 }
 public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
 Reader reader = null;
 reader = new InputStreamReader(stream, "UTF-8"); 
 char[] buffer = new char[len];
 reader.read(buffer);
 return new String(buffer);
 }
}

my test_get.php class

<?php
$con = mysqli_connect("localhost","root","","embrace_db");
//if(mysqli_connect_errno($con))
 //echo "Failed to connect to MySQL: ";
 //else echo "Connected successfully";
$output = array();
$nr = $_GET['nr'];
$q = mysqli_query($con,"SELECT * FROM duomenys WHERE nr = '$nr' ");
while ($e=mysqli_fetch_assoc($q))
 $output = $e;
echo (json_encode($output));
mysqli_close($con);
?>

LogCat output

07-29 21:52:10.399: W/System.err(12985): org.json.JSONException: No value for {"nr":"1","pav":"MANTAS"}??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
07-29 21:52:10.409: W/System.err(12985): at org.json.JSONObject.get(JSONObject.java:354)
07-29 21:52:10.409: W/System.err(12985): at org.json.JSONObject.getJSONObject(JSONObject.java:569)
07-29 21:52:10.409: W/System.err(12985): at com.damkell.wamptutorial.MainScreenActivity.onClick(MainScreenActivity.java:123)
07-29 21:52:10.409: W/System.err(12985): at android.view.View.performClick(View.java:2485)
07-29 21:52:10.409: W/System.err(12985): at android.view.View$PerformClick.run(View.java:9080)
07-29 21:52:10.409: W/System.err(12985): at android.os.Handler.handleCallback(Handler.java:587)
07-29 21:52:10.409: W/System.err(12985): at android.os.Handler.dispatchMessage(Handler.java:92)
07-29 21:52:10.409: W/System.err(12985): at android.os.Looper.loop(Looper.java:123)
07-29 21:52:10.409: W/System.err(12985): at android.app.ActivityThread.main(ActivityThread.java:3729)
07-29 21:52:10.409: W/System.err(12985): at java.lang.reflect.Method.invokeNative(Native Method)
07-29 21:52:10.409: W/System.err(12985): at java.lang.reflect.Method.invoke(Method.java:507)
07-29 21:52:10.409: W/System.err(12985): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
07-29 21:52:10.409: W/System.err(12985): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:632)
07-29 21:52:10.409: W/System.err(12985): at dalvik.system.NativeStart.main(Native Method)

P.S that's what I've already tried: To correct received string end remove /n mark; To use slightly different method http://www.helloandroid.com/tutorials/connecting-mysql-database But then LogCat throwed that End of input at character 0, also i tried logging my output(String received from HTTP, and it was same as from browser(pretty JSON String)); So, as you can see I've tried a lot, but it seems that there is a problem for every possible solution. Thanks in advance :)

SOLVED!!! special thanks to jteezy14 ! It was not exact problem as he said, but in fact he led me to the right way. It should be :

JSONObject b=null;
 try {
 b = new JSONObject(naujas);
 } catch (JSONException e1) {
 // TODO Auto-generated catch block
 Log.e("JSONKE",e1.toString());
 }

Instead of:

JSONObject b = new JSONObject();
 try{
 b.getJSONObject(naujas);
 } catch (JSONException e1) {
 Log.e("JSONKE",e1.toString());
 }

Also, thanks to Kimmax for formatting my answer and making it more understandable ;)

ArtKorchagin
4,86913 gold badges45 silver badges58 bronze badges
asked Jul 28, 2014 at 19:12
1
  • I think you should try using GSON library to parse the JSON string for you. Here is the official documentation. A second answer to this question will provide a nice example. Commented Jul 28, 2014 at 19:23

1 Answer 1

2

The reason this is happening is because you are creating a string that is 500 characters long in your readIt() function. Your JSON expression {"nr":"1","pav":"MANTAS"} is valid, but there are trailing characters that make it invalid JSON. That is why in the logcat you get so many question marks after the JSON expression.

In order to fix this, you need to have remove the extra characters from the JSON string.

EDIT (After reading your comment):

The first part of my answer was necessary but you must also use the JSONObject differently. Take a look at the documentation for the Android JSONObject

http://developer.android.com/reference/org/json/JSONObject.html#getJSONObject(java.lang.String)

The function you are using is expecting the input value to be the key of the JSON object (and that is why you are getting the error that says there is no value, because you are specifying a key that doesn't exist). You need to create the object passing the string, then get the values:

JSONObject b = new JSONObject(contentAsString)
JSONObject valAtNr = b.getJSONObject("nr"); //value at nr
JSONObject valAtPav = b.getJSONObject("pav"); //value at pav
answered Jul 28, 2014 at 19:23
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, it's not working.. I cut these unnecessary characters. Also, checked modified and not modified Strings lengths, and they are 25 compared to 500. But i'm still getting error : No value for {"nr":"1","pav":"MANTAS"}

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.