no any response when use httpclient in AsyncTask - java

i want to get data from my server with AsyncTask and then extract some and send to another location and get more info from that
for first section I'm using from this code for run my AsyncTask method and Cancel AsyncTask after some time (for no response...)
new MySecendServer(link, param,mInstagramSession).execute();
final ProgressDialog pd2 = new ProgressDialog(testActivity.this);
pd2.show();
final Timer tm = new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
count++;
if (count == 30) {
pd2.cancel();
tm.cancel();
new MySecendServer(.....) .cancel(true); }
}
});
}
}, 1, 1000);
then after get data from my server i try to get more info with this code but i don't get any response or exception i test this code in doInBackground And onPostExecute and no any diffrent and no any response
try {
String requestUrl = "https://api.instagram.com/v1/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(requestUrl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (Exception ex) {}
now anyone can give me reason or any suggest for do this work ?
thanks
Update :
I found exception here :
HttpResponse httpResponse = httpClient.execute(httpGet);
and message is :
cause NetworkOnMainThreadException (id=831620140512)
Update 2 :
My first AsyncTask
public class MySecendServerClass extends AsyncTask {
private String link="";
private String [][]pparams;
private InstagramUser IG_User;
private InstagramSession IG_Session;
public MySecendServerClass(String link,String [][]params,InstagramSession user){
this.link=link;
this.pparams=params;
this.IG_Session = user;
}
#Override
protected String doInBackground(Object... arg0) {
String data="";
try{
if(pparams!=null){
for(int i=0;i<pparams.length;i++){
if(i!=0){
data+="&";
}
data+=URLEncoder.encode(pparams[i][0],"UTF8")+"="+URLEncoder.encode(pparams[i][1],"UTF8");
}
}
URL mylink=new URL(link);
URLConnection connect=mylink.openConnection();
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line);
}
Log.d("sssss",sb.toString());
return sb.toString();
}
catch(Exception ex){
}
return null;
}
#Override
protected void onPostExecute(Object tr) {
super.onPostExecute(tr);
String result = (String)tr;
try{
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("followlist");
JSONObject jObject = jArray.getJSONObject(0);
String client_id=jObject.getString("client_id");
GrtUserProfile(client_id);
}
catch(Exception ex){
}
}
}
Solve Problem With this Code :
public void GrtUserProfile(String Cid) {
String requestUrl= "https://api.instagram.com/v1/users/"+Cid+"/"+"&access_token="+mInstagramSession.getAccessToken();
new HTTPRequestClass().execute(requestUrl);
}
class HTTPRequestClass extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
String url = urls[0];
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
throw new Exception("Request returns empty result");
}
InputStream stream = httpEntity.getContent();
String response = StringUtil.streamToString(stream);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new Exception(httpResponse.getStatusLine().getReasonPhrase());
}
return response;
} catch (Exception e) {
return "";
}
}
protected void onPostExecute(String Response) {
Log.i("Response", Response);
}
}

Instead of using Timer to cancel async task you can set timeout for HttpURLConnection
private class DownloadFilesTask extends AsyncTask<URL, Integer, Boolean> {
protected Boolean doInBackground(URL... urls) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Boolean result) {
showDialog("Downloaded " + result );
}
}

Related

Why can't read this json, but Browser can

I don't understand why can't I read this json link but Browser Chrome can read, I tried with different link and I read them.
this is the link for requesting json response:
My Code:
runOnUiThread(new Runnable() {
#Override
public void run() {
new sendToken().execute("http://admin:123#qlvb-snv.newsaigonsoft.com/push-notifications-portlet/api/secure/jsonws/pushnotificationsdevice/add-push-notifications-device?token=cNAXYNQSPHk:APA91bF86THzkPE_ol9euea1M40x6jVgN9RjUOISVtL-UEXDYpAP62aeRnUwkLrSt6z8C4saTJPKW5CJ57VSRmovZ5OBX4NsZg3U-zoDdXB64dWzAQGB7WllGvqGEO3Nt4_Fbg-vUyok&platform=android");
}
});
and My AsyncTask:
class sendToken extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return docNoiDung_Tu_URL(params[0]);
}
#Override
protected void onPostExecute(String s) {
Log.d("Respones: ", s + "");
}
}
and it does not respond with anything.
Two things may be the cause
either your method
docNoiDung_Tu_URL is not correct or correctly written
or, You have no permissions to access Internet.
change your doInBackground Like this
class sendToken extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = getNewHttpClient();
HttpGet httpget = new HttpGet(arg0[0]);
// Execute HTTP get Request
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
return responseString;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
Log.d("Respones: ", s);
}
Also add the dependencies to build.gradle
compile('org.apache.httpcomponents:httpcore:4.4.1') {
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
don't forget to add the internet permission to manifest
<uses-permission android:name="android.permission.INTERNET"/>
you have to make http call
HttpURLConnection urlConnection = null;
String My_URL = "YOUR URL";
BufferedReader reader = null;
URL url = null;
String Json;
InputStreamReader inputStream1 = null;
InputStream inputStream = null;
inside do in background
#Override
protected String doInBackground(Void... params) {
try {
url = new URL(My_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if(urlConnection.getResponseCode() == 200)
{
inputStream = urlConnection.getInputStream();
Json = readData(inputStream);
}
else {
urlConnection.getResponseCode();
}
}catch (Exception e){
Json = e.toString();
}
finally {
if (urlConnection!=null)
urlConnection.disconnect();
try {
if (inputStream!=null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return Json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// your work
}
public String readData(InputStream inputStream)
{
StringBuilder builder = new StringBuilder();
try {
if (inputStream != null) {
inputStream1 = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStream1);
String line = reader.readLine();
while (line != null) {
builder.append(line);
line = reader.readLine();
}
} else {
Toast.makeText(MainActivity.this, "errorwa", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){}
return builder.toString();
}
You can not directly read the response from the url.
Try out below code:
public JSONObject getJSONFromUrl(String url) {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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;
}
Add the below permission in manifest
<uses-permission android:name="android.permission.INTERNET"/>

How to connect Clusterpoint database to an android appliaction

I am new to NoSQL database and cloud. I am trying to develop a simple application in android using Clusterpoint (DBAAS). I tried and searched so many possibilities, but it is not quite working.
(new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
String requestString = "https://username:password#api-eu" +
".clusterpoint.com/908/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(requestString);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (IOException e) {
result = "Error";
e.printStackTrace();
} finally {
Log.v("ClusterResponse", result);
return result;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.v("ClusterResponse", s);
}
}).execute();
In my code i replaced username and password with original values.
I got the connection. I am posting my code so the next person can get it right in a much faster way
My mistakes
- Needed GET instead of POST
- Authorization should be of base64 with NOWRAP , so it won't add "CR" line at the end.
(new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
String requestString = "https://api-eu.clusterpoint.com/908/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestString);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpget.addHeader("Authorization", "Basic "+Base64.encodeToString
("username:password".getBytes(),Base64.NO_WRAP));
result = httpClient.execute(httpget, responseHandler);
} catch (IOException e) {
result = e.toString();
e.printStackTrace();
} finally {
Log.v("ClusterResponse", "Done");
return result;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getBaseContext(), s, Toast.LENGTH_LONG).show();
Log.v("ClusterResponse", s);
}
}).execute();

How to send variables to PHP from Android to do a SELECT ... WHERE in PHP

I already got a method to read data from mysql and display it into my android app in textview's. The problem is that now I just retrieve all data from the database without doing a select ... where , just a select. I want to do a select ... where using the variables sent from my android app. I already use the folowing code in my login to send username and pass
nameValuePairs=new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("utilizator",utilizator.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("parola",parola.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
In the method I use I have 2 java files. I really don't understand them much ... so I don't know where to add the code to send variables to php.
httprequest.java
public class httprequest {
static int TIMEOUT = 5000;
public String read_url_resource(String _s_url)
{
String s_response_ = "";
BufferedReader br_reader=null;
StringBuilder sb_builder = new StringBuilder();
URL u_url = null;
try {
if ( _s_url==null || _s_url.length()==0)
return "";
//this.log_message("Downloading from "+_s_url, false);
u_url = new URL(_s_url);
HttpURLConnection huc_urlConnection = null;
huc_urlConnection = (HttpURLConnection)u_url.openConnection();
if ( huc_urlConnection!=null){
huc_urlConnection.setConnectTimeout(TIMEOUT);
huc_urlConnection.setReadTimeout(TIMEOUT);
huc_urlConnection.setUseCaches(false);
huc_urlConnection.setDoOutput(false);
InputStream is_input_stream = huc_urlConnection.getInputStream();
#SuppressWarnings("unused")
URL oURL = huc_urlConnection.getURL();
int i_response_code=huc_urlConnection.getResponseCode();
if ( i_response_code==200){
br_reader = new BufferedReader(new InputStreamReader(is_input_stream));
String line="";
while ((line = br_reader.readLine()) != null)
sb_builder.append(line);
is_input_stream.close();
s_response_ = sb_builder.toString();
String s_auth= huc_urlConnection.getURL().getAuthority();
}
}
} catch (Exception e) {
if ( e!=null )
Log.e("URL PROBLEM", e.toString());
s_response_ = "[\"error\": \"No connection\"]";
}
return s_response_;
}
}
and ReadJSONData.java
public class ReadJSONData extends AsyncTask<String, Integer, Integer> {
private String server = "http://asociatia-online.esy.es/cote.php?hc_location=ufi";
private ReadJSONListener jsonListener;
private String json ="";
private int internal_categ;
httprequest request;
public interface ReadJSONListener
{
void onTaskFinished(String s_json, int _i_internal_category);
}
public ReadJSONData (ReadJSONListener _jsonListener, int _i_internal_category)
{
this.jsonListener=_jsonListener;
this.internal_categ =_i_internal_category;
}
#Override
protected Integer doInBackground(String... strings) {
request = new httprequest();
this.downloadResource();
return null;
}
private void downloadResource() {
switch (this.internal_categ) {
case 1:
this.json = request.read_url_resource(server);
break;
}
}
#Override
protected void onPostExecute(Integer result)
{
this.jsonListener.onTaskFinished(this.json, this.internal_categ);
}
}
So, where to add the 4 lines code to send variables? In which file and where. Thanks !
With this code you can send variables to PHP and get some data back and store it in strings to use as you want.
private class ObtinereInformatii extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://asociatia-online.esy.es/rezumat.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("luna_rezumat",spinner_luna.getSelectedItem().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("an_rezumat",spinner_an.getSelectedItem().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("-------",result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
protected void onPostExecute(String result){
try{
jArray = new JSONArray(result);
readJson(jArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void readJson(JSONArray ja_data) throws JSONException {
if (ja_data!=null)
{
for (int i = 0; i<ja_data.length(); i++)
{
JSONObject jo = ja_data.getJSONObject(i);
if (jo.has("data_rezumat"))
{
if (jo.getString("data_rezumat")!=null)
{
z_data_rezumat= jo.getString("data_rezumat");
}
}
}
}
}

Conversion of HttpClient written in java to C# FOR calling Web apis

I am extremely new to C# And windows app programming.
I am trying to create an AsyncTask, like in java , where i can query a url and get its response back.
Here is the code i usually use in java, i want to implement the copy in C sharp.
public interface ResponseCallback
{
void onSuccess(String response);
void onFailure(String exception);
}
public class MyAsyncTask extends AsyncTask<String, Void, String>
{
private ResponseCallback myResponse = null;
private int type = 0;//POST
List<NameValuePair> nameValuePairs = null;
StringEntity entity = null;
private HttpResponse response = null;
public MyAsyncTask(String url,ResponseCallback myResponse)
{
this.myResponse = myResponse;
this.execute(url);
}
#Override
protected String doInBackground(String... param)
{
String url = param[0];
response = null;
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
try {
if (type == 0)
{
HttpPost httppost = new HttpPost(url);
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
if (entity != null)
httppost.setEntity(entity);
response = httpclient.execute(httppost);
}
else
{
HttpGet httppost = new HttpGet(url);
response = httpclient.execute(httppost);
}
} catch (ClientProtocolException es)
{
} catch (IOException e)
{
}
String resp = null;
if (response != null)
{
try {
resp = Utilities.convertStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resp;
}
else
return null;
}
#Override
protected void onPostExecute(String resp)
{
if (resp != null)
{
if (response.getStatusLine().getStatusCode() == Constants.RESULT_OK )
{
try {
myResponse.onSuccess(resp.trim());
} catch (IllegalStateException e) {
}
}
else
myResponse.onFailure(resp);
}
else
myResponse.onFailure(resp);
}
}
I have tried this in C #. Anyone wanna help me fix few things in this code and give me some info, what to do next
namespace The_Vow.Global
{
class MyAsyncTask
{
public ResponseCallback callback;
static void queryUrl(String url)
{
RunAsync(url).Wait();
}
static async Task RunAsync(String url)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("MY_IP");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync(url);
//response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
String jsonStr = await response.Content.ReadAsStringAsync();
// callback variable is not being recognized????
callback.onSuccess(jsonStr);
//Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
}
}
}
namespace The_Vow.Global
{
public interface ResponseCallback
{
void onSuccess(String response);
void onFailure(String exception);
}
}
Your callback field is an instance field, so you can't access it from a static method, unless you make the field static.
Another alternative I would like to recommend though, is not using a field at all. Pass the callback variable as a method argument.
Or you can stop using static methods at all, make them instance methods.

What is the most efficient way on Android to call HTTP Web API calls that return a JSON response?

I'm the perfectionist type, I already got web API calls working fine with Google Places API (just as an example), but I feel it's sometimes slow or maybe I'm not doing it right. Some blogs are saying I should use AndroidHttpClient, but I'm not, should I ?
The web API calls i'm using return json and I don't run them on the UI thread, hence using AsyncTask (is AsyncTask the most efficient way to run on background thread or should I use something else ?)
Please see my code and tell me how could it be more efficient in anyway
public static class NearbySearchRequest extends AsyncTask<String, Void, JSONObject>
{
Exception mException = null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
this.mException = null;
}
#Override
protected JSONObject doInBackground(String... params)
{
StringBuilder urlString = new StringBuilder();
urlString.append("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
urlString.append("key=").append(Constants.GOOGLE_SIMPLE_API_KEY);
urlString.append("&location=").append(params[0]);
urlString.append("&sensor=").append("true");
urlString.append("&language=").append("en-GB");
urlString.append("&name=").append(params[1]);
urlString.append("&rankby=").append("distance");
LogHelper.Log(urlString.toString());
HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
try
{
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream inStream = null;
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp, response = "";
while ((temp = bReader.readLine()) != null)
response += temp;
bReader.close();
inStream.close();
urlConnection.disconnect();
object = (JSONObject) new JSONTokener(response).nextValue();
}
catch (Exception e)
{
this.mException = e;
}
return (object);
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
if (this.mException != null)
ErrorHelper.report(this.mException, "Error # NearbySearchRequest");
}
}
The Http engine you're using seems the best choice. Actually any other 3-rd party engines are based either on Apache, either on HttpUrlConnection. I prefer to use Spring for Android as that API provide an abstraction over Http Engine and you don't really need to care how about what API to use based on API level. Or you can use Volley - a very fashionable library.
I would touch however some of your code:
What if there is an exception while reading the stream? Then the stream remains open and also the connection. So I would suggest to have a finally block where the streams and connection is closed no matter if you get an exception or not:
HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
InputStream inStream = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp, response = "";
while ((temp = bReader.readLine()) != null) {
response += temp;
}
object = (JSONObject) new JSONTokener(response).nextValue();
} catch (Exception e) {
this.mException = e;
} finally {
if (inStream != null) {
try {
// this will close the bReader as well
inStream.close();
} catch (IOException ignored) {
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
JSON parsing: you're using the Android standard way of parsing JSON, but that's not the fastest and easiest to work with. GSON and Jackson are better to use. To make a comparison when it comes for JSON parsers, I would go for Jackson. Here's another SO topic on this comparison.
Don't concatenate strings like that as concatenating strings will create each time another string. Use a StringBuilder instead.
Exception handling (this is anyway a long-debate subject in all programming forums). First of all you have to log it (Use Log class not System.out.printXXX). Then you need to either inform the user: either you toast a message, either you show a label or notification. The decision depends on the user case and how relevant is the call you're making.
These are the topics I see in you code.
EDIT I realize I didn't answer this: is AsyncTask the most efficient way to run on background thread or should I use something else?
The short answer I would give is: if you're supposed to perform a short time lived request, then AsyncTask is perfect. However, if you need to get some data and display it - but you don't want to worry about whether to download again if the screen is rotated and so on, I would strongly recommend using an AsyncTaskLoader and Loaders in general.
If you need to download some big data, then either you use an IntentService or, for heavy-weight operations, DownloadManager.
Enjoy coding!
------Create a Service Handler Class to your Project--------
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) {
Log.e("in POST","in POST");
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
Log.e("in POST params","in POST params");
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
Log.e("url in post service",url);
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
Log.e("in GET","in GET");
if (params != null) {
Log.e("in GET params","in GET params");
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
Log.e("url in get service",url);
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;
}
public String makeServiceCallIMAGE(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;
}
}
--------------AsyncTask For Login------------------
public class Login_Activity extends ActionBarActivity {
//Internet Service
NetworkConnection nw;
ProgressDialog prgDialog;
Boolean netConnection = false;
//
//Login API
String loginURL ="url";
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
nw = new NetworkConnection(getApplicationContext());
prgDialog = new ProgressDialog(this);
// Set Cancelable as False
prgDialog.setCancelable(false);
new LoginOperation().execute();
}
private class LoginOperation extends AsyncTask<String, Void, Void> {
String status, message;
#Override
protected void onPreExecute() {
// Set Progress Dialog Text
prgDialog.setMessage("Logging...");
prgDialog.show();
}
#Override
protected Void doInBackground(String... urls) {
if(nw.isConnectingToInternet() == true)
{
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "ClientesLogin"));
nameValuePairs.add(new BasicNameValuePair("Email", str_Email));
nameValuePairs.add(new BasicNameValuePair("Senha", str_Password));
ServiceHandler sh = new ServiceHandler();
String response = sh.makeServiceCall(loginURL, ServiceHandler.GET,
nameValuePairs);
Log.e("response", response);
JSONObject js = new JSONObject(response);
status = js.getString("status");
Log.e("status",status);
if(status.contains("Fail"))
{
message = js.getString("message");
}
/*else
{
JSONObject jslogin=js.getJSONObject("user_list");
for (int i = 0; i < jslogin.length(); i++) {
}
}*/
}catch(Exception ex){
}
netConnection = true;
}else
{
netConnection = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
prgDialog.dismiss();
if(netConnection == false)
{
Toast toast = Toast.makeText(getApplicationContext(),"Internet is not available. Please turn on and try again.", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else
{
if(status.contains("Success"))
{
Toast toast = Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Intent i=new Intent(Login_Activity.this,home_page_activity.class);
startActivity(i);
}
else{
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
super.onPostExecute(result);
}
}
}
---------------Network Connection class---------------------
public class NetworkConnection {
Context context;
public NetworkConnection(Context context){
this.context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
JSONArray main1 = js.getJSONArray("Test 1");
for (int i = 0; i < main1.length(); i++) {
JSONObject jsonObject = main1.getJSONObject(i);

Categories