JSON to Android error - java

I have a successfully converted data from database into json format, my json data is as follows
{"room":[{"id":"1044","location":"kathmandu","title":"room room rome",
"quantity":"2","price":"1000","contact":"9811111111","area":"1500",
"description":"kjkfs ksdjfsd kj","address":"kat"}],"success":1}
I want to view these data on android, my json parser code is
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;
}
}
my view room java file is intended to extract the json data
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
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.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class viewroom extends ListActivity {
// url to make request
private static String url = "http://10.0.2.2/iWant/src/android_view_all_room.php";
// JSON Node names
private static final String TAG_ROOM = "room";
// private static final String TAG_SUCCESS = "success";
private static final String TAG_ID = "id";
private static final String TAG_LOCATION = "location";
private static final String TAG_TITLE = "title";
private static final String TAG_QUANTITY = "quantity";
private static final String TAG_PRICE = "price";
private static final String TAG_CONTACT = "contact";
private static final String TAG_AREA = "area";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ADDRESS = "address";
// contacts JSONArray
JSONArray room = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_room);
// Hashmap for ListView
ArrayList<HashMap<String, String>> roomList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
try {
// Getting Array of Contacts
room = json.getJSONArray(TAG_ROOM);
// looping through All Contacts
for(int i = 0; i < room.length(); i++){
JSONObject c = room.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String location = c.getString(TAG_LOCATION);
String quantity = c.getString(TAG_QUANTITY);
String address = c.getString(TAG_ADDRESS);
String price = c.getString(TAG_PRICE);
String contact = c.getString(TAG_CONTACT);
String area = c.getString(TAG_AREA);
String description = c.getString(TAG_DESCRIPTION);
String title = c.getString(TAG_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_LOCATION, location);
map.put(TAG_QUANTITY, quantity);
map.put(TAG_ADDRESS, address);
map.put(TAG_PRICE, price);
map.put(TAG_CONTACT, contact);
map.put(TAG_AREA, area);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
roomList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, roomList,
R.layout.list_room,
new String[] { TAG_TITLE, TAG_LOCATION, TAG_PRICE }, new int[] {
R.id.title, R.id.location, R.id.price });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String location = ((TextView) view.findViewById(R.id.location)).getText().toString();
String price = ((TextView) view.findViewById(R.id.price)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleRoomActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_PRICE, price);
startActivity(in);
}
});
}
}
the singleroom activity class is intended to show data about clicked room only,
it is as follows
package com.iwantnew.www;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleRoomActivity extends Activity {
private static final String TAG_TITLE = "title";
private static final String TAG_LOCATION = "location";
private static final String TAG_PRICE = "price";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_room);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String title = in.getStringExtra(TAG_TITLE);
String location = in.getStringExtra(TAG_LOCATION);
String price = in.getStringExtra(TAG_PRICE);
// Displaying all values on the screen
TextView lblTitle = (TextView) findViewById(R.id.title_label);
TextView lblLocation = (TextView) findViewById(R.id.location_label);
TextView lblPrice = (TextView) findViewById(R.id.price_label);
lblTitle.setText(title);
lblLocation.setText(location);
lblPrice.setText(price);
}
}
and here is the log cat error i get. :(
http://pastebin.com/q4yQxKvF

According to your code one Exception Which you will be getting is NetworkOnMainThreadException
Because you are performing Network operations on Main UI Thread
to Avoid it use AsyncTask inside view room java file
Check Example here AsyncTask Android example

Try using the below code inside your viewroom activity below setContentView() to avoid networkOnmainThread exception..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
But, doing heavy operation inside background thread using AsyncTask without blocking main thread would be great!

With ICS & beyond, you can't make network calls on the main thread (as you've noticed, it throws an error), which is why you need to use something like AsyncTask; or, you can create a new thread (using the Runnable class) to make your network call. Either way, you are not making the http call on the main thread. Even if you aren't using an ICS or JB device, you should never make network calls on the main thread.
From the Android docs:
Network operations can involve unpredictable delays. To prevent this
from causing a poor user experience, always perform network operations
on a separate thread from the UI. The AsyncTask class provides one of
the simplest ways to fire off a new task from the UI thread.
Here is that link: http://developer.android.com/training/basics/network-ops/connecting.html

Related

how can i fix the error when JSONException was detected while i try to connect to Mysql?

I try to connect to mysql.
I catch the exception on ligne "jObj = new JSONObject(json);" by used "pDialog.setMessage("7777");" because the application wass stopped when pDialog show "7777"
this is my class
JSONParser.java
package com.larig2.test;
/**
* Created by GNassro on 26/02/2018.
*/
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.app.ProgressDialog;
import android.util.Log;
import java.util.Date;
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 mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params,ProgressDialog pDialog) {
// 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 (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
//convert byte-stream to character-stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
//close the input stream
is.close();
json = sb.toString();
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
pDialog.setMessage("7777");
pDialog.show();
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
pDialog.setMessage("00000");
pDialog.show();
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
pDialog.setMessage("99999");
pDialog.show();
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
Signin_Client.java
package com.larig2.test;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.content.Intent;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
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 Signin_Client extends AppCompatActivity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputNom;
EditText inputPrenom;
EditText inputCIN;
EditText inputJour;
Spinner inputMois;
EditText inputAnnee;
Spinner inputAdresse;
EditText inputTel;
EditText inputMail;
EditText inputPwd;
//attribute string
String nom;
String prenom;
String cin;
String jour;
String mois;
String annee;
String sexe;
String adresse;
String tel;
String mail;
String pwd;
String date;
// url to create new product
private static String url_create_product = "http://192.168.1.177/Karhabti/signup_client.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin__activity_client);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Intent contactus = new Intent(this, Contactez_nous.class);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(contactus);
}
});
//Spinner for Address Start ****
Spinner spinner = (Spinner) findViewById(R.id.adresse);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Tunisia_State, R.layout.spinnerthem1);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
adapter.setDropDownViewResource(R.layout.spinnerthem);
spinner.setAdapter(adapter);
//Spinner for Address End ****
//Spinner for Months Date Start ****
Spinner spinnerMonths = (Spinner) findViewById(R.id.mois);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterMonths = ArrayAdapter.createFromResource(this,
R.array.Mois_Date, R.layout.spinnerthem1);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
adapterMonths.setDropDownViewResource(R.layout.spinnerthem);
spinnerMonths.setAdapter(adapterMonths);
//Spinner for Months Date End ****
//select input
inputNom = (EditText) findViewById(R.id.nom);
inputPrenom = (EditText) findViewById(R.id.prenom);
inputCIN = (EditText) findViewById(R.id.CIN);
inputJour = (EditText) findViewById(R.id.jour);
inputMois = (Spinner) findViewById(R.id.mois);
inputAnnee = (EditText) findViewById(R.id.annee);
inputAdresse = (Spinner) findViewById(R.id.adresse);
inputTel = (EditText) findViewById(R.id.tel);
inputMail = (EditText) findViewById(R.id.mail);
inputPwd = (EditText) findViewById(R.id.pwd);
}
public void signupClickC(View view) {
cin = inputCIN.getText().toString();
new CreateNewClient().execute();
}
/**
* Background Async Task to Create new product
* */
class CreateNewClient extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Signin_Activity_client.this);
pDialog.setMessage("Creation en cours ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nomC", "Med"));
params.add(new BasicNameValuePair("prenomC", "Ali"));
params.add(new BasicNameValuePair("CIN", cin));
params.add(new BasicNameValuePair("date","1999-11/11" ));
params.add(new BasicNameValuePair("sexe", "h"));
params.add(new BasicNameValuePair("adresse", "gafsa"));
params.add(new BasicNameValuePair("tel", "556"));
params.add(new BasicNameValuePair("mail", "khhg"));
params.add(new BasicNameValuePair("psw", "kdlkdj"));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params, pDialog);
pDialog.setMessage("22222");
pDialog.show();
// 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(), ClientSpace.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();
}
}
}
my question is how to fix this exception Although the insert to Mysql was successful ?
you should create pDialog object in JsonPArser class instead of passing as a parameter..
in JsonParser Class use this code below and dont use two prgressDialog at the same time.ProgressDialog pd = new ProgressDialog(context);
progressDialog.setMessage(your message);

null pointer exception error in http POST request JSON object

I am doing android coding and sending a http POST request using httpClient. and it is giving me a null point expception error at the line
httpEntity = httpResponse.getEntity();
i used log cat and found that my code was stopping at the line mentioned above. please help me out with it. thanks in advance.
my code is for the establishment of http client is in the file serviceHandler:
package com.example.manumaheshwari.vigo;
/**
* Created by ManuMaheshwari on 30/06/15.
*/
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
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.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
StringBuilder sb;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded ");
if (params != null) {
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response: ", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
and the code for my main activity is as follows:
package com.example.manumaheshwari.vigo;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get pending rides JSON
private static String url = "http://128.199.206.145/vigo/v1/displayalldrivers";
// JSON Node names
private static final String TAG_SOURCE = "source";
private static final String TAG_DESTINATION = "destination";
private static final String TAG_DRIVER_ID = "driver_id";
private static final String TAG_NAME = "name";
// pending rides JSONArray
JSONArray pendingRides = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> pendingRidesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pendingRidesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Calling async task to get json
new GetRides().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Async task class to get json by making HTTP call
* */
private class GetRides extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("contractor_id", "1"));
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST, nameValuePairs);
Log.d("Response: " , "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
pendingRides = jsonObj.getJSONArray("driver");
// looping through All Contacts
for (int i = 0; i < pendingRides.length(); i++) {
JSONObject c = pendingRides.getJSONObject(i);
String source = c.getString(TAG_NAME);
String destination = c.getString(TAG_DRIVER_ID);
// tmp hashmap for single contact
HashMap<String, String> pendingRide = new HashMap<String, String>();
// adding each child node to HashMap key => value
pendingRide.put(TAG_NAME, source);
pendingRide.put(TAG_DRIVER_ID, destination);
// adding pending ride to pending ride list
pendingRidesList.add(pendingRide);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, pendingRidesList,
R.layout.list_view, new String[] { TAG_SOURCE, TAG_DESTINATION,}, new int[] { R.id.source,R.id.destination});
setListAdapter(adapter);
}
}
}
It seems that httpResponse is null,because in POST method you didn't assign any value to it.So in POST method,change
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response: ", response.toString());
to
httpResponse = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response: ", httpResponse.toString());

How do I pass parameter to webservice and get json datas in listview

Hi (fresher to andorid)
I'm developing an android application which will use the webservice which should accept 1 parameter from the user and based on that the value is fetched datas from DB(sql server 2008) and bind that to android:LISTVIEW.
Without using the parameter my android application is working fine.But when i altered my webserservice to accept parameter and call it in android it is not displaying the result based on the given value instead of that it displays all values.
Here is my webservice code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class JService : System.Web.Services.WebService
{
public JService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void Cargonet(string jobno)
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT id,name,salary,country,city FROM EMaster where age = '" + jobno + "'";
cmd.CommandText = "SELECT [Id] as Id,[Status] as status ,[DateTime] as DateTime FROM [Attendance].[dbo].[cargo] WHERE JobNo= '" + jobno + "' ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
Here is my android code(Main.java):
package com.example.cargotracking;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView Id;
TextView Status;
TextView DateTime;
Button Btngetdata;
String JobNo;
EditText editText1;
ArrayList<HashMap<String, String>> CargoTracklist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://ip/testing/TrackId.asmx/Cargonet";
//JSON Node Names
private static final String TAG_CargoTrack = "Cargo";
private static final String TAG_Id = "Id";
private static final String TAG_Status = "Status";
private static final String TAG_DateTime = "DateTime";
JSONArray Cargo = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
// List params = new ArrayList();
params.add(new BasicNameValuePair("JobNo","01"));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my json parser code:
package com.example.cargotracking;
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.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
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() {
}
//public JSONObject getJSONFromUrl(String url, List params) {
public JSONObject getJSONFromUrl(String url, List<BasicNameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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;
}
}
please help me to resolve this.
Thanks in advance

Android - Get HTTP Post Response in other activity

I created two activities one contains some text fields which accepts data. From other activity(Async Task) this data is sent to the server and gets the response from the server.
I am able to log the response but unable to store that response in variable and user in other activities. Is there any way to do that?
Here is one activity,
RegisterDevice.java
package sys.darpan.tracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegisterDevice extends Activity{
EditText regEmail, regPassword, regImei, regDeviceName, regVehicleNumber;
Button regButton;
AsyncRegisterDevice asd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_device);
regEmail = (EditText)findViewById(R.id.regEmail);
regPassword = (EditText)findViewById(R.id.regPassword);
regVehicleNumber = (EditText)findViewById(R.id.regVehicleNum);
regImei = (EditText)findViewById(R.id.regImei);
regDeviceName = (EditText)findViewById(R.id.regDeviceName);
regButton = (Button)findViewById(R.id.regButton);
regImei.setText("165465416416416");
regDeviceName.setText("GT-I9300");
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerDevice();
}
});
}
protected void registerDevice(){
asd = new AsyncRegisterDevice();
String email = regEmail.getText().toString();
String password = regPassword.getText().toString();
String imei = regImei.getText().toString();
String deviceName = regDeviceName.getText().toString();
String vehicleNo = regVehicleNumber.getText().toString();
String aobj[] = new String[5];
aobj[0] = email;
aobj[1] = password;
aobj[2] = vehicleNo;
aobj[3] = imei;
aobj[4] = deviceName;
asd.execute(aobj);
}
}
Here is Async Task,
package sys.darpan.tracking;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.util.Log;
public class AsyncRegisterDevice extends AsyncTask<String, String, String> {
String sb;
String finalResult;
#Override
protected String doInBackground(String... params) {
String email = params[0];
String password = params[1];
String vnumber = params[2];
String imei = params[3];
String deviceName = params[4];
DefaultHttpClient defaulthttpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://logicvibes.com/vts/register-device.php");
ArrayList<BasicNameValuePair> arraylist = new ArrayList<BasicNameValuePair>(5);
arraylist.add(new BasicNameValuePair("email", email));
arraylist.add(new BasicNameValuePair("pass", password));
arraylist.add(new BasicNameValuePair("vno", vnumber));
arraylist.add(new BasicNameValuePair("imei", imei));
arraylist.add(new BasicNameValuePair("dname", deviceName));
try
{
httppost.setEntity(new UrlEncodedFormEntity(arraylist));
httppost.getAllHeaders();
}
catch (UnsupportedEncodingException unsupportedencodingexception)
{
unsupportedencodingexception.printStackTrace();
}
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = defaulthttpclient.execute(httppost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
sb = stringBuilder.toString();
Log.d("Custom resp: ", sb);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String sb) {
Log.d("RESULT", "Result : " + sb);//this returns NULL
finalResult = sb;
}
public String getFinalResult() {
return finalResult;
}
}
I searched a lot but no luck, please tell me the proper way to do this.
Solved it by using,
try {
asd.execute(aobj).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
The main thread waits until the async task finished processing. (good for short processes)

NullPointerException in Android JSONParser

I have an android application that crashes whenever I press the Login button; I keep getting a Null Pointer Exception in my JSONParser. I really hope you can help.
Here is my UserFunctions.java:
package com.example.sabre9.library;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.content.Context;
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://10.0.2.2/Sabre1/";
//private static String registerURL = "http://10.0.2.2/Sabre1/";
private static String login_tag = "login";
//private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(loginURL, "POST", params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Register Request
* #param name
* #param email
* #param password
* */
/*
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
//getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(registerURL, "POST", params);
// return json
return json;
}*/
/**
* Function get Login status
**/
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
JSONParser.java:
package com.example.sabre9.library;
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 mehtod
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;
}
}
And here are my logcat errors:
02-13 03:15:01.921: E/Buffer Error(1263): Error converting result java.lang.NullPointerException: lock == null
02-13 03:15:01.931: E/JSON Parser(1263): Error parsing data org.json.JSONException: End of input at character 0 of
02-13 03:15:02.891: E/Buffer Error(1263): Error converting result java.lang.NullPointerException: lock == null
02-13 03:15:02.891: E/JSON Parser(1263): Error parsing data org.json.JSONException: End of input at character 0 of
Edit: My LoginActivity.java:
package com.example.sabre9;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.sabre9.library.DatabaseHandler;
import com.example.sabre9.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
//Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
//private static String KEY_ERROR = "error";
//private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
if (params.length != 2)
return null;
JSONObject json = userFunction.loginUser(params[0], params[1]);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
if (json != null && json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous From in database
UserFunctions userFunction = new UserFunctions();
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Main Screen
Intent main = new Intent(getApplicationContext(), MainActivity.class);
// Close all views before launching Dashboard
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
//btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
new MyAsyncTask().execute(email, password);
}
});
//Link to Register Screen
/*btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});*/
}
}
Your java.lang.NullPointerException: lock == null occurs >= Android 3.0 because networking is not allowed on the main(UI) thread, unless overridden via StrictMode policy. Try:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Note that as a result, httpClient.execute(httpPost); will lock up the system pretty bad as it waits for the response. (Instead, you might do that in an AsyncTask so it doesn't lock up the main thread.) Hope this helps.
I have fixed this error. Seems that through a very embarassing brain fart I have forgotten to include in my manifest file the internet permissions needed. Also, I have tweaked my php files a little. Thank you for the answers anyways :)

Categories

Resources