JSONException during AsyncTask - java

#Override
protected Integer doInBackground(Void... params)
{
String readMyJSON = readMyJSON();
try {
JSONArray jsonArray = new JSONArray(readMyJSON);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
This is not working, during JSONArray jsonArray = new JSONArray(readMyJSON);, JSONException occurs. Could somebody tell me where is the problem? Thanks in advance.
P.S.: Method I use:
public String readMyJSON()
{
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://search.twitter.com/search.json?q=android");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
This method seems to be allright.

In short, the response from twitter is not an JSON array, so you get an exception. If you want the array of results, do the following:
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = object.getJSONArray("results");
I suggest you read the Twitter API docs. Specifically, https://dev.twitter.com/docs/api/1/get/search.

Can you try this:
JSONArray jsonArray = new JSONArray("["+readMyJSON+"]");
I hope it should work.

Related

how to post json objects to webservices like url

I want to pass JSON objects to web services like this
firstname=jhon&lastname=mic&mail=jhon#gmail.com&sex=M&hometown=blablabla
how can I pass,any one please help me.Am trying like this
JSONObject json = new JSONObject();
json.put("firstname", firstname);
json.put("lastname", laststname);
json.put("mail", mail);
json.put("sex", sex);
json.put("hometown", hometown)
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
post.setEntity(new ByteArrayEntity(json1.toString().getBytes("UTF8")));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null)
{
InputStream instream=entity.getContent();
String result=convertStreamToString(instream);
}
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
But this code not posted the right value to webservice,Is there any wrong please help me ,
Thank you:)
StringBuilder bu = new StringBuilder();
for(int i = 0; i<json.names().length(); i++){
bu.append("&");
try {
bu.append(json.names().getString(i)+"="+json.get(json.names().getString(i)));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bu.toString();//give you parameters

Can't get JSON in HTTP Request in Android

I'm trying to receive a JSON format file throw HTTP in Android. But while i do that i guess the file comes bad formatted. The code is the following:
#Override
protected String doInBackground(String... params) {
StringBuilder builder = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
URI website = new URI(params[0]);
HttpGet request = new HttpGet();
request.setHeader("Content-type", "application/json");
request.setURI(website);
HttpResponse httpResponse = httpClient.execute(request);
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
builder.append(line);
}
}
catch(Exception e){
Log.e("http", e.toString());
}
return builder.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result);
txt.setText((String) jObject.get("shortName"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//txt.setText(result);
}
The JSON file is like this:
{"lectiveSemesters":[{"lectiveSemesterId":1,"shortName":"0910i","startYear":2009,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/1","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":2,"shortName":"0910v","startYear":2009,"term":2,"termName":"Spring","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/2","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":3,"shortName":"1011i","startYear":2010,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/3","root":"http://thoth.cc.e.ipl.pt/api/v1"}},
...
...
"_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters"}}
This is just a part of the file.
Am I doing something wrong? I included the header in order to receive in JSON format.
Here you are.
try{
JSONObject jObject = new JSONObject(result);
JSONArray jarray = jObject.getJSONArray("lectiveSemesters");
for(int i = 0; jarray != null & i < jarray.length(); i++){
JSONObject jitem = (JSONObject) jarray.get(i);
}
} catch (Exception e){
}

How to parse all JSON values correctly in Android

First the: Android Code
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
machines = new ArrayList<Machine>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(result));
jsonReader.setLenient(true);
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
for (JsonElement obj : jsonArray) {
Machine machine = gson.fromJson(obj.getAsJsonObject().get("mobileMachine"), Machine.class);
machines.add(machine);
machines.get(0);
}
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
}
Here is some Code of the JSON File
[
{ "mobileMachine":
{ "condition":"VERY_GOOD",
"document":"", . . .
"mobileCategory": { "idNr":"1816e5697eb3e0c8442786be5274cb05cff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e",
"mobileCategoryEng":"Bookletmaker",
"mobileCategoryGer":"Broschuerenfertigung" },
"modelYear":2006,
Abmessungen: 665x810mm " } }
{ "mobileMachine":
{
"condition":"VERY_GOOD"," ...... } } ]
Sometimes there is a mobileCategory inside. The mobileCategoryGer and mobileCategoryEng are allways null in the List.
I can't edit the JSON File! I only want the value for mobileCategoryGer and mobileCategoryEng from the Json File. The Rest works fine. I hope u understand and can help me to parse it correctly.
(Sorry for my english)
Here you go.
Type listType = new TypeToken<List<Machine>>() {}.getType();
ArrayList<Result> results = gson.fromJson(result, listType);
Here is your complete modified code:
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
Type listType = new TypeToken<List<Machine>>() {}.getType();
machines= gson.fromJson(result, listType);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
You could check if it has the key with has() method. Also you can get optional value with optJSONObject() and check if it is not null.
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
try {
doSomething(jsonArray);
} catch (JSONException e) {
Log.wtf("Terrible Failure", e);
}
private void doSomething(JsonArray jsonArray) throws JSONException{
for (int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
JSONObject mobileCategory = obj.optJSONObject("mobileCategory");
if(mobileCategory !=null){
if(mobileCategory.has("mobileCategoryEng") && mobileCategory.has("mobileCategoryGer") ){
String mobileCategoryEng = mobileCategory.getString("mobileCategoryEng");
String mobileCategoryGer = mobileCategory.getString("mobileCategoryGer");
}
}
}
}

HttpClient.excute(HttpPost) no response

I constructed an HttpClient, and set timeout parameters.
the code is like this:
while(bufferedinputstream.read()!=-1){
post.setEntity(multipartEntity);
HttpResponse response = httpClient.excute(post);
}
it worked fine for the first several request, and then somehow the response is not returned, and no exception or timeout exception was thrown. Anyone has any idea what's happening?
since you re not getting any errors or exceptions (do you print them out?), you could check the satusCode of your response. Maybe it helps.
(overridden method from my AsyncTask)
protected String doInBackground(String... arg) {
String url = arg[0]; // Added this line
//...
Log.i(DEBUG_TAG, "URL CALL -> " + url);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String mResponse = "";
try {
List<NameValuePair> params = new LinkedList<NameValuePair>();
//...
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse mHTTPResponse = client.execute(post);
StatusLine statusLine = mHTTPResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //
//get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
mHTTPResponse.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = rd.readLine()) != null) {
builder.append(aux);
}
mResponse = builder.toString();
} else {
//cancel task and show error
Log.e(DEBUG_TAG, "ERROR in Request:" + statusCode);
this.cancel(true);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mResponse;
}

How do I display a Java HttpPost object as a string?

I am creating an HttpPost object in Android to communicate with a server operated by a client. Unfortunately the server isn't providing either of us with very useful error messages; I would like to see the content of the HttpPost object as a string so I can send it to our client and he can compare it with what he's expecting.
How can I convert an HttpPost object into a string that reflects how it would look as it arrived at the server?
Should use it after execute
public static String httpPostToString(HttpPost httppost) {
StringBuilder sb = new StringBuilder();
sb.append("\nRequestLine:");
sb.append(httppost.getRequestLine().toString());
int i = 0;
for(Header header : httppost.getAllHeaders()){
if(i == 0){
sb.append("\nHeader:");
}
i++;
for(HeaderElement element : header.getElements()){
for(NameValuePair nvp :element.getParameters()){
sb.append(nvp.getName());
sb.append("=");
sb.append(nvp.getValue());
sb.append(";");
}
}
}
HttpEntity entity = httppost.getEntity();
String content = "";
if(entity != null){
try {
content = IOUtils.toString(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
sb.append("\nContent:");
sb.append(content);
return sb.toString();
}
snippet
I usually do post in this way (The server answer is a JSON object) :
try {
postJSON.put("param1", param1);
postJSON.put("param2",param2);
} catch (JSONException e) {
e.printStackTrace();
}
String result = JSONGetHTTP.postData(url);
if (result != null) {
try {
JSONObject jObjec = new JSONObject(result);
}
} catch (JSONException e) {
Log.e(TAG, "Error setting data " + e.toString());
}
}
And postData is:
public static String postData(String url, JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = null;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
httpclient = new DefaultHttpClient(myParams);
} catch (Exception e) {
Log.e("POST_DATA", "error in httpConnection");
e.printStackTrace();
}
InputStream is = null;
try {
HttpPost httppost = new HttpPost(url.toString());
//Header here httppost.setHeader();
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// // Do something with response...
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert response to string
BufferedReader reader = null;
String result = null;
try {
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");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
#SuppressWarnings("unused")
JSONObject jObjec = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
return result;
}
Hope it helps
Well i actually did HTTP-Post using NameValuePair...... I am showing the code which i use to do an HTTP-Post and then converting the Response into a String
See the below Method code:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}

Categories

Resources