Cannot parse JSON to Java(android) - java

My PHP file:
<?php
include("ConnectDatabase.php");
$Username = mysql_real_escape_string($_POST['Username']);
$Password = mysql_real_escape_string($_POST['Password']);
$q = mysql_query("SELECT Username, Password FROM Users
where Username = '".$Username."' and
Password = '".$Password."'", $con);
if(mysql_num_rows($q) > 0){
$row = mysql_fetch_assoc($q);
print json_encode($row);
}else{
print "0";
}
?>
I tried to parse that by the following to get a value,but it got null values both userJson and passJson:
public void parseJson(String result){
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
userJson = jArray.getJSONObject(i).getString("Username").toString();
passJson = jArray.getJSONObject(i).getString("Password").toString();
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
Anyone can see my mistake ? Thank you
PS This is my older post that related to this post.

I would think they end up null cuz the first line doesn't work. It's not a JSONArray as you have generated.
try {
JSONObject root = new JSONObject(result);
username = root.getString("Username");
password = root.getString("Password");
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
something like that.

Related

Java app connection to MySQL with json no value for

Hi i have a problem with display data from my database on my app
That's part of Java file
#Override
protected String doInBackground(String... params)
{
String result ="";
String host = "http://192.168.0.12/LoginRegister/workelectricallist.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
while ((line = reader.readLine()) != null)
{
stringBuffer.append(line);
break;
}
reader.close();
result = stringBuffer.toString();
}
catch (Exception e)
{
return new String("There exception: " + e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result)
{
try
{
Toast.makeText(getApplicationContext(),"1 enter", Toast.LENGTH_SHORT).show();
JSONObject jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if (success == 1)
{
Toast.makeText(getApplicationContext(),"2 enter", Toast.LENGTH_SHORT).show();
JSONArray ad = jsonResult.getJSONArray("ad");
for(int i=0; i < ad.length(); i++)
{
JSONObject object = ad.getJSONObject(i);
int id = object.getInt("id");
String user_name = object.getString("user_name");
String NameAd = object.getString("NameAd");
double Content = object.getDouble("Content");
String TypeOfAd = object.getString("TypeOfAd");
String line = id + "-" + user_name + "-" + NameAd + "-" + Content + "-" + TypeOfAd;
adapter.add(line);
}
}
else
{
Toast.makeText(getApplicationContext(),"No Ad to display", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
php file take data from MySQL data base, i can see array of data on a broswer
but on my app, i can see only "1 enter" and "no value for a success"
Like it didn't go to if, but there is no "No ad to display" so it didnt go to else
That's php file
<?php
$host ='localhost';
$user ='root';
$pwd ='';
$db ='loginregister';
$conn = mysqli_connect($host, $user, $pwd, $db);
if(!$conn)
{
die("Error in connection" . $mysqli_connect_error());
}
$response = array();
$sql_query = "select *from ad";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0)
{
$response['succes'] = 1;
$ad = array();
while ($row = mysqli_fetch_assoc($result))
{
array_push($ad, $row);
}
$response['ad'] = $ad;
}
else
{
$response['succes']=0;
$response['succes']='no data';
}
echo json_encode($response);
mysqli_close($conn);
?>
Using a local service you also need to see your development environment. If the app runs on the same machines where the site is hosted there should be no problem. If, on the other hand, the app is used externally, the error may be caused by the http request not being able to get a response because it does not know who to ask for the response.
I invite you to analyze the try and catch since there is the error "no value for a success". It is very likely that the result string do not get readed correctly or is not in a json format and because of that sends you the exception.
By googling "JSONException no value for" it possible to find extra information about this kind of issue like Android - JSONException No value for

Android : get data from MySQL using 'where' condition

I am trying to get data from MySQL database to my android app using where condition. I already create a method for get data. This method give me all data as a string array from a single column.
Look the bellow method :
String adress = "http://myserver_link/get_data.php";
InputStream inputStream = null;
String line = null, result = null, data[];
private void get_data(){
try {
URL url = new URL(adress);
HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(httpsURLConnection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// read input stream into a string
try{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
// Parse json data
try{
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject = null;
data = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("user_adress"); // column name
}
}
catch (Exception e){
e.printStackTrace();
}
}
This is my get data java method. And my get_data.php code is :
<?php
require "conn.php";
$query = mysqli_query($conn, "select * from android_data");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
Now I want to write my get_data.php file like bellow :
<?php
require "conn.php";
$user_name = $_POST["username"];
$query = mysqli_query($conn, "select * from android_data where username='$user_name'");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
But how I can send username using get_data() java method from my app?
You should probably send this as a parameter on the URL...
String adress = "http://myserver_link/get_data.php?username=xxxxx";
Not done Java for a while, but you can create this string using the appropriate value for xxxxx.
This will then be passed in as $_GET["username"] instead of $_POST["username"]. So just replace this line
$user_name = $_POST["username"];
with
$user_name = $_GET["username"];
Or you can change the Request method to POST in your Java code.

Conversion error from String to JSONObject in Android [duplicate]

I have a JSON file with 2 JSON-Arrays in it:
One Array for routes and one Array for sights.
A route should consist of several sights where the user gets navigated to.
Unfortunately I am getting the error:
JSONException: Value of type java.lang.String cannot be converted to JSONObject
Here are my variables and the code that parses the JSON-File:
private InputStream is = null;
private String json = "";
private JSONObject jObj = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
// hier habe ich das JSON-File als String
json = sb.toString();
Log.i("JSON Parser", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Log.i("JSON Parser", json);
shows me that at the beginning of the generated string there is a strange sign:
but the error happens here:
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
04-22 14:01:05.043: E/JSON Parser(5868): Error parsing data
org.json.JSONException: Value //STRANGE SIGN HERE // of type
java.lang.String cannot be converted to JSONObject
anybody has a clue on how to get rid of these signs in order to create the JSONObject?
Reason is some un-wanted characters was added when you compose the String.
The temp solution is
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
But try to remove hidden characters on source String.
see this
http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
you try to use some thing like:
new JSONObject("{your string}")
Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.
So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.
BTW. i used UTF-8 encoding on both sides.
PHP side: header('Content-type=application/json; charset=utf-8');
JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
So try the solution one by one 1,2,3,4...! Hope it helps you guys!
try {
jObj = new JSONObject(json.substring(3));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
This worked for me
json = json.replace("\\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));
Here is UTF-8 version, with several exception handling:
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
static HttpResponse httpResponse = null;
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue(params, true);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpGet httpPost = new HttpGet( url);
httpResponse = httpClient.execute( httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException ee) {
Log.i("UnsupportedEncodingException...", is.toString());
} catch (ClientProtocolException e) {
Log.i("ClientProtocolException...", is.toString());
} catch (IOException e) {
Log.i("IOException...", is.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8); //old charset iso-8859-1
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
json = sb.toString();
Log.i("StringBuilder...", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
try {
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (Exception e0) {
Log.e("JSON Parser0", "Error parsing data [" + e0.getMessage()+"] "+json);
Log.e("JSON Parser0", "Error parsing data " + e0.toString());
try {
jObj = new JSONObject(json.substring(1));
} catch (Exception e1) {
Log.e("JSON Parser1", "Error parsing data [" + e1.getMessage()+"] "+json);
Log.e("JSON Parser1", "Error parsing data " + e1.toString());
try {
jObj = new JSONObject(json.substring(2));
} catch (Exception e2) {
Log.e("JSON Parser2", "Error parsing data [" + e2.getMessage()+"] "+json);
Log.e("JSON Parser2", "Error parsing data " + e2.toString());
try {
jObj = new JSONObject(json.substring(3));
} catch (Exception e3) {
Log.e("JSON Parser3", "Error parsing data [" + e3.getMessage()+"] "+json);
Log.e("JSON Parser3", "Error parsing data " + e3.toString());
}
}
}
}
}
// return JSON String
return jObj;
}
This is simple way (thanks Gson)
JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();
https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem
I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.
Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.
return response;
After that get the response we need to parse this By:
JSONObject myObj=new JSONObject(response);
On response there is no need for double quotes.
I made this change and now it works for me.
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
The 3 characters at the beginning of your json string correspond to Byte Order Mask (BOM), which is a sequence of Bytes to identify the file as UTF8 file.
Be sure that the file which sends the json is encoded with utf8 (no bom) encoding.
(I had the same issue, with TextWrangler editor. Use save as - utf8 (no bom) to force the right encoding.)
Hope it helps.
In my case the problem occured from php file.
It gave unwanted characters.That is why a json parsing problem occured.
Then I paste my php code in Notepad++ and select Encode in utf-8 without BOM
from Encoding tab and running this code-
My problem gone away.
In my case, my Android app uses Volley to make a POST call with an empty body to an API application hosted on Microsoft Azure.
The error was:
JSONException: Value <p>iisnode of type java.lang.String cannot be converted to JSONObject
This is a snippet on how I was constructing the Volley JSON request:
final JSONObject emptyJsonObject = new JSONObject();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, emptyJsonObject, listener, errorListener);
I solved my problem by creating the JSONObject with an empty JSON object as follows:
final JSONObject emptyJsonObject = new JSONObject("{}");
My solution is along the lines to this older answer.
if value of the Key is coming as String and you want to convert it to JSONObject,
First take your key.value into a String variable like
String data = yourResponse.yourKey;
then convert into JSONArray
JSONObject myObj=new JSONObject(data);
For me, I just needed to use getString() vs. getJSONObject() (the latter threw that error):
JSONObject jsonObject = new JSONObject(jsonString);
String valueIWanted = jsonObject.getString("access_token"))

Value 0 of type Java.lang.Integer cannot be converted to JSONObject

I'm trying to execute this Code for my App:
JSONObject json = jsonParser.makeHttpRequest(url_kickit_connect,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
try {
int response = json.getInt(TAG_RESPONSE);
if (response == 0){
Toast.makeText(getApplicationContext(), "email " +mail , Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
While getting a 0 as return value, the 0 should be parsed as jsonobject within this code (above I do the standard Httppost and Stringbuilder):
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
The JSON value I get from my MySQL side(.php):
else
{
$response = 0;
echo json_encode($response);
}
But I get this error in Logcat:
02-26 09:24:14.920: E/JSON Parser(619): Error parsing data org.json.JSONException: Value 0 of type java.lang.Integer cannot be converted to JSONObject
If I try to change the value, or the data type to string etc. The error message just changes to the told value or data type.
How do I solve this?
0 is not a valid json. Server should return something like {"response": 0} for this case
To send the response as a JSON, add this on the php/mysql side
else {
//creates an array
$result = array();
//adds a json node for response
$result['response'] = 0;
//encode and echo out
echo json_encode($result);
}

Error converting a HTTP POST response to JSON

When I try to convert an HTTP POST response to JSONArray I get the error:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
the error happens in the line: JSONArray jArray = new JSONArray(result);
the value of the string result is [{"return":"1"}] but it includes an extra blank character at the beginning that when removed, solves the problem. However, this character is not blank because a trim does not solve the problem. I believe there is some problem with the POST response, maybe badly constructed? (or maybe the POST request is wrong?) Any help is welcome.
A GET request works just fine, but I need to do a POST request.
This is the code:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
this is the code of the function HttpPost()
private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
this is the code of the function ConvertResponseToString()
private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
this is the code of my php that replies to the POST
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
I'm using this and for me always works fine:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
The problem is solved.
PHP files were saved in UTF-8 WITH BOM, the solution was saving the files in UTF8 no BOM and the initial character in the POST response was removed.

Categories