NullPointerException in android AsyncTask class - java

I'm trying to get data through web services, So that I'm using below shown asynctask calls. It gives me a null point exception as shown in the below screen shot. What can be the issue?
Activity class
new PickupAsyncTask(getApplicationContext(), null).execute();
Asynctask class
public class PickupAsyncTask extends AsyncTask<String, Integer, JSONArray> {
private OnTaskCompleted listener;
private JSONArray responseJson = null;
private Context contxt;
private Activity activity;
public PickupAsyncTask(Context context, OnTaskCompleted listener) {
// API = apiURL;
this.contxt = context;
this.listener = listener;
}
// async task to accept string array from context array
#Override
protected JSONArray doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
try {
path = "http://xxxxxxxxxxxxxxx/LocationService.svc/StreetDetails";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONArray(response);
System.out.println("*****JARRAY*****" + responseJson.length());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONArray result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompleted(responseJson); //line 101
}
}
OnTaskCompleted.java
public interface OnTaskCompleted {
void onTaskCompleted(JSONArray responseJson);
}

listener is null. Introduce a check to verify that listener is not null before calling any methods on it.
Edit
If you want to handle the task completion, pass an anonymous object of OnTaskCompleted to PickupAsyncTask constructor as follows:
new PickupAsyncTask(context, new OnTaskCompleted() {
#Override
public void onTaskCompleted(JsonArray response) {
//Handle the task completion
}
}).execute();

Related

How can I make an httppost request in Android?

I know this should have been easy to find online but none of the articles addressed my issue so I am coming to SO for some help.I am trying to make an httppost request in android to a wcf restful web service. I want to create an xml and then I want to post that to the service and get a response from the service.
I have created a WCF Rest service and it has a method to accept the xml and respond back.Here is the code for the method:
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "DoWork1/{xml}",
BodyStyle = WebMessageBodyStyle.Wrapped)]
XElement DoWork1(string xml);
public XElement DoWork1(string xml)
{
StreamReader reader = null;
XDocument xDocRequest = null;
string strXmlRequest = string.Empty;
reader = new StreamReader(xml);
strXmlRequest = reader.ReadToEnd();
xDocRequest = XDocument.Parse(strXmlRequest);
string response = "<Result>OK</Result>";
return XElement.Parse(response);
}
Here is android code to post xml :
String myXML = "<? xml version=1.0> <Request> <Elemtnt> <data id=\"1\">E1203</data> <data id=\"2\">E1204</data> </Element> </Request>";
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("http://192.168.0.15/Httppost/Service1.svc/DoWork1/"+myXML);
This code crasehes throwing an illegal character in the path exception.
How can I make post an xml file to this service from android. Any suggestions would be really appreciated.
public class HTTPPostActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
makePostRequest();
}
private void makePostRequest() {
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("www.example.com");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
}
}
To connect to WCF service on android you have to use external library like ksoap.
enter link description here
Then you can adapt for your needs this class:
public abstract class SoapWorker extends AsyncTask<SoapWorker.SoapRequest,Void,Object> {
public static class SoapRequest{
private LinkedHashMap<String,Object> params;
private String methodName;
private String namespace;
private String actionName;
private String url;
public SoapRequest(String url, String methodName,String namespace){
this.methodName = methodName;
this.params = new LinkedHashMap<>();
this.namespace=namespace;
this.actionName=this.namespace + "IService/" + methodName;
this.url=url;
}
public void addParam(String key,Object value){
this.params.put(key,value);
}
}
#Override
protected Object doInBackground(SoapRequest input) {
try {
SoapObject request = new SoapObject(input.namespace, input.methodName);
for(Map.Entry<String, Object> entry : input.params.entrySet()){
request.addProperty(entry.getKey(),entry.getValue());
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(input.url);
androidHttpTransport.call(input.actionName, envelope);
input.params.clear();
return parseResponse(envelope.getResponse());
} catch (Exception e) {
Log.e("SoapWorker", "error " + e);
return e;
}
}
#WorkerThread
public abstract Object parseResponse(Object response);
}
Use this class like:
SoapWorker.SoapRequest request = new SoapWorker.SoapRequest(URL,METHOD_NAME,NAMESPACE);
request.addParam(KEY,VALUE);
....
request.addParam(KEY,VALUE);
SoapWorker worker = new SoapWorker(){
#Override
public Object parseResponse(Object response) {
if(response==null)
return null;
//parse response
// this is background thread
return response;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// this is ui thread
//update your ui
}
};
worker.execute(request);
Use this asynck task only in application context.Pass data to Activity / fragment only using EventBus from green roboot or otto.

Android - HTTP GET on separate thread

Background:
I am new to android programming. I want to simply do an http get request to a local server.
I want to pass this request a name as a parameter and want to get a return in json. This issue that I cannot execute it on the main thread. How can I do this?
Here is what I tried:
main class:
itemsAdapter.add(get.getName(device.getName()));
Seperate class in same file:
private class httpGet extends AsyncTask<Editable, Void, Integer> {
protected String doInBackground(Editable... params) {
Editable editable = params[0];
return getName(editable.toString());
}
final String getName(String btName) {
HttpResponse response = null;
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://192.168.1.105/getName.php?q=" + btName);
request.setURI(website);
response = client.execute(request);
// Convert String to json object
JSONObject json = new JSONObject(response.toString());
// get LL json object
JSONObject json_Name = json.getJSONObject("Name");
// get value from LL Json Object
name = json_Name.getString("value"); //<< get value here
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
// Do something to recover ... or kill the app.
}
return result;
}
protected void onPostExecute(Integer result) {
// here you have the result
}
I am not sure if this is even a good way to do this task. I also have no idea how I would call it.
AsyncTask allows you to perform a background operation in a different thread without manipulating threads/handlers.
It should be this way:
private class httpGet extends AsyncTask<ParamForDoInBackground, ParamForOnProgressUpdate, ParamForOnPostExecute> {
protected Long doInBackground(ParamForDoInBackground... urls) {
// do the request here
}
protected void onProgressUpdate(ParamForOnProgressUpdate progress) {
// if you need to show any progress of the
// request from doInBackground
}
protected void onPostExecute(ParamForOnPostExecute result) {
// this method will run when doInBackground
// is done executing
}
}
Then you can execute an AsyncTask:
new httpGet().execute(ParamForDoInBackground);
You can use the following as a reference: AndroidBackgroundProcessing and Android Developer AsyncTask
You should learn how the asyncTask work. Inside DoInBackground you should to put the code referent to the HTTPRequest. I recommend to use methods to improve the understanding of code. Here is an example of one of my apps:
public String query(String uri) {
HttpClient cliente = new DefaultHttpClient();
HttpContext contexto = new BasicHttpContext();
HttpPost httpPost = new HttpPost(uri);
HttpResponse response = null;
String resultado=null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("dato", cod_restaurante));
httpPost.setEntity(new UrlEncodedFormEntity(params));
response = cliente.execute(httpPost, contexto);
HttpEntity entity = response.getEntity();
resultado = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
}
return resultado;
}
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params)
{
result=query(params[0]);
return result;
}
protected void onPostExecute(final String resultadoDoInBackground)
{
//here put the code to modify the UI
}
}
Then in your activity onCreate() method you execute the Asynktask.
new MyAsyncTask().execute(" ");
You can read more about AsyncTask here:
AsyncTask Android Developer

MySQL Query from Android app to remote database

I want to carry out the following php query on my remote database
$result = mysqli_query($con->myconn, "SELECT id, stake, user, returns, teams, status FROM `bet` WHERE user = $user") or die(mysql_error());
My only problem is I'm not sure how to modify my JSONParser class so that I can simultaneously pass the user parameter to the database and receive the results. It currently looks like this and allows me only to either retrieve values or send values.
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) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
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;
}
}
CODE :
public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "***";
JSONParser jParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_GAMELIST = "gamelist";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
JSONArray allgames = null;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
// Hashmap for ListView
ArrayList<HashMap<String, String>> gamesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
*/
/**
* Before starting background thread Show Progress Dialog
*//*
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Bets. 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_games, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Games: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Games
allgames = json.getJSONArray(TAG_GAMELIST);
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
id = c.getString(TAG_ID);
stake = c.getString(TAG_STAKE);
returns = c.getString(TAG_RETURNS);
status = c.getString(TAG_STATUS);
teams = c.getString(TAG_TEAMS);;
// 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_TEAMS, teams);
map.put(TAG_STAKE, stake);
map.put(TAG_RETURNS, returns);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
gamesList.add(map);
}
// } else {
// no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return "";
}

How to parse a large number of nested json objects with different values?

Here is a link: http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js with JSON objects. There are 261 objects with unique value (strings). How to get each object with numbers (2101, 2107 etc.) and 2 strings inside (picture and title)?
So this is my technologies AsyncTask:
ListView listView;
TechnologiesAdapter adapter;
ArrayList<Technologies> techList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView);
techList = new ArrayList<Technologies>();
new TechnologiesAsyncTask().execute("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
}
public class TechnologiesAsyncTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
//How to get the other objects?
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
You can get all of the names to a json array, then get every json object from the names in json array.
Following is a simple example.
private class DataAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL("http://mobevo.ext.terrhq.ru/shr/j/ru/technology.js");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("technology");
JSONArray nameArray = jsonObject.names();
final int size = nameArray.length();
for (int i = 0; i < size; i++) {
JSONObject object = jsonObject.getJSONObject(nameArray.getString(i));
// get id, title and pictures, etc
Log.d(TAG, nameArray.getString(i) + " " + object.getString("title") + " " + object.getString("picture"));
}
} catch (IOException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
After you get the "technology" object just create another JSONObject from that like this:
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj1 = new JSONObject(data);
JSONObject jObj2 = jObj1.getJSONObject("technology");
// Get the 2101 object
JSONObject jObj3 = jObj2.getJSONObject("2101");
// Get the picture and title of 2101
String picture = jObj3.getString("picture");
String title = jObj3.getString("title");
Your JSON looks like it might be better suited to use a JSONArray instead of nested JSONObjects though.
JSONObject jPages=jQuery.getJSONObject("pages");
Iterator < String> keys = jPages.keys();
while(keys.hasNext()){
JSONObject jPageId=jPages.getJSONObject(keys.next());
//Action need to be performed
}

POST using HttpPost in an android not returning JSON string, returns error

So I am trying to post to this api: http://www.idmypill.com/api/id/ in my android program. This is my service handler class:
public class ServiceHandler
{
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
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;
android.os.Debug.waitForDebugger();
// Checking http request method type
if (method == POST)
{
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
// adding post params
if (params != null)
{
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} 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;
}
}
The response I am getting is: Response:(1990): > {"errors": null, "results": [], "success": false}
My main activity that is calling my service handler looks like:
public class QueryAPI extends Activity
{
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://www.idmypill.com/api/id/api";
Bitmap pillPicture;
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent QueryAPI = getIntent();
pillPicture = (Bitmap) QueryAPI.getParcelableExtra("PillImage");
nameValuePair.add(new BasicNameValuePair("api_key", "AIzaSyAdxxOjmh_nx4dKP_uJhtKy3cr32jrs7C8"));
nameValuePair.add(new BasicNameValuePair("image", "pillPicture"));
new GetPillInfo().execute();
}
private class GetPillInfo extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(QueryAPI.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0)
{
android.os.Debug.waitForDebugger();
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST, nameValuePair);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("JSON", jsonObj.toString());
} 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();
}
}
}
The python example the website gives look like this:
# highly suggested to use the requests package
# http://www.python-requests.org/en/latest/
import requests
# read in the image and construct the payload
image = open("example.jpg").read()
data = {"api_key": "KH8hdoai0wrjB0LyeA3EMu5n4icwyOQo"}
files = {"image": open("example.jpg")}
# fire off the request
r = requests.post("http://www.idmypill.com/api/id/",
data = data,
files = files)
# contents will be returned as a JSON string
print r.content
I am not familiar with Python and very new to using Http request so an advice would be great.
The api wants a MultiPartEntity containing a text value with key api_key and a image file with key image.
Android does not natively support MultiPart Uploads but you can archive it with Apache's HTTP Library which is actually an updated version of Android's HTTP Library since they are the same thing.
Once you have the library installed, which is simply adding the dependency in gradle then modify your code for something similar:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("api_key", yourAPIKey);
builder.addBinaryBody("image", inputStream); // Flexible here, see below
httpPost.setEntity(builder.build());
httpResponse = httpClient.execute(httpPost);
The .addBinaryBody() actually has various ways of receiving the image, you can either pass a File a InputStream or the full byte[] array of the image.
You are not returning any result.The return method was Void.That's why you were unable to see any result in Log.
Change your AsyncTask to
private class GetPillInfo extends AsyncTask
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(QueryAPI.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0)
{
android.os.Debug.waitForDebugger();
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST, nameValuePair);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("JSON", jsonObj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
} else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
}

Categories

Resources