Java - String from JSONArray not matching in if statement - java

I really can't see where I'm going wrong with this. Any help would be much appreciated.
I have a JSONArray
JSONArray jsonArray = new JSONArray(responseString);
Where responseString is ["prob", "2"]
I get the 1st String
String maybeProb = jsonArray.getString(0);
and when I show it using a Toast all is ok and the toast popup just says prob
Toast.makeText(getBaseContext(),maybeProb ,Toast.LENGTH_LONG).show();
But when I use an if (maybeProb == "prob") it doesnt return true
Why not??? What am I doing wrong???
Some more details for you:
responseString which forms the original JSONArray comes from an HttpPost to my server
InputStream is = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//Convert response to string
responseString = convertStreamToString(is);
public String convertStreamToString(InputStream inputStream) {
StringBuilder sb = null;
String result = null;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
inputStream.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
// return the string
return result;
}
The PHP on my server which makes the response is
$message = array("prob", "2");
$response = json_encode($message);
print($response);
Many thanks to anyone that can help me

To compare objects in java use .equals() method instead of "==" operator
Replace the following code
if(maybeProb == "prob") {
}
with this one.
if(maybeProb.equals("prob")) {
}

The equals operator (==) returns true only if both objects are the same, not if their value is the same. Therefore, when you compare the object maybeProb with the object "prob" it returns false
If you want to do the comparison, you have to use maybeprob.equals("prob").

Related

URLConnection and POST method android

I am trying to make a post request using the reference of this documentation. But the problem is that the PHP developer at the other end is not able to receive the value of the parameter hence is not able to send a proper response. Am I missing something out here.
// Edits ;
I am making a HTTP Post request. As you can seen the code below. I am writing the arguments and parameters (location_id=3) to the outputstream. I have also pasted the code for PHP which i have been using. Now the problem is:
The parameter value ( which is 3 ) is not received at the PHP code so I am getting a response which is surrounded by the else block. So I just want to know if there is an error in the android code or the PHP code
#Override
protected Boolean doInBackground(String... params) {
Log.d(Constants.LOG_TAG,Constants.FETCH_ALL_THEMES_ASYNC_TASK);
Log.d(Constants.LOG_TAG," The url to be fetched "+params[0]);
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
// /* optional request header */
// urlConnection.setRequestProperty("Content-Type", "application/json");
//
// /* optional request header */
// urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location_id",params[1]));
outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(writeToOutputStream(nameValuePairs));
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
Log.d(Constants.LOG_TAG, " The response is " + response);
return true;
}
else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
// Here is the code for writeToOutputStream
public String writeToOutputStream(List<BasicNameValuePair> keyValuePair)throws UnsupportedEncodingException{
String result="";
boolean firstTime = true;
for(BasicNameValuePair pair : keyValuePair){
if(firstTime){
firstTime = false;
}
else{
result = result.concat("&");
}
result = result + URLEncoder.encode(pair.getKey(), "UTF-8");
result = result + "=";
result = result+ URLEncoder.encode(pair.getValue(),"UTF-8");
}
Log.d(Constants.LOG_TAG," The result is "+result);
return result;
}
// Here is the code for convertInputStream to String
public String convertInputStreamToString(InputStream is) throws IOException {
String line="";
String result="";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
while((line = bufferedReader.readLine()) != null){
Log.d(Constants.LOG_TAG," The line value is "+line);
result += line;
}
/* Close Stream */
if(null!=inputStream){
inputStream.close();
}
return result;
}
Here is the PHP CODE
<?php
include 'config.php';
header ('Content-Type:application/json');
if(isset($_POST['location_id']))
{
$id=$_POST['location_id'];
$selectThemeQuery = mysql_query("select theme_id from location_theme where location_id='$id'",$conn) or die (mysql_error());
$noRows = mysql_num_rows($selectThemeQuery);
//echo "HI";
if($noRows > 0)
{
$result = array();
while($row = mysql_fetch_assoc($selectThemeQuery))
{
$themeid = $row['theme_id'];
//echo "HI";
$selectNameQuery = mysql_query("select theme_name,theme_image from theme where theme_id='$themeid'",$conn) or die(mysql_error());
$numRows = mysql_num_rows($selectNameQuery);
if($numRows > 0)
{
while($rows = mysql_fetch_assoc($selectNameQuery))
{
$name = $rows['theme_name'];
$image = $rows['theme_image'];
$result[] = array('theme_id'=>$themeid,'theme_name'=>$name, 'theme_image'=>$image);
}
}
}
//echo json_encode($result);
echo json_encode("Hi");
}
else
{
$data2[] = array('Notice'=>false);
echo json_encode($data2);
}
}
else
{
echo "Not Proper Data";
}
?>
Remove:
urlConnection.setChunkedStreamingMode(0);
You use a buffered writer so it can only buffer instead of write.
To force all been written:
bufferedWriter.write(writeToOutputStream(nameValuePairs));
bufferedWriter.flush();
And then ask for a response code. And don't call a response code a status code.
writeToOutputStream() ??? What a terrible name. That function does not write to an output stream. It justs makes a text string.
For Android, I would suggest using a library like Spring-Android.
Spring-Android contains a RestTemplate class, which is a quite effective REST-Client. For example, a simple POST request would be...
myRestTemplate.exchange("http://www.example.net", HttpMethod.POST, new HttpEntity( ...some JSON string ...), String.class );
To create the JSON String, I suggest a library like Jackson, which should work fine on Android, see for example here. Not sure if Jackson integrates as fine in Spring-Android as it does in Spring-Web, but in any case, using it to create the Json Strings manually should work just fine.
for post method
create a string builder first
StringBuilder strbul=new StringBuilder();
then append the data like
strbul.append("name=sangeet&state=kerala");
then write to output stream like
httpurlconnection.getOutput().write(strbul.toString().getBytes("UTF-8"));
php script will recieve that data on
$_POST['name'] and $_POST['state']

String cannot be converted to JSON - Android

I have am trying to convert my response from a POST to JSON. And here is what I am doing:
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) {
response.append(line).append("\r");
}
rd.close();
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response.toString());
But then I get error java.lang.String cannot be converted to JSONObject
But if I make a string, String string; and then I paste the what I logged and set it equal to string, and then try
JSONObject jsonObject = new JSONObject(string);
It works, so why is it working when I paste the logged response, but not when I just use response.toString();?
In the logcat it looks like this {"url": "www.google.com"}. And then when I paste it into string = "{\"url\": \"www.google.com\"}";
Thanks for the help
I met this problem before, try this:
new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
or
if (response != null && response.startsWith("\ufeff")) {
in = in.substring(1);
}
the response from server contains a BOM header
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string.
source - A string beginning with { (left brace) and ending with } (right brace).
So while doing response.toString() if the string do not start with { and close with } then it will throw Exception.

Can't properly parse JSON

I am having some issues while parsing JSON response in Android. The response I get is:
{
"response": "{\"session_token\":\"48500d8e42acc09aa45cb8f3a7ba2b30\",\"user_login\":\"newoff2\",\"user_id\":\"62\",\"user_profile_img\":\"http://onepgr.com/system/photos/62/medium/userfile054c35e29.png?1422089771\",\"success\":\"0\",\"user_email\":\"newoff2#pdmoffice.com\"}"
}
I need the values for user_login, success, user_profile_img, user_email. Here is what I tried so far, but it won't do what I need:
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
Log.d("Final Response",json);
jsonObject = new JSONObject(json);
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
Log.e("Parsed data is",str);
use this
json=json.replace("\\\"", "\"");
Log.e("resule",json);
try {
JSONObject jsonObject = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use regex to make your string JSON parsable
var res = data.replace(/\\"/g, '').replace(/\"{/g, '{').replace(/\}"/g, '}');
var jsonData = JSON.parse(res);
alert(jsonData.response.user_login);
Here is FIDDLE
Note: in fiddle I have declared your JSON with a ' ' to make it complete string
Use Scanner to remove \:
String resultStr = new Scanner(json).useDelimiter("\\A").next();
jsonObject = new JSONObject(resultStr);
Above is used for BufferedInputStream to get JSON string.
[UPDATE:]
For BufferReader, need to use StringBuilder to get JSON string:
StringBuilder strBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
strBuilder.append(line);
}
//for your JSON string, should use 'JSONTokener' to parse
jsonObject = (JSONObject) new JSONTokener(strBuilder.toString()).nextValue();
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
This should work for your case!
Try this....
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.d("Result",result);
JSONObject jsonObject = new JSONObject(result);
String resJson=jsonObject.getString("response");
Log.d("Result",resJson);
JSONObject jsparam=new JSONObject(resJson);
String success=jsparam.getString("success");
Log.d("Value for success",success);
// JSONObject json1=jsonObject.getJSONObject("response");
//String objResponse = json1.getString("success");
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

Decoding HttpEntity into android string - encoding issue

I know that should be basics but i had no formation :( and I don't understand it, everywhere it seems obvious to people. I get that one side encode data with his set and android is probably expecting another one, but what can I do to translate?
My app perform a get request on google maps api to retrieve an address from a Lat/lng. But I failed to decode properly the result as a French è is displayed as è
I have not enough xp in Java to understand what to do. It is linked with UTF-8, right?
What should I do?
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject();
jsonObject = new JSONObject(stringBuilder.toString());
retList = new ArrayList<Address>();
if("OK".equalsIgnoreCase(jsonObject.getString("status"))){
JSONArray results = jsonObject.getJSONArray("results");
for (int i=0;i<results.length();i++ ) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.ITALY);
addr.setAddressLine(0, indiStr);
Dbg.d(TAG, "adresse :"+addr.toString());
retList.add(addr);
}
}
Thanks for help !
Try using UTF-8,
instead of using InputStream try something like,
String responseBody = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
you can use BufferReader
your code will be like this:
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int b;
while ((b = br.read()) != -1) {
stringBuilder.append(b);
}

HttpURLConection - JSON Response isn't Complete

I am trying to send a request to the Grooveshark API using POST Payload and their requested methods, and I have found a problem. Allow me to show you my code first.
public void getResponse() throws Exception
{
if(service.equals("Grooveshark")) link += getHmacMD5(privateGroovesharkKey, jsonInfo.toString());
if(requestedMethod.equals("GET")) infoURL = new URL(link+arguments);
else infoURL = new URL(link);
HttpURLConnection connection = (HttpURLConnection) infoURL.openConnection();
connection.setRequestMethod(requestedMethod);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
if(service.equals("Grooveshark"))
{
connection.setRequestProperty("Content-Type","application/json");
OutputStream output = connection.getOutputStream();
output.write(jsonInfo.toString().getBytes());
}
else if(requestedMethod.equals("POST") || requestedMethod.equals("PUT"))
{
OutputStream output = connection.getOutputStream();
output.write(arguments.getBytes());
}
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
sb.append(line).append('\n');
setJsonResult(sb.toString());
System.out.println(jsonResult);
jsonFinal = new JSONObject(jsonResult);
connection.disconnect();
}
I have got that code up here in my project, and I can successfully send requested to any API Webservice that uses JSON in their responses. Now there's only a problem: In Android, it does not give me the WHOLE answer. I've tried running the code on a separate Java (no Android) project, and I get the following output. Although, if I run it on Android, the Log shows me the following:
{"header":{"hostname":"RHL073"},"result":{"songs":[{"SongID":5443351,"SongName":"??????\u00b7???? (FINAL FANTASY XII????)","ArtistID":713,"ArtistName":"Final Fantasy","AlbumID":898007,"AlbumName":"Final Fantasy XII Original Soundtrack","CoverArtFilename":"","Popularity":1214500005,"IsLowBitrateAvailable":tr
And it stops on that tr. Has it anything to do with the parsing of the file that I actually apply afterwards? I don't think it is, but just in case, here it is [This is how I call the search, JSONHandler being the object that contains the code provided above]:
public void performSearch() throws Exception
{
JSONObject search = new JSONObject();
search.put("method", method);
JSONObject header = new JSONObject();
header.put("wsKey", key);
JSONObject parameters = new JSONObject();
parameters.put("query", getSearchQuery());
parameters.put("country", "Portugal");
parameters.put("limit", limit);
parameters.put("offset", "");
search.put("header", header);
search.put("parameters", parameters);
JSONHandler jsonHandler = new JSONHandler(link, search, "Grooveshark", "POST", "");
JSONObject finalResult = jsonHandler.getJsonFinal();
JSONArray songs = finalResult.getJSONObject("result").getJSONArray("songs");
ArrayList<Result> allResults = new ArrayList<Result>();
for(int i = 0; i < songs.length(); i++)
{
JSONObject inner = (JSONObject) songs.get(i);
String name = inner.getString("SongName");
int ID = inner.getInt("SongID");
String artist = inner.getString("ArtistName");
Result res = new Result(name, artist, ID);
res.setAlbumName(inner.getString("AlbumName"));
boolean low = inner.getBoolean("IsLowBitrateAvailable");
int bit = 0;
if(low) bit = 1;
else bit = 0;
res.setIsLowBitRateAvailable(bit);
}
setResults(allResults);
}
As you can clearly see, I am using the json.org library. I really don't understand what's the problem here. Has anyone got any idea as to why?

Categories