public class GetUserDetail extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog=ProgressDialog.show(PropertyDetailActivitys.this, "Wait", "User Detail");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
System.out.println("Size mArrayListReviewDetails "+mArrayListReviewDetails.size());
for (int i = 0; i < mArrayListReviewDetails.size(); i++) {
String jsonStr = sh.makeServiceCall("https://graph.facebook.com/"+mArrayListReviewDetails.get(i).getFromid(), ServiceHandler.GET);
System.out.println("JSON OP USer"+"{"+"\"User\""+":"+jsonStr.toString()+"}");
try {
JSONObject jsonObj = new JSONObject(jsonStr);
System.out.println("Name "+jsonObj.getString("name"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (mProgressDialog!=null) {
mProgressDialog.dismiss();
}
}
}
ServiceHandler.Java
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;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// 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;
}
}
Hello friends this is my code in this i have mArrayListReviewDetails Arraylist which include size and as per that size i want to get user name which i call next web service as below ,,right now this arraylist size is 11 but when i call this service it will get only 2 data and progress dialog progress continueouly so how can i solve it any idea?
you just make change in doINBackground fun. Take
ServiceHandler sh = new ServiceHandler(); line inside for loop
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Making a request to url and getting response
System.out.println("Size mArrayListReviewDetails "+mArrayListReviewDetails.size());
for (int i = 0; i < mArrayListReviewDetails.size(); i++) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall("https://graph.facebook.com/"+mArrayListReviewDetails.get(i).getFromid(), ServiceHandler.GET);
System.out.println("JSON OP USer"+"{"+"\"User\""+":"+jsonStr.toString()+"}");
try {
JSONObject jsonObj = new JSONObject(jsonStr);
System.out.println("Name "+jsonObj.getString("name"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return null;
}
You could pass your parameters to the async task:
public class GetUserDetail extends AsyncTask<String, Void, Void> {
// ...
#Override
protected Void doInBackground(String... usernames) {
for (int i = 0; i < usernames.length; i++) {
String jsonStr = sh.makeServiceCall("https://graph.facebook.com/" + usernames[i], ServiceHandler.GET);
// ...
}
}
}
Of course, instead of String, feel free to pass your own type. To call the async task:
new GetUserDetail().execute( "test1", "test2" );
Other option is to have each async task perform exactly one single webservice call and create many of them. Advantage: on Android 3.0+, the task executions will be done in parralel.
I think instead of using that...you can use "Volley" library...it's simple and having build-in functionality like;
Request queuing and prioritization
Effective request cache and memory management
Extensibility and customization of the library to our needs
Cancelling the requests
volley reference
volley tutorial
Related
I'm working on an android project and I use JSON to intechange data with server.. Problem is here when I use JSON file with UTF-8 format, some crash happens and the app stops.. and when I don't, it works fine.
I really need to have my files in UTF-8 format to have the correct charecters.
Where am I missing? Thank you in advanced.
Here 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;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// 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;
}
and Here is the method I use in main activity:
private class GetContacts extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SecondActivity.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();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
// Getting JSON Array node
if (jsonObj != null) {
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
}
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_Title);
String content = c.getString(TAG_CONTENT);
String date = c.getString(TAG_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_Title, title);
contact.put(TAG_CONTENT, content);
contact.put(TAG_DATE, date);
// adding contact to contact list
conatctlist.add(contact);
}
} 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) {
ListView lv = (ListView)findViewById(R.id.listView);
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SecondActivity.this, contactlist,
R.layout.list_item_2, new String[] { TAG_Title, TAG_CONTENT,
TAG_DATE }, new int[] { R.id.name,
R.id.email, R.id.date });
lv.setAdapter(adapter);
}
}//end getContacts
May be, You have to define HttpClient like this...(Not Tested)
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
I am developing weather application by using world weather online API
for android.How i show data in application? data is showing in logcat.Following is my code.
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
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();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
// adding contact to contact list
dataList.add(contact);
}
} 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,
dataList, R.layout.list_item, new String[] { TAG_NAME }, new int[] {
R.id.name });
setListAdapter(adapter);
}
}
}
ServiceHandler.java
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;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// 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;
}
}
First of all, this format will refer to the V1 free version. World Weather Online has released v2, which is superior. I was in the process of updating and saw this question sitting out there so I'll answer based off of what I had that did work.
You are on the right track to use the AsyncTask, here is my call to AsyncTask. You should know I use my "DataPoint" class to simply contain the data from WWO that I need to use. Based on your question, you can show the data that I will put in the DataPoint object in anyway you see fit on the screen, since at the end of the queryWeatherService(), you will end up with a parsed set of data.
//Some call to query the weather, which executes the AsyncTask
private DataPoint queryWeatherService()
{
// This method will retrieve the data from the weather service
DataPoint newDataPoint = new DataPoint();
if (!waiting)
{
try{
newDataPoint = new WeatherServiceClass().execute(
String.valueOf(getlatitude()), //Not shown here: pass in some String of a float value of of your lat coordinate.
String.valueOf(getlongitude())) //Not shown here: pass in some String of a float value of of your long coordinate.
.get();
} catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
return newDataPoint;
// Documentation:
// https://developer.worldweatheronline.com/page/documentation
}
The WeatherServiceClass that extends the AsyncTask
public class WeatherServiceClass extends AsyncTask<String, String, DataPoint> {
private String latitude;
private String longitude;
public WeatherServiceClass() {
}
#Override
protected DataPoint doInBackground(String... params) {
DataPoint dp = new DataPoint();
JSONWeatherParser jparser = new JSONWeatherParser();
latitude = params[0];
longitude = params[1];
String data = ((new WeatherHttpClient().getWeatherData(latitude, longitude)));
try {
dp = jparser.getWeather(data);
} catch (JSONException e) {
e.printStackTrace();
}
return dp;
//Reference:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
}
}
Here is the WeatherHttpClient class:
public class WeatherHttpClient {
private static String BASE_URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
private static String BASE_URL_PT2 = "&format=json&num_of_days=5&date=today&key=[ENTER YOUR KEY HERE, I'M NOT GIVING YOU MINE]";
public String getWeatherData(String latitude, String longitude){
HttpURLConnection con = null;
InputStream is=null;
try{
con = (HttpURLConnection)(new URL(BASE_URL + latitude+","+longitude+BASE_URL_PT2)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
//Reading the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line=br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try { is.close();} catch(Throwable t){}
try { con.disconnect();} catch(Throwable t){}
}
return null;
}
Finally, here is my JSONWeatherParser:
public class JSONWeatherParser {
public JSONWeatherParser() {
}
public DataPoint getWeather(String data) throws JSONException {
DataPoint dp = new DataPoint();
Weather weather = new Weather(); //This is just a class that has a bunch of strings in it for the weather info.
JSONObject jObj = new JSONObject(data);
//Parsing JSON data
JSONObject dObj = jObj.getJSONObject("data");
JSONArray cArr = dObj.getJSONArray("current_condition");
JSONObject JSONCurrent = cArr.getJSONObject(0);
weather.setCurrent_temp(getString("temp_F",JSONCurrent));
weather.setHour(getString("observation_time",JSONCurrent));
JSONArray jArr = dObj.getJSONArray("weather");
JSONObject JSONWeather = jArr.getJSONObject(0);
JSONArray jArrIcon = JSONWeather.getJSONArray("weatherIconUrl");
JSONObject JSONIcon = jArrIcon.getJSONObject(0);
weather.setDate(getString("date",JSONWeather));
weather.setPrecipmm(getString("precipMM",JSONWeather));
weather.setTempMaxc(getString("tempMaxC",JSONWeather));
weather.setTempMaxf(getString("tempMaxF",JSONWeather));
weather.setTempMinf(getString("tempMinF",JSONWeather));
weather.setTempMinc(getString("tempMinC",JSONWeather));
weather.setWeatherCode(getString("weatherCode",JSONWeather));
weather.setWeatherIconURL(getString("value",JSONIcon));
weather.setWinddir16point(getString("winddir16Point",JSONWeather));
weather.setWinddirDegree(getString("winddirDegree",JSONWeather));
weather.setWindspeedKmph(getString("windspeedKmph",JSONWeather));
weather.setWindspeedMiles(getString("windspeedMiles",JSONWeather));
dp.setWeather(weather); //assigns and converts the relevant weather strings to DataPoint
// For details of these operations and how each works go here:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
return dp;
}
private static String getString(String tagName, JSONObject jObj)
throws JSONException {
return jObj.getString(tagName);
}
}
My android app posts a string to web server using json and Http post and following code structure is used, but i want to pass few parameters to AsyncTask<> class through HttpAsyncTask().execute("from here"). can any one help me how to do it.. your help will be greatful for me thanks in advance
btn_send.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String strData = "Some String to post";
String strURL = "http://My-Url/";
String reqTimeOut = "30000";
String Code = "9990001" ;
String webRequest = SendWebRequest(strURL,strData, reqTimeOut, Code);// method to send HTTpPost request
WriteToFile(webRequest);//writing response to file
private String SendWebRequest(String urlStr, String Data,String reqTimeOut, String Code)
{
// TODO Auto-generated method stub
String result="";
try
{
/*
Some mandatory operations on Data
*/
// Here i want to pass parameters: url, reqTimeout, Data, text and value(for setting header) to POST method.
new HttpAsyncTask().execute(urlStr);
}catch(Exception e){}
return result;
}
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return POST(params[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
private String POST(final String url, final String postData,String text, String value) {
// TODO Auto-generated method stub
InputStream inputStream ;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "2. url is "+url,
Toast.LENGTH_LONG).show();
}
});
String json=postData ;
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// HttpConnectionParams.setConnectionTimeout(null, 300000);
// 7. Set some headers to inform server about the type of the content
// httpPost.setHeader("Accept", "application/json");
httpPost.setHeader(text, value);
// 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;
}
Write parameterised constructor for your HttpAsyncTask class. Add private field which you want to use in your HttpAsyncTask class. Then just instantiate the HttpAsyncTask class object with required parameters.
Your class structure would like:
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
private String url,reqTimeout,data,text,value;
public HttpAsyncTask(String url,String reqTimeout,String data, String text, String value){
this.url = url;
this.reqTimeout = reqTimeout;
this.data = data;
this.text = text;
this.value = value;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return POST(params[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
private String POST(final String url, final String postData,String text, String value) {
// TODO Auto-generated method stub
InputStream inputStream ;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "2. url is "+url,
Toast.LENGTH_LONG).show();
}
});
String json=postData ;
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// HttpConnectionParams.setConnectionTimeout(null, 300000);
// 7. Set some headers to inform server about the type of the content
// httpPost.setHeader("Accept", "application/json");
httpPost.setHeader(text, value);
// 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;
}
And then when you call the execute method of HttpAsyncTask class, you should call it in following way:
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(url,reqTimeout,data, text,value);
httpAsyncTask().execute(urlStr);
I have already done this task for another project and it gave JSON values but for this code when I use the extends Fragment, it show null value.
Following is the Fragment extended class code:
Note: I'm using same ServiceHandler class as previous project
public class NewsActivity extends Fragment {
private NewsActivity activity;
// url to get JSON
private static String url = "http://vikashparajuli.orgfree.com/zz/get_all_products.php";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
activity = this;
//TODO: if Internet is connected
if(AutoLifeUtils.isConnectedToInternet(getActivity())){
new Get_postlist().execute();
}else{
}
return rootView;
}
public class Get_postlist extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to API url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
Here is ServiceHandler class
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
/**
* 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
* */
private String makeServiceCall(String url, int method, List<NameValuePair> params) {
// TODO Auto-generated method stub
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);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params)); // UrlEncodedFormEntity() is useful to send HTTP POST request
}
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 ex){
ex.printStackTrace();
}catch(IOException exc){
exc.printStackTrace();
}
return null;
}
}
At the end of the makeServiceCall you have return null;
change it to return response; as shown below.
private String makeServiceCall(String url, int method, List<NameValuePair> params) {
....
//return null;
return response; //this should fix your problem.
}
I want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.
Methods of Async task include:-
OnPreExecute()-Want to start progress dialog same for each class.
doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.
onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.
Now I'm writing the async task in my every class as inner class like the following:-
class loaddata extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddNewLineitem.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
compoment = json.getJSONArray(COMPONENT_CODE);
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
loadSpinnerData();
pDialog.dismiss();
}
}
And JSON parser class is as follows:-
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 in oncreate() I call this and it works fine:-
new loaddata().execute();
We can reuse Aysntask with different parameters. For this
1.Create an Interface so that we can reuse,pass and receive parameters
public interface BackgroundListener {
public Object[] startBackgroundWork(Object... objs);
public void endBackgroundWork(Object... objs);
public void beforeBackgroundWork();
}
2.Create a Class Extending Asyntask
BackgroundHandler.java
import android.os.AsyncTask;
public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
BackgroundListener backgroundListener;
public void setBackgroundListener(BackgroundListener aBackgroundListener)
{
this.backgroundListener = aBackgroundListener;
}
#Override
protected void onPreExecute() {
backgroundListener.beforeBackgroundWork();
}
#Override
protected Object[] doInBackground(Object... objs) {
return backgroundListener.startBackgroundWork(objs);
}
#Override
protected void onPostExecute(Object result[]) {
backgroundListener.endBackgroundWork(result);
}
}
Using in Activity
A.java
Class A extends Activity implements BackgroundListener
{
...onCreate()
{
BackgroundHandler backgroundHandler = new BackgroundHandler()
backgroundHandler.setBackgroundListner(this);
backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type
// show loading bar
}
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(A.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url_foralldropdowns = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();// hide loading bar
//access resultant parameters like objs[0], objs[1]
//user list_component will be in obj[0]
}
}
Similarly we can reuse in B.java
Class B extends Activity implements BackgroundListener
{
...
....
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(B.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url2 = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url2,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();
.....
//user list_component will be in obj[0]
}
}
Asyntask is just a class like others. Apart from the main inhertited methods of AsyncTask you can create your own methods, constructor etc. So just create a separate class in separate file. pass the context as parameter of the constructor. you can pass other values also to define the tasks.
class Loaddata extends AsyncTask<String, String, String> {
public Loaddata( pass the params){
... set the params
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Data. Please wait...");
pDialog.show();
}
protected void onPostExecute() {
// pDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}