get json as result in android - java

I have an android code which i am sharing below. in the ninth step i.e step 9 can the input stream be converted into json before the result is displayed in the last step. If yes how? . please help i just want the result should be what i get from the url. i am getting result as an Xml till now
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);
//etTwitter = (EditText) findViewById(R.id.etTwitter);
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("pass", person.getCountry());
//jsonObject.accumulate("twitter", person.getTwitter());
// 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.myurl");
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());
//person.setTwitter(etTwitter.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 if(etTwitter.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;
}
}

/*Try using Gson library to prepare Json string from your service, sample code is given below
JsonObject myObj = new JsonObject(); //Create Json Object
myObj.addProperty("Email", person.getName()); //Add properties to your Json object
myObj.addProperty("pass", person.getCountry());
return new Gson().toJson(myObj); //Convert Json Object to String and return from your service*/
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String resp = null;
JsonObject myObj = null;
if (entity != null) {
resp = EntityUtils.toString(entity);
Gson gson = new Gson();
myObj = gson.fromJson(resp, JsonElement.class).getAsJsonObject();
}

Related

doInbackground of asyncktask is not called

This url is executed when a button is clicked
new HttpAsyncTasks().execute("http://www.demo.com/xyz");
this is the asynctask for the above execution
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return POSTS(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "successfull!", Toast.LENGTH_LONG).show();
//call main activity activity upon successful registration
Intent callMain = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(callMain);
}
}
The doInbackground of the above never gets executed but the onPostExecute method does.
this is the POSTS method called in doInbackground
public String POSTS(String url){
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("xyz", "xyz");
jsonObject.accumulate("amount", "800");
jsonObject.accumulate("demo", "demo");
jsonObject.accumulate("demo2", demo2);
// 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;
}
Please what could be wrong?
Can you try this with way. It's checking your POSTS method.
If toast show empty line, your error in POSTS method on WebProcess.
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
private String myResult="check";
#Override
protected String doInBackground(String... urls) {
try
{
myResult = POSTS(urls[0]);
}
catch(Exception e)
{
return e;
}
return myResult;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
/* other codes */
}
}
Your POSTS(urls[0]) call must be giving an exception and when it does the rest of the code is skipped and it bypasses your toast. Try removing exception you can find it in logcat.

Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject in android?

I am trying to access a json array from android. But it shows an exception. This is my android code used for retrieving the json array:
protected void showList(){
final String TAG_RESULTS="result";
final String TAG_USERNAME="username";
final String TAG_NAME = "message_recd";
final String TAG_ADD ="message_sent";
ArrayList<HashMap<String, String>> personList;
personList = new ArrayList<HashMap<String,String>>();
//for tesitng
JSONObject jObject=null;
//
try {
//for testing
//
JSONObject json = new JSONObject(myJSON);
JSONArray peoples =json.getJSONArray("emparray");
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
name = c.getString("user_id");
address = c.getString("crtloc_lat");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put("user_id",name);
persons.put("crtloc_lat",address);
personList.add(persons);
Toast.makeText(MapsActivity.this, "woow id"+name, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("errore",e.toString());
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("username", fName));
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://abh.netai.net/abhfiles/searchProfession.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
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();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
php file
<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);
$pro_id=0;
$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($con);
?>
and the json array
[[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769566","crtloc_lng":"72.361031"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]
the error it show me is this
Value [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769749","crtloc_lng":"72.361168"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}] of type org.json.JSONArray cannot be converted to JSONObject
It is giving you this error because the first object in the array is not a JSONObject but an JSONArray following 4 JSONObjects.
[
[],
{
"user_id": "77",
"crtloc_lat": "34.769638",
"crtloc_lng": "72.361145"
},]
As you can see you expect it to always be a JSONObject.
JSONObject c = peoples.getJSONObject(i);
Anticipate on that first JSONArray in the list.

post data in json format to php script with java

I'm trying to POST data in JSON format to a script I have running PHP on my webserver. I have found this post: How to send data to a website using httpPost, app crashes.
Using the code he wrote (putting it on a separate thread first) I am able to post data to the PHP script, which accesses it by the $_POST variable. However, I wish to post my data in JSON format. I am guessing it would require me to post a raw stream of data to the server. What functions are available to achieve this? I would also need to post images as a stream of data to the PHP script so I think this solution will also help me in that area.
Additionally, what are the advantages of posting JSON to the server rather than using the method he used?
I am programming the client side in Java in conjunction with the Android SDK.
Any help would be appreciated.
I have a sample example for posting json data .
Have a look at this:
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private Context mContext;
private Intent mIntent;
private ProgressDialog pdLoading;
private class LoginTask extends AsyncTask<Void, Void, String>
{
private ArrayList<NameValuePair> mParams = new ArrayList<NameValuePair>();
private JSONArray mJArray = new JSONArray();
private JSONObject mJobject = new JSONObject();
private String jsonString = new String();
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.show();
}
#Override
protected String doInBackground(Void... params) {
try {
mJobject.put("userName", "test");
mJobject.put("password", "test");
mJArray.put(mJobject);
mParams.add(new BasicNameValuePair("message", mJArray.toString()));
jsonString = WebAPIRequest.postJsonData("http://putyoururlhere.com/login.php?", mParams);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return jsonString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdLoading.dismiss();
if(result!=null)
{
/* try {
mJobject = new JSONObject(jsonString);
if(mJobject.getString("Success").equals("True"))
{
mJArray = mJobject.getJSONArray("user");
JSONObject mUser = mJArray.getJSONObject(0);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Log.e(TAG, jsonString);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialization();
new LoginTask().execute();
}
private void initialization() {
mContext = this;
mIntent = new Intent();
pdLoading = new ProgressDialog(mContext);
pdLoading.setMessage("loading...");
}
}
and
public class WebAPIRequest {
public static String convertStreamToString(InputStream is)
throws IOException {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
public static String postJsonData(String url, List<NameValuePair> params) {
String response_string = new String();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
try {
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
String sampleurl = url + "" + paramString;
Log.e("Request_Url", "" + sampleurl);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
InputStream in = response.getEntity().getContent();
response_string = WebAPIRequest.convertStreamToString(in);
}
} catch (Exception e) {
e.printStackTrace();
}
return response_string;
}
}
EDIT :
try,
print_r(json_decode($_POST['message'], true);
or
$data = file_get_contents('php://input');
$json = json_decode($data,true);
I hope it will be helpful !!

JSONException: no value for data

I want to fetch json data from this link: link
& here is my code for that:
private static String url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27https://www.facebook.com/BillionHands%27";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_SHARE = "share_count";
private static final String TAG_LIKE = "like_count";
private TextView LikeTv;
public String like;
JSONArray data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing each json item in variable
String share = c.getString(TAG_SHARE);
like = c.getString(TAG_LIKE);
Log.i("Like Count",like);
} catch (JSONException e) {
e.printStackTrace();
}
LikeTv = (TextView) findViewById(R.id.tvLike);
LikeTv.setText(like);
Now I am getting "JSONException: no value for data" Please help... whats wrong in my code..
Well....
I got your problem solution...
The method you wrote getJSONFromUrl()..
I am sure it contains HttpPost object..
change that to HttpGet and it will start working...
EDIT
Here is the code I tried with
public class MainActivity extends Activity {
private static String url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27https://www.facebook.com/BillionHands%27";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_SHARE = "share_count";
private static final String TAG_LIKE = "like_count";
private TextView LikeTv;
public String like;
JSONArray data = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONfromURL(url);
try {
// Getting Array of Contacts
Log.d("JSON ","DATA "+json);
data = json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing each json item in variable
String share = c.getString(TAG_SHARE);
like = c.getString(TAG_LIKE);
Log.i("Like Count",like);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
class JSONParser
{
public JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
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, "iso-8859-1"), 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 get data string ",
"Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag create object ",
"Error parsing data " + e.toString());
}
return jArray;
}
}
The "data" element in your JSON isn't an array, it is a JSONobject. So instead of:
JSONArray data = json.getJSONArray(TAG_DATA);
Try this:
JSONObject data = json.getJSONObject(TAG_DATA);
From the JSONObject, you can get items like TAG_SHARE and TAG_LIKE.
Good luck!

App doesn't retrieve JSON data from PHP webservice. Webservice works fine

My app doesn't seem to pull the JSON data from PHP webservice properly.
Visiting the webservice's function to get all data records from database produces JSON properly, but my app can't grab that data and seems to end up with NullPointerException.
LogCat issues me this:
Update:
Noticed this error in yellow that happens before the below errors:
W/System.err(835): org.apache.http.conn.HttpHostConnectException:
Connection to http:// localhost refused
If I can't connect to the webservice on my localhost then I'm not getting the JSON to my app. But why would it refuse connection to localhost?
W/System.err(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:113)
W/System.err(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:1)
E/AndroidRuntime(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:116)
E/AndroidRuntime(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:1)
E/WindowManager(1159): at
com.example.myfirstapp.MainActivity$LoadAllCars.onPreExecute(MainActivity.java:103)
Line 113: JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);
Line 116: Log.d("All Cars: ", json.toString());
MainActivity
package com.example.myfirstproject;
//imports
public class MainActivity extends ListActivity implements OnItemClickListener {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> carsList;
// url to get all products list
private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CARS = "cars";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray cars = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
carsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllcars().execute();
// Get listview
ListView lv = getListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllcars extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading cars. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);
// Check your log cat for JSON reponse
Log.d("All cars: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
cars = json.getJSONArray(TAG_CARS);
// looping through All Products
for (int i = 0; i < cars.length(); i++) {
JSONObject c = cars.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
carsList.add(map);
}
} else {
// no products found
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("No cars found");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, carsList,
android.R.id.list, new String[] {TAG_NAME},
new int[] { R.id.title });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
EDIT
JSONParser:
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 think your problem may be that you never put anything in params. It's just an empty List.
Well if you are getting a null pointer exception on this line
JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);
then 1 or more of them things must be null. The jParser is instantiated, the url string is also, the params is as a list however there is nothing in the list. Have a look inside the jParser and see what is happening with that list of params. Do you need them? Does it need them?
EDIT
So the jParser is converting your list(which is empty) to a string with string builder. Which is returning an empty sting.
so your url when it is sent to your server looks like this
http://localhost/webservice/get_all_cars.php?
So the normal url but with a question mark on it. Is that correct?
It would make sense to log the statuscode and status reason from your httpresponse so you can see what the server is responsing you would do that like so...
Log.d("Class Name", "Status code: " + httpResponse.getStatusLine().getStatusCode() + " Status Phrase: " + httpResponse.getStatusLine().getReasonPhrase());
EDIT
The url is set to "localhost" so I presume it is looking within the device rather than at your server. Put in the ip of your server instead
Problem was here:
private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";
Can't use localhost because the emulated phone itself is localhost/127.0.0.1
You need to change localhost to 10.0.2.2:
private static String url_all_cars = "http://10.0.2.2/webservice/get_all_cars.php";

Categories