I am new to android development and am trying to work with json data. I followed the web page "
http://hmkcode.com/android-parsing-json-data/" to make a simple app to get and display json. It works fine with the tutorial json web site. But when I change the url to point to my website I get an exception error on the line "JSONObject json = new JSONObject(result);"
03-15 08:56:10.518: W/System.err(1330): org.json.JSONException: Value <?xml of type
java.lang.String cannot be converted to JSONObject
03-15 08:56:10.528: W/System.err(1330): at org.json.JSON.typeMismatch(JSON.java:111)
03-15 08:56:10.528: W/System.err(1330): at org.json.JSONObject.<init>(JSONObject.java:159)
03-15 08:56:10.528: W/System.err(1330): at org.json.JSONObject.<init>(JSONObject.java:172)
When I display the string I get it looks like this (almost, I had trouble formatting, the mgmtresponse line is all one line, I also blocked out the ip address):
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<mgmtResponse
responseType="operation"requestUrl="https://128.205.x.xxx/webacs/api/v1/op/info/version"
rootUrl="https://128.205.x.xx/webacs/api/v1/op">
-<versionInfoDTO>
<result>2.0.0.0.294</result>
</versionInfoDTO>
</mgmtResponse>
Here is the main section of code. As you can see I tried a bunch of things and commented out a bunch of things to get down to the problem. I am stuck at the point where I can not take my input and convert it to a json object. I think I need to format the response some how but I just can not figure out what is wrong.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Base64;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText etResponse;
TextView tvIsConnected;
static TextView response_code;
static String httpcode;
static String version;
#Override
// oncreate is called when activity is created
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
response_code = (TextView) findViewById(R.id.response_code);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("network is connected");
}
else{
tvIsConnected.setText("network is NOT connected");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("https://128.205.x.xx/webacs/api/v1/op/info/version");
// new HttpAsyncTask().execute("https://hmkcode.appspot.com/rest/controller/get.json");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new MyHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Basic " + Base64.encodeToString
("username:password".getBytes(), Base64.NO_WRAP));
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(request);
final int StatusCode = httpResponse.getStatusLine().getStatusCode();
String st=String.valueOf(StatusCode);
httpcode = st;
//HttpResponse httpResponse = HttpClient.execute(new HttpGet(url));
// receive response as inputStream
//HttpEntity entity = httpResponse.getEntity();
//result = EntityUtils.toString(entity);
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader
(inputStream,"iso-8859-1"),8);
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line+"\n";
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService
(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
// displays results to Edittext and displays recieved to toast
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
response_code.setText(httpcode);
try {
//etResponse.setText(result);
JSONObject json = new JSONObject(result);
//etResponse.setText(json.toString(1));
//JSONObject mgmtResponse =
// new JSONObject(json.getString("mgmtResponse"));
//JSONObject versionInfoDTO =
// new JSONObject(mgmtResponse.getString("versionInfoDTO"));
version = "NCS-Version";
//
//JSONArray articles = json.getJSONArray("articleList"); //get articles array
//str += "articles length = "+json.getJSONArray("articleList").length();
//str += "\n--------\n";
//str += "names: "+articles.getJSONObject(0).names(); //get first articles keys
//str += "\n--------\n";
//str += "url: "+articles.getJSONObject(0).getString("url"); //return an article url
//String str = "NCS Version";
//version += versionInfoDTO.getJSONObject("result");
etResponse.setText(version);
// not - etResponse.setText(json.toString(1));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//etResponse.setText(version);
}
}
}
As Rashmi points out, you are receiving data in XML-format, and attempting to parse it as JSON-format, which is giving you an error. The format of the data can usually be specified in the request URL.
EDIT
Your are using the URL https://128.205.x.xx/webacs/api/v1/op/info/version and I don't know what that is, if it's your own server or not, but usually, APIs provide both XML and JSON formats, which could look something like this:
https://example.com:2087/xml-api/functionname
for XML and
https://example.com:2087/json-api/functionname
for JSON
Some webservices will allow/require you to specify "application/json" as the accept header, so in addition to this:
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Basic " + Base64.encodeToString
("username:password".getBytes(), Base64.NO_WRAP));
Say what you want back:
request.setHeader("Accept", "application/json");
And, if required, what you are supplying:
request.setHeader("Content-type", "application/json");
Related
i have an android program having two fields name and pas which post the data in json format and the response is "data sent." instead of that response i want the name and pass parameters to be checked by my api which is connected to database.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data sent!", Toast.LENGTH_LONG).show();
}
the complete code
package com.hmkcode.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("Email", person.getName());
jsonObject.accumulate("Password", person.getCountry());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://dev.blinkawards.com/blinkawards.RestService/Service1/LoginRequestTemp");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
I have an android login app which post two parameters i.e username and password. These 2 parameters are passed as json. The problem is I m not able to call the .net web api. This api confirms the login details and response I get from the page is id = 0 message "null"
I dont know where i am going wrong.
The complete source code
package com.hmkcode.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are connected");
}
else{
tvIsConnected.setText("You are NOT connected");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject login = new JSONObject();
login.accumulate("Email", person.getName());
login.accumulate("Password", person.getCountry());
// 4. convert JSONObject to JSON to String
json = login.toString();
JSONObject finaldata = new JSONObject();
finaldata.put("LoginRequestTemp", json);
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(),
"Enter some data!",
Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute
("http://dev.blinkawards.com/blinkawards.RestService/Service1/LoginTemp");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(),result , Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString
(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader
( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
I have the following code in my json parser .
I have tried changing from iso-8859-1 to utf-8.
But i always get this error.What have i done wrong??
I could not figure it out of what i have done wrong.
package com.iwantnew.www;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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, "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 used mysql for my database. I am new to android with database. help plz!
My php file looks like this:
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/1
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['quantity']) && isset($_POST['price']) && isset($_POST['descriptions'])) {
//$location = $_POST['location'];
$quantity = $_POST['quantity'];
$price = $_POST['price'];
//$productID = $_POST['area'];
$contact = $_POST['contact'];
$descriptions = $_POST['descriptions'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO room_tb(quantity, price,description) VALUES('$quantity', '$price','$descriptions')");
//$result1 = mysql_query("INSERT INTO users(userContactNumber) VALUES('$contact')");
// check if row inserted or not
if (($result)/*&& ($result1)*/) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Room added successfully.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
MY java file look like this..i have used POST METHod here.
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class post_item extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
Button add_room;
EditText contact_no;
EditText no_of_room;
EditText price_per_room;
EditText description;
private static String url_create_product = "http://10.0.2.2/android_iwant/android_add_room.php";
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_form);
//contact_no = (EditText) findViewById(R.id.contact_no);
no_of_room = (EditText) findViewById(R.id.no_of_room);
price_per_room = (EditText) findViewById(R.id.price_per_room);
description = (EditText) findViewById(R.id.description);
add_room = (Button) findViewById(R.id.add_room);
add_room.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// creating new product in background thread
new add_new_room().execute();
}
});
}
// suru...
class add_new_room extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(post_item.this);
pDialog.setMessage("Saving details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
//String contact = contact_no.getText().toString();
String quantity = no_of_room.getText().toString();
String price = price_per_room.getText().toString();
String descriptions = description.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("contact", contact));
params.add(new BasicNameValuePair("quantity", quantity));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("descriptions", descriptions));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Blackbelt and Nizam covered the Java side of your problem. I'll cover the PHP side.
The biggest error in your PHP script seems to be the following (unless it's just a copy & paste error):
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/1
^
|
The number 1 does not belong here
Instead of a JSON string output your PHP script probably just aborts with a syntax error message.
On top of that you have a SQL injection vulnerability in your PHP script. Learn how to use prepared statements.
EDIT: Another mistake I spotted in your PHP script:
if (isset($_POST['quantity']) && isset($_POST['price']) && isset($_POST['descriptions'])) {
You check if the POST parameter "descriptions" is set. It should be "description" without 's' in the end.
Mostly your mistake is in those lines:
if(method == "POST"){
}else if(method == "GET")
String comparison in java has to be performed with the equals or equalsIgnoreCase method. In your case, the InputStream is is null, and it is never initialize. So you are trying to convert an empty string, the one the StringBuilder.toString() is returning, into a JSONObject.
Edit:
Change
if(method == "POST"){
}else if(method == "GET")
with
if(method.equalsIgnoreCase("POST")){
// your code
}else if(method.equalsIgnoreCase("GET"))
// your code
and see if it makes any difference (at least the error should change)
First, make it if(method.equalsIgnoreCase("post")) as 'blackbelt' suggested. One more suggestion-
While receiving some text(whether JSON or not) from server, I'll prefer always check the response before doing any action with it.
Here, try
HttpEntity httpEntity=httpResponse.getEntity();
String all=EntityUtils.toString(httpEntity);
Log.d("response",all);
i am working on an app using json parsing...in this parsing is done by json of the given url.
As i run my project on emulator having target = "Google APIs (Google Inc.) - API level 10"
then it runs properly and shows needed results from the target url.
but when run my project on emulator having target = "Google APIs (Google Inc.) - API level 16"
then it shows error and it never parse the given url data and get force close.
i want to make app which run on every API level.
please help...
here's my code:
json parser class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
static String req = "POST";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url, String method) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
if(method == req) {
HttpPost httpC = new HttpPost(url);
httpResponse = httpClient.execute(httpC);
}else {
HttpGet httpC = new HttpGet(url);
httpResponse = httpClient.execute(httpC);
}
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 JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Another class using json parser class snd fetch data:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class showData extends ListActivity{
public static String url = "http://something/something/";
public static final String TAG_A = "a";
public static final String TAG_B = "b";
public static final String TAG_C = "c";
public static final String TAG_D = "d";
public static final String TAG_E = "e";
public static final String TAG_F = "f";
public static final String GET = "get";
JSONArray Data1 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
EditText editext_text = (EditText) findViewById(R.id.et);
String urlnew = url + editext_text.getText().toString();
Log.d("url", urlnew);
JSONParser jParser = new JSONParser();
// getting JSON string from URL
area1 = jParser.getJSONFromUrl(urlnew, GET);
Log.d("Json String", area1.toString());
try {
for(int i = 0; i < area1.length(); i++){
JSONObject c = area1.getJSONObject(i);
// Storing each json item in variable
String a = c.getString(TAG_A);
String b = c.getString(TAG_B);
String c = c.getString(TAG_C);
String d = c.getString(TAG_D);
String e = c.getString(TAG_E);
HashMap<String,String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_A, a);
map.put(TAG_B, b);
map.put(TAG_C, c);
map.put(TAG_D, d);
map.put(TAG_E, e);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item_area,
new String[] { TAG_B, TAG_A, TAG_C, TAG_D, TAG_E }, new int[] {
R.id.b, R.id.a, R.id.c, R.id.d, R.id.e });
setListAdapter(adapter);
}
}
You are getting a NetworkOnMainThreadException because as the name is self-explaining, you are doing network request on UI Thread that will make your application laggy and create an horrible experience.
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it's heavily
discouraged. See the document Designing for Responsiveness.
You should use Threads or AsyncTask, do you need some explanations on how to use them?
private class NetworkTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//DO YOUR STUFF
}
#Override
protected void onPostExecute(String result) {
//Update UI
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
This is Network On Main Thread Exception, You have to use Thread for network connection, because the main thread is UI thread will not give any response for Network connection. Use separate thread for network connection
I am currently trying to translate the code for the MainActivity of an app that I created in API10 into API 16. From what I have read, I have to start using ASyncTask to access a URI and display the information on my app. I managed to do that in 2.3, but after translating it to JSON, I am now facing some roadblocks.
Essentially, what the app does is that, it takes a manifest code i.e. WAMF33000 and at the click of a button, the Spinner is populated with the jobs contained in that manifest. As I am fairly new to the concept of ASyncTask, I would like to understand how my code applies to the theory behind ASyncTask.
Based on my code, I have some questions:-
i) Which of my code in the ASyncTask is the parameter that is being passed?
ii) What is the progress value in my AsyncTask?
iii) Finally, is my return value the ArrayList of ManifestItems?
As of the 2.3 version, I invoke the JSON twice - once to load the consignments within the Manifest, and the second time to load details of a consignment selected in the spinner.
The following is my code:
package com.signonglass;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private final static String POD_URI = "http://192.168.0.105:8092/PodCore.svc";
private EditText evManifestCode;
private Spinner list_job;
private Button btnSubmit;
private String jobName;
private Button btnCons;
ArrayList<ManifestItemObj> jobList = new ArrayList<ManifestItemObj>();
ArrayList<ConsignmentItems> conItemList = new ArrayList<ConsignmentItems>();
Consignments retConsignment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
evManifestCode = (EditText)findViewById(R.id.manifest);
btnSubmit = (Button)findViewById(R.id.btnSearchManifest);
list_job = (Spinner)findViewById(R.id.jobSpinner);
//tvView = (TextView)findViewById(R.id.deviceIdt);
//TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
//String IMEI_Number = telephonyManager.getDeviceId();
//tvView.setText("IMEI Number: " + IMEI_Number);
}
public class MyAsyncTask extends AsyncTask<String, Void, ArrayList<ManifestItemObj>>
{
protected void onPreExecute()
{
}
protected void onPostExecute(ArrayList<ManifestItemObj> jobList)
{
}
#Override
protected ArrayList<ManifestItemObj> doInBackground(String... params)
{
//http get request
HttpGet request = new HttpGet(POD_URI + "/getJobs/" + evManifestCode.getText().toString());
//set the hedear to get the data in JSON format
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
String theString = new String("");
try
{
//get the response
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
is.close();
theString = builder.toString();
JSONObject jobsJSON = new JSONObject(theString);
JSONArray jobs = jobsJSON.getJSONArray("getJobsResult");
for(int i = 1; i < jobs.length(); i++)
{
JSONObject mit = jobs.getJSONObject(i);
ManifestItemObj mi = new ManifestItemObj();
mi.ManifestItemID = mit.getInt("ManifestItemID");
mi.JobType = mit.getString("JobType");
mi.FKID = mit.getInt("FKID");
jobList.add(mi);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return jobList;
}
}
/*private void showToast(String msg)
{
// TODO Auto-generated method stub
Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
}*/
public void onViewConsignment(View view)
{
ShowItemsOfManifest(retConsignment);
}
public Consignments getConsignmentManifest(String consignment)
{
Consignments con = new Consignments();
try
{
DefaultHttpClient client = new DefaultHttpClient();
String theString = new String("");
//http get request
HttpGet request = new HttpGet(POD_URI + "/getJobDetails/" + consignment);
//set the hedear to get the data in JSON format
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
//get the response
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
is.close();
theString = builder.toString();
JSONObject conJSON = new JSONObject(theString);
JSONArray cons = conJSON.getJSONArray("getJobDetailsResult");
for(int i = 0; i < cons.length(); i++)
{
JSONObject cObj = cons.getJSONObject(i);
con.ConsignmentID = cObj.getInt("ConsignmentID");
con.ConsignmentCreationDate = cObj.getString("ConsignmentCreationDate");
con.ConsignmentCustRef = cObj.getString("ConsignmentCustRef");
con.OrderNo = cObj.getString("OrderNo");
con.ConsignmentActive = cObj.getBoolean("ConsignmentActive");
con.JobType = cObj.getString("JobType");
//Client object
JSONObject clObj = cObj.getJSONObject("Client");
Clients cl = new Clients();
cl.ClientId = clObj.getInt("ClientID");
cl.ClientName = clObj.getString("ClientName");
con.Clients = cl;
//ShipTo object
JSONObject stObj = cObj.getJSONObject("ShipTo");
ShipTo sto = new ShipTo();
sto.ShipToId = stObj.getInt("ShipToId");
sto.ShipToName = stObj.getString("ShipToName");
sto.ShipToAddress1 = stObj.getString("ShipToAddress1");
sto.ShipToAddress2 = stObj.getString("ShipToAddress2");
sto.ShipToCity = stObj.getString("ShipToCity");
sto.ShipToPostcode = stObj.getString("ShipToPCode");
sto.ShipToState = stObj.getString("ShipToState");
con.ShipTo = sto;
//FreightZone object
JSONObject fzObj = cObj.getJSONObject("FreightZone");
FreightZones fz = new FreightZones();
fz.FreightZoneID = fzObj.getInt("FreightZoneId");
fz.FreightZone = fzObj.getString("FreightZone");
con.FreightZone = fz;
JSONArray conItems = cObj.getJSONArray("ConsignmentItems");
for(int m = 0; m < conItems.length(); m++)
{
JSONObject cit = conItems.getJSONObject(m);
ConsignmentItems ci = new ConsignmentItems();
ci.ConsignmentItemID = cit.getInt("ConsignmentItemsID");
ci.Quantity = cit.getInt("QTY");
//get Product from ConsignmentItems
JSONObject pro = cit.getJSONObject("Products");
Products prod = new Products();
prod.ProductId = pro.getInt("ProductID");
prod.ProductModel = pro.getString("ProductModel");
prod.ItemsPerCarton = pro.getInt("PerCarton");
prod.ProductDescription = pro.getString("Description");
prod.Height = (float) pro.getDouble("Height");
prod.Length = (float) pro.getDouble("Length");
prod.Width = (float) pro.getDouble("Width");
prod.Cubic = (float) pro.getDouble("Cubic");
ci.Product = prod;
conItemList.add(ci);
con.ConsignmentItems = conItemList;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
public void ShowItemsOfManifest(Consignments consignments)
{
Bundle bundle = new Bundle();
Intent newIntent = new Intent(this.getApplicationContext(), ConActivity.class);
newIntent.putExtras(bundle);
newIntent.putExtra("Consignment", consignments);
this.startActivity(newIntent);
}
public void onSearchClick(View view)
{
new MyAsyncTask().execute();
ManifestItemAdapter mia = new ManifestItemAdapter(MainActivity.this, android.R.layout.simple_spinner_item, jobList);
list_job.setAdapter(mia);
}
}
I look forward to understanding more about ASyncTask through your constructive comments on my code. Thanks ahead for helping me improve my code and my understanding of Android, guys! :)
PS: Please let me know if you need any more code to work with. I will update my post with more information as necessary. Cheers!
The point behind AsyncTask is to allow you to run background work on a separate thread such as networking stuff so you don't hold up the UI and users can still do things while data is being downloaded.
Which of my code in the ASyncTask is the parameter that is being passed?
You currently are not passing any params to the AsyncTask
new MyAsyncTask().execute(); // you would put params in here if needed such as a URL, String, etc...
What is the progress value in my AsyncTask?
As far as I can tell, you don't have one. If you wanted to you could use publishProgress(value) and that would be sent to onProgressUpdate() to update things like files downloaded, time of progression, time left, etc...
Finally, is my return value the ArrayList of ManifestItems?
you are returning jobList so that is what will get sent to onPostExecute() to do what you need with it
Note: One of the most important things to understand about AsyncTask is that you can't update the UI from doInBackground() so you must do this in one of the other AsyncTask methods or pass values back to a UI function. Also, AsyncTask works differently in 2.3 than it does in 3.0 and beyond. They don't run in parallel any more but put into a queue. So you may want to read about executeOnExecutor() if you want them to run in parallel in 4.2. I hope this answers your questions
AsyncTask
executeOnExecutor()(http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor(java.util.concurrent.Executor, Params...)
A couple other things I see is that you will want to add the #Override annotation to the implemented methods as well as super calls.