Get data from json and org.json.JSONException is thrown - java

Following json will be received but through the http://localhost/getData.php but exception is thrown
{"username":"not found","password":null}
Log I received
02-19 17:31:54.745: E/JSON Parser(5277): Error parsing data org.json.JSONException: End of input at character 0 of
02-19 17:31:59.185: E/JSON Parse(5277): ERROR
Following code is the method where exception throw
#Override
protected String doInBackground(String... url){
try{
String resultText = "";
EditText edit = (EditText)findViewById(R.id.text_box);
id = edit.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id",id));
JSONObject json = jsonParser.HttpRequest("http://localhost/getData.php", params);
resultText = json.getString("username");
}catch(Exception e){
e.printStackTrace();
Log.e("JSON Parse","ERROR");
}
return "";
}
public class SimpleJsonParser {
public SimpleJsonParser(){
}
public JSONObject HttpRequest(String url, List<NameValuePair> params){
InputStream input = null;
JSONObject jObj = null;
String json = "";
String line;
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
paramsString = URLEncodedUtils.format(params,"utf-8");
url += "?" + paramsString;
HttpGet httpGet = new HttpGet(url);
try{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
input = entity.getContent();
BufferedReader reader =
new BufferedReader(new InputStreamReader(input));
while((line = reader.readLine())!=null){
builder.append(line);
}
json = builder.toString();
} else {
Log.e("JSON Parser","Failed to download file");
}
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
input.close();
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
Anything wrong with my code? The code I provided is where exception throws occur

From what you mentioned, it appears that you are doing this via an emulator.
Emulator may not be able to access http://localhost//. You can try access using, loopback address or the ip address.

You never verify that you actually have received anything after reading from the stream returned from the HttpEntity. That exception is telling you there's no input at character 0 (The first character) - you have nothing to parse; it's an empty string. Nothing was ever appended to your StringBuilder.
public static void main(String[] args) throws JSONException
{
String json = "{\"username\":\"not found\",\"password\":null}";
JSONObject jObj = new JSONObject(json);
}
Throws no such exception. Often writing a small test case will point you in the right direction.
As others have mentioned, this is probably because you are using the wrong URL or maybe your parameters? Since you're getting back a 200 OK you're obviously connecting to a webserver and getting a response ... I'd check to see if that PHP is working as you expect.

Inside simpleJarsonParser class, I replace the following code
HttpClient httpClient = new DefaultHttpClient();
to
DefaultHttpClient httpClient = new DefaultHttpClient();
and it works. And of course I have replace localhost to 10.0.2.2 as I'm using xampp and android emulator.

Related

how to read it into a string without using a readline of String Buffer in android

public class HttpPosrHitter {
public static String getJSONfromURL(String url, String member_id,
String phonenumber) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("memberid", member_id));
pairs.add(new BasicNameValuePair("numbers", phonenumber));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
// http post
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());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
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());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return result;
}
}
This is class from which i am Post Phone Number to web service and getting response .
when i Post Number of Phone which has 15 to 20 contact i am getting response . but when i post number which has 150 contact i am not getting response one at a time i have to relaunch app two time then i am getting response . i dont know where i am doing mistake . even i am unable to read phone large file in chunks with fixed size buffer.
Just to solve all your potential bugs in one single shot: is there anything preventing you from using Retrofit and GSON or Jackson?
Each time I see such JSON/InputStream/URLConnection/... questions, I keep wondering why people keep on spending time to reinvent basic stuff instead of actually writing apps.
public class HttpPosrHitter {
public static String getJSONfromURL(String url, String member_id,
String phonenumber) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("memberid", member_id));
pairs.add(new BasicNameValuePair("numbers", phonenumber));
httppost.setEntity(new UrlEncodedFormEntity(pairs));
// http post
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity); //changes Made
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return result;
}
}

Error parsing data org.json.JSONException: End of input at character 0 of

I'm trying to parse JSON data which is coming from this url.
But I am getting these errors:
03-27 16:48:21.019: E/Buffer Error(23717): Error converting result java.lang.NullPointerException
03-27 16:48:21.059: E/JSON Parser(23717): Error parsing data org.json.JSONException: End of input at character 0 of
Wwhen I debug my code; getJsonFromUrl() method returns null jobject. Here is the JSONParser class which I used. What's causing the error?
public class JSONParser {
static InputStream iStream = null;
static JSONArray jarray = null;
static JSONObject jObj= null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
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");
}
iStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parsing the string to a JSON object
try {
if (json != null) {
jObj = new JSONObject(json);
} else {
jObj = null;
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I'm making the call for this method from another class using these lines. (url parameter is defined at top)
JSONParser jParser = new JSONParser();
final JSONObject jobject = jParser.getJSONFromUrl(url);
You are trying to get the JSON content using a HTTP POST method instead of the appropiated GET method (W3schools.com GET vs.POST), modify your source code to simplify and fix your HTTP request
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(get);
String json = EntityUtils.toString(httpResponse.getEntity());
System.out.println(json);
....
....
} catch (Exception e) {
....
}

Parse Json Arabic text

I can't parse Arabic/Persian text from SQL database. Everything is set to UTF-8. My SQL database text is set to utf8_general_ci. JSON parser is set to UTF-8 too.
Text is shown good in English. But when I use Arabic/Persian text in database, android shows text as ???????.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} 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;
}
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You
Maybe the problem is on server side. Check the raw String you got from the Server to see if it is correctly formatted.
I think it can help you by storing it as clob/blob, since once you have the bytes which were convereted from UTF-8 at server side, any client side code can also then using various String encoding formats to display the test.
Or my other advice, use a webview to display it, its more mature to handle these nuances.

Get json object created in mvc (jsonResult) in android

I created a json result in mvc and I'm building an Android app to get the json result. This is what my json result looks like
{"name":"Mr. Spock","gender":"Male"}
This is my controller
public ActionResult Index()
{
var result = new { name = "Mr. Spock", gender = "Male" };
return Json(result, JsonRequestBehavior.AllowGet);
}
And this I'm using in android
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} 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;
}
}
I have a declared variable url. Every time I debug, the json variable does not have any values and says "errors during the evaluation"
Anyone with a tip? I tried working with Gson, but no succes
Kind regards
I'll give you some code for Gson. It really is much easier to work with than the built in JSON parsing code. Here's a minimal example using your JSON.
Person.class:
package com.example.tutorial.models;
import com.google.gson.annotations.SerializedName;
public class Person {
#SerializedName("gender")
public String gender = "";
#SerializedName("name")
public String name = "";
}
The annotations are really only necessary when your variable and JSON name differ, but I tend to always include them as it reinforces that they are coming from JSON.
To deserialize:
Gson gson = new GsonBuilder().create();
Person person = gson.fromJson(json, Person.class);
It really is that simple. If this does not work, log the result from the web server and make sure it really is the valid JSON string you expect it to be.
I do have one question, where is your AsyncTask? Your attempt to open a connection to the webserver in the UI thread will definitely cause a NetworkOnMainThreadException. I created a library to do RESTful calls on Android. It's licensed under BSD, so feel free to use it as a guide or outright use it: https://github.com/nedwidek/Android-Rest-API

Parsing error from string to JSONArray in Android Application

I want to receive from an MySQL-Server all my data from a table.
So, I wrote a PHP script that fetches the complete table and encode it to JSON format.
PHP-Code:
<?php
include ("connect.php");
mysql_query("SET NAMES 'utf8'");
$query = mysql_query('SELECT * FROM MyTable);
while ($row = mysql_fetch_assoc($query))
{
$buffer[] = $row;
}
print json_encode( $buffer );
mysql_close($dbconnect);
?>
So, when I run the script, all the JSON String looks fine, no corupted characters etc.
In Android App:
When I run the following codes and receive the JSON String throught the HTTP, I get a strange String in the Debugger...
Screenshot: http://goo.gl/gTssQ
Java Code:
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// HTTP Verbindung
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Fehler bei der http Verbindung "+e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),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());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
I cant understand the Problem, because my Database is full UTF-8 and my script too.
I hope someone can help me! :-)
Greets, andr3w

Categories