This is my first post on this site, i have a problem with my app, i can't find the reason which my app stops. I am sending a request to Despegar to get a json of the countries but happens these. I would be very greatfull if you could help me. Here is my code:
public class MainActivity extends Activity {
final TextView txtResultado = (TextView) findViewById(R.id.txtResultado);
String JSONRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new TareaConexion().execute("http://api.despegar.com/countries");
}
class TareaConexion extends AsyncTask<String, Void, String>{
protected void onPreExecute() {
}
protected String doInBackground(String... urls) {
httpHandler httphandler = new httpHandler();
JSONRequest = httphandler.Post(urls[0]);
return JSONRequest;
}
protected void onProgressUpdate () {
}
protected void onPostExecute() {
txtResultado.setText(JSONRequest);
}
}
and the class httpHandler:
public class httpHandler {
public String Post (String PostURL)
{
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PostURL);
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
String Respuesta = EntityUtils.toString(ent);
return Respuesta;
} catch (Exception e) {
return "error";
}
}
}
can anybody find the reason which do my app stops? what am i doing wrong?
i'm argentinian so excuse me if i make a mistake with the lenguage, ajja. Thanks
Try this code
MyAsyncTask extends AsyncTask<String, Void, HttpResponse>
{
#Override
protected HttpResponse doInBackground(String... param)
{
String url = param[0];
HttpResponse response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
if (type == Constants.TYPE_POST)
{
HttpPost httppost = new HttpPost(url);
response = httpclient.execute(httppost);
}
else if (type == Constants.TYPE_DELETE)
{
HttpDelete httpdelete = new HttpDelete(url);
response = httpclient.execute(httpdelete);
}
else
{
HttpGet httppost = new HttpGet(url);
response = httpclient.execute(httppost);
}
} catch (ClientProtocolException es)
{
Log.e("x" , es.getMessage());
} catch (IOException e)
{
Log.e("aasx" , e.getMessage());
}
return response;
}
#Override
protected void onPostExecute(HttpResponse response)
{
if (response != null)
{
JSONObject obj = new JSONObject(Utilities.convertStreamToString(response.getEntity().getContent()));
//Whatever you want to do
}
}
}
Related
Normally I create classes for every web service call that extends with the AsyncTask and it's so hard to maintain the code. So I think to create the One class and get the OUTPUT Json string according to the parameters.
how do I return the JSON string?
UPDATE
Here what I tried
public class WebCallController extends AsyncTask<Void,Void,String>
{
String PassPeram = "";
JSONStringer JSonRequestString;
String URL;
String JSonResponseString;
public WebCallController(String PerameterPass, JSONStringer JSonRequestString, String URL) {
PassPeram = PerameterPass;
this.JSonRequestString = JSonRequestString;
this.URL = URL;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-type", "application/json");
try {
StringEntity entity = new StringEntity(JSonRequestString.toString());
post.setEntity(entity);
}
catch (Exception Ex)
{
}
try {
HttpResponse response = client.execute(post);
StatusLine status = response.getStatusLine();
int statusCode = status.getStatusCode();
if(statusCode == 400)
{
Log.d("Error", "bad request");
}
else if(statusCode == 505)
{
Log.d("Error","Internal server error");
}
else
{
InputStream jsonStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
builder.append(line);
}
JSonResponseString = builder.toString();
}
}
catch (IOException Ex)
{
}
return JSonResponseString;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
this may be what you are looking for(get string as result and parse it to json):
YourAsycTask yat=new YourAsycTask();
yat.execute();
String result=yat.get().toString();
I am assuming that you need to write one AsyncTask which can be reusable for every webservice call. You can do something like below example ,
Step-1: Create a abstract class
public abstract class HttpHandler {
public abstract HttpUriRequest getHttpRequestMethod();
public abstract void onResponse(String result);
public void execute(){
new AsyncHttpTask(this).execute();
}
}
2. Sterp-2: Write your AsyncTask code
public class AsyncHttpTask extends AsyncTask<String, Void, String>{
private HttpHandler httpHandler;
public AsyncHttpTask(HttpHandler httpHandler){
this.httpHandler = httpHandler;
}
#Override
protected String doInBackground(String... arg0) {
//do your task and return the result
String result = "";
return result;
}
#Override
protected void onPostExecute(String result) {
httpHandler.onResponse(result); // set it to the onResponse()
}
}
Step-3: Write your Activity code
public class MainActivity extends Activity implements OnClickListener {
private Button btnRequest;
private EditText etResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRequest = (Button) findViewById(R.id.btnRequest);
etResponse = (EditText) findViewById(R.id.etRespose);
//check isConnected()...code is on github
btnRequest.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new HttpHandler() {
#Override
public HttpUriRequest getHttpRequestMethod() {
return new HttpGet("http://hmkcode.com/examples/index.php");
// return new HttpPost(url)
}
#Override
public void onResponse(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}.execute();
}
// public boolean isConnected(){}
}
reference
http://hmkcode.com/android-cleaner-http-asynctask/
https://github.com/hmkcode/Android/tree/master/android-clean-http-async-task
Try out below code and put it in separate class from where it returns json string to your activity.
Only pass your url to this method and get the response in a string formate.
public static final String GetConnectionInputStream(String strUrl) {
String line = null;
String response = null;
try {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
// This is the default apacheconnection.
HttpClient mHttpClient = new DefaultHttpClient(httpParameters);
// Pathe of serverside
HttpGet mHttpGet = new HttpGet(strUrl);
// get the valu from the saerverside as response.
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
try {
// convert response in to the string.
if (mHttpEntity.getContent() != null) {
BufferedReader mBufferedReader = new BufferedReader(
new InputStreamReader(mHttpEntity.getContent(),
HTTP.UTF_8), 8);
StringBuilder mStringBuilder = new StringBuilder();
while ((line = mBufferedReader.readLine()) != null) {
mStringBuilder.append(line + "\n");
}
response = mStringBuilder.toString();
// mInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return response;
}
Change your doInBackground method as below:
private class GetParsedResponse extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String response=null;
response=GetConnectionInputStream(URL);
return response;
}
#Override
protected void onPostExecute(String result) {
//your response parsing code.
}
}
private class MyAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return "Executed";
}
#Override
protected String onPostExecute(String result) {
return "json String";
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
Trying to read and parse some json data in my app. I implemented Parser class extending AsyncTask as follows:
public class JSONParser extends AsyncTask<Void, Void, String> {
private String strUrl;
private List<NameValuePair> params;
private String result;
private String response;
public static final String RESULT_SUCCESS = "success";
public static final String RESULT_FAILED = "failed";
public JSONParser(String strUrl, List<NameValuePair> params) {
this.strUrl = strUrl;
this.params = params;
}
private void parse() {
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strUrl);
// Add parameters
if (params != null) {
httppost.setEntity(new UrlEncodedFormEntity(params));
}
// Execute HTTP Post Request
HttpResponse httpResponse = httpclient.execute(httppost);
// return by response
result = RESULT_SUCCESS;
this.response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (Exception e) {
result = RESULT_FAILED;
this.response = null;
e.printStackTrace();
}
}
#Override
public String doInBackground(Void... params) {
parse();
return response;
}
public String getResult() {
return result;
}
public String getResponse() {
return response;
}
}
It works well in later android versions, but unfortunately it throws NetworkOnMainThreadException in older versions.
I've searched and found that I should use Strict mode in my app, but performance of threads became very bad! when I click parse button it freezes!
can you help me with more better solution?
Call you class like this, it will solve your issue !!
new JSONParser().execute();
I have web services and I want to create a class that should takes an email and password from server after authentication in hash table, and then saves email and password in shared preferences.
Try this class to call webservice in your app, i am sharing get and post both methods you can use any one as per your need.
public class CallService {
String url;
HttpEntity str1;
String str;
Context context;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public CallService(String url1) {
this.url = url1;
}
public String getResponceWithPost() {
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,5000000);
HttpConnectionParams.setSoTimeout(httpParameters,500000);
HttpConnectionParams.setTcpNoDelay(httpParameters,true);
HttpClient hc = new DefaultHttpClient(httpParameters);
HttpPost post= new HttpPost (url);
HttpResponse rp = hc.execute(post);
// //////////////
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
str = EntityUtils.toString(rp.getEntity());
Log.e("Calling service", str);
return str;
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int getResponceWithGet() {
int code = 0;
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse rp = hc.execute(get);
code= rp.getStatusLine().getStatusCode();
return code;
} catch (IOException e) {
Log.e("calling service", e.toString());
e.printStackTrace();
}
catch(Exception e)
{
Log.e("calling service", e.toString());
}
return code;
}}
this will return response from server like email password or other details.
and you can save these details in sharedpreference .
for shared preference follow this -
http://developer.android.com/guide/topics/data/data-storage.html#pref
and in your activity call your url using my call service class like this-
declare your hashTable in activity like this
Hashtable hashtable = new Hashtable();
call this method
new checkForLogin().execute();
and your async class
class checkForLogin extends AsyncTask<Void, Void,String>
{
#Override
protected void onPreExecute() {
progress= ProgressDialog.show(LoginScreen.this,"Authenticating !","Please Wait");
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Parse your json data here that will be in data
CallService cl2=new CallService("your server url here");
Log.e("login url is",""+Urls.loginurl);
data=cl2.getResponceWithPost();
Log.e("server response data","data = "+data);
hashtable.put(“email″, data.getString("email"));
hashtable.put(“pass″, data.getString("pass"));
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}
i hope this ll help you.
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;
}
}
I have a custom http class in my android app to handle http post data that is sent to the server. However, I need to convert it to extend asyncTask because I need to 1, show a progress animation while the data is being fetched and 2, refresh/update the ui at the same time.
So what would be the easiest way to do this. Please note that I am already using the class throughout my app to handle httpPOST requests.
Here is the class:
public class Adapter_Custom_Http_Client
{
//<editor-fold defaultstate="collapsed" desc="Class Members">
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getHttpClient">
private static HttpClient getHttpClient()
{
if(mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="executeHttpPost">
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="executeHttpGet">
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
//</editor-fold>
}
Use this Async Class:
public class Albums extends AsyncTask<Void, Void, Void> {
//declarations what u required
#Override
protected void onPreExecute() {
super.onPreExecute();
///declare ur progress view and show it
}
#Override
protected Void doInBackground(Void... params) {
//do ur http work here which is to be done in background
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Update ur UI here...
}
}
Any problem please ask..
EDIT:
Albums alb=new Albums();
alb.execute(null);///u can use different arguments that u need
follow like this:
public class postmethod extends AsyncTask<Void, Void, Void> {
//declarations what u required
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//do ur work here completly that will runs as background
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Create new asynch inner class in your activity :
public class InnerClass extends AsyncTask<Void, Void, String>{
ProgressDialog dialog;
#Override
protected String doInBackground(Void... params) {
String result = Adapter_Custom_Http_Client.executeHttpPost(url , param);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(context, "", "Please wait....");
super.onPreExecute();
}
}
and execute background task using
new InnerClass().execute();