AsyncTask doInBackground comes with big delay - java

Can anyone explain why AsyncTask comes with big delay and only in one case, and that is when I have wifi network but there is no internet connectivity on that network.
What could be the reason for that, and is there a way to make bigger priority on async task?

I have had that problem before, solved it by adding onPreExecute
in order to check if there is internet connection before attempting to execute the DoInBackground, check out the code below:
public class httpGetProduct extends AsyncTask<Void,Void,String> {
String result, rs;
JSONArray jArray;
String itemcode="",price,desc_ar,desc_en;
#Override
protected void onPreExecute() {
super.onPreExecute();
isOnline=ping(); // use ping if connecting to a certain local ip address
isOnline= hasInternetConnection();// use this if your connecting to internet
}
#Override
protected String doInBackground(Void... params) {
if(isOnline) // executes only if online
try {
String link = "http://"+ip+"/PriceCheckerWS.asmx/get_product_data?barcode="+barcode;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
// do somthing with the result if you need it
rs = "sucessful";
} catch (Exception e) {
rs = "Fail";
}
return rs;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
public boolean ping() {
String[] separated = ip.split(":");
String hostip=separated[0];
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 " + hostip);
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
public boolean hasInternetConnection() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo i = cm.getActiveNetworkInfo();
if (i != null) {
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
}
if (i == null)
return false;
} else
return false;
}
catch (Exception e){
return false;
}
internet=true;
return true;
}

Related

Get JSON from server if network is available

How can I make a file load from the Internet with a negative value of a variable, and from a file on a phone with a positive value?
It should work like this:
My system checks if there is internet
If not, load from memory
If there is, load from the site url
public String getJSONFromAssets(Context context) {
String json = null;
try {
InputStream inputData = context.getAssets().open("data.json"); //load assets file
//Log.e("100rad", ":"+inputData);
int size = inputData.available();
byte[] buffer = new byte[size];
inputData.read(buffer);
inputData.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private class AsyncTaskGetMareker extends AsyncTask<String , String, JSONArray> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(String... strings) {
String stationsJsonString = getJSONFromAssets(MainActivity.this);
try {
JSONArray stationsJsonArray = new JSONArray(stationsJsonString);
return stationsJsonArray;
} catch (JSONException e) {
e.printStackTrace();
}
//This will only happen if an exception is thrown above:
return null;
}
protected void onPostExecute (JSONArray result){
if (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
jsonObject= result.getJSONObject(i);
String name=jsonObject.getString("store_name");
String lat=jsonObject.getString("latitude");
String lang=jsonObject.getString("longitude");
String desc=jsonObject.getString("store_desc");
String oxr=jsonObject.getString("telephone");
String sost=jsonObject.getString("keywords");
int cat=jsonObject.getInt("category_id");
int id=jsonObject.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Here is the JSONParser Class
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}}
You can check whether your mobile device is connected to the internet or not by below code,
public class ConnectionDetector
{
private Context _context;
public ConnectionDetector(Context context)
{
this._context = context;
}
public boolean isConnectingToInternet()
{
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null)
{
if (info.getType() == ConnectivityManager.TYPE_WIFI)
{
return true;
}
else if (info.getType() == ConnectivityManager.TYPE_MOBILE)
{
return true;
}
}
else
{
// not connected to the internet
return false;
}
}
return false;
}}
And your AsyncTask class code would be similar like below code,
private class AsyncTaskGetMareker extends AsyncTask<String , String, JSONArray>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(String... strings) {
JSONArray stationsJsonArray;
String stationsJsonString = getJSONFromAssets(MainActivity.this);
try {
if(new ConnectionDetector().isConnectionToInternet())
{
Hashmap<String,String> mapToSend = new Hashmap();
JSONParser jsonParser = new JSONParser();
stationsJsonArray = jsonParser.makeHttpRequest("URL", "POST", mapToSend);
}else{
stationsJsonArray = new JSONArray(stationsJsonString);
}
return stationsJsonArray;
} catch (JSONException e) {
e.printStackTrace();
}
//This will only happen if an exception is thrown above:
return null;
}
protected void onPostExecute (JSONArray result){
if (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
jsonObject= result.getJSONObject(i);
String name=jsonObject.getString("store_name");
String lat=jsonObject.getString("latitude");
String lang=jsonObject.getString("longitude");
String desc=jsonObject.getString("store_desc");
String oxr=jsonObject.getString("telephone");
String sost=jsonObject.getString("keywords");
int cat=jsonObject.getInt("category_id");
int id=jsonObject.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
You can also add this check
public static boolean isNetworkAvailable(Context con) {
try {
ConnectivityManager cm = (ConnectivityManager) con
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Then check this in your Activity/Fragment
if (isNetworkAvailable)
{
//Do you task
//callAPI(); fetch data from website / api call
}
else{
/*No internet so, load from memory */
}

AsyncTask loading data in very different amount of times in android

I wrote this code to send request and get data from server.
Sometimes the loading process takes 2 seconds with 2G internet connection but sometimes it takes more than 20 seconds with 4G internet connection.
do i have to consider anything that i did not ?
here is my code
#Override
protected void onPreExecute() {
dialog.show();
new CountDownTimer(10000, 10000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// stop async task if not in progress
if (getStatus() == Status.RUNNING) {
Request.this.cancel(false);
activity.finish();
font.toast(activity.getResources().getString(R.string.connection_problem));
}
}
}.start();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
if (isOnline())
try {
data += params[1];
link += params[0];
URL url = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection
.getOutputStream()));
writer.write(data);
writer.flush();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {//if valid, read result from server
BufferedReader reader = new BufferedReader(new InputStreamReader
(httpURLConnection.getInputStream()));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
else {
dialog.cancel();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
font.toast(activity.getResources().getString(R.string.internet_connection_problem));
activity.finish();
}
});
}
return null;
}
#Override
protected void onPostExecute(final String o) {
try {
if (o != null) {
dialog.cancel();
callBack.onResponse(new Response(o));
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(o);
}
public static boolean isOnline() {
try {
int timeoutMs = 2500;
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
return true;
} catch (IOException e) {
return false;
}
}
I use post method to send the request to server(php) and then i receive the result.
I Check the internet connection with isOnline method and i set a timeout with CountDownTimer in the onPerExecute method.
is there anyway to speed up the connection ?
how do i prevent having very different amount of loading time ?
Just a suggestion here, of course you can ignore me always :)
Why do not use Retrofit -> https://square.github.io/retrofit/, it is really easy and intuitive.

AsyncTask not returning any response

Hi I have trouble getting the response of my url from my host. I tried putting static variables and it worked but when I tried to use a asynctask for response it didnt work.
<?PHP
include_once('connection.php');
$where='';
if(isset($_GET['userLat']) && isset($_GET['userLng'])){
$where = "WHERE ((userLat >= '".addslashes($_GET['userLat'])."' AND userLat <= '".addslashes($_GET['userLat'])."' + .00901) OR (userLat <= '".addslashes($_GET['userLat'])."' AND userLat >= '".addslashes($_GET['userLat'])."' - .00901)) AND ((userLng >= '".addslashes($_GET['userLng'])."' AND userLng <= '".addslashes($_GET['userLng'])."' + .014935) OR (userLng <= '".addslashes($_GET['userLng'])."' AND userLng >= '".addslashes($_GET['userLng'])."' - .014935))";
$query = "SELECT * FROM tbl_user ".$where." AND isOnline = 'Yes' LIMIT 1 ";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
$json['details'][]=$row;
}
}
mysqli_close($conn);
echo json_encode($json);
}
?>
AsyncTask
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getActivity());
pd.setMessage("Checking nearby wingmans");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
request = result;
Log.d("Test", result);
}
}
how i call my url
btnEmergency.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"ANDuserLng="+tvLng.getText().toString();
new JsonTask().execute(url);
}
});
Thanks guys i hope i get an answer to my question. Thanks :)
Very foolish of me. I jsut change the AND to & in my url
from
String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"ANDuserLng="+tvLng.getText().toString();
to
String url = "http://10.0.2.2/wingman/emergency.php?userLat="+tvLat.getText().toString()+"&userLng="+tvLng.getText().toString();
And it worked. Thanks!

AsyncTask setting priority

I have an AsyncTask(.execute()) with an onPostExecute method. This method starts another AsyncTask(.execute()) that needs to be done before continuing the execution of the first onPostExecute. Is it possible to pause the first thread and to wait for the second thread to finish? I need the result from the second postExecute method in order to finish the first postExecute.
An example below:
public class RetrieveData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... strings) {
HttpURLConnection conn = null;
try {
URL url = new URL(strings[0]);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String linieNoua = "";
String crlf = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
while((linieNoua = br.readLine()) != null) {
sb.append(linieNoua);
sb.append(crlf);
}
conn.disconnect();
return sb.toString();
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
RetrieveData retrieveData = new RetrieveData() {
#Override
protected void onPostExecute(String s) {
if (s != null) {
retrieveTransport(transportRegNr);
} else {
Toast.makeText(getApplicationContext(), R.string.login_server_error, Toast.LENGTH_LONG).show();
}
}
};
retrieveData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"http://192.168.0.101:3000/route/" + prefs.getString("email",null));
}
private void retrieveTransport(String regNr){
RetrieveData retrieveData = new RetrieveData() {
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject jsonObject = new JSONObject(s);
String model = jsonObject.getString("model");
String regNr = jsonObject.getString("regNr");
int type = jsonObject.getInt("type");
int seats = jsonObject.getInt("seats");
t = new Transport(model,regNr,null,seats,type);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), R.string.login_server_error, Toast.LENGTH_LONG).show();
}
}
};
retrieveData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"http://192.168.0.101:3000/transport/registryNr/" + regNr);
}
If I use the execute method, onPostExecute from retrieveTransport(String regNr) is never called. If I use executeOnExecutor, they are running simultaneously, and that's not good, either. I need to finish the first retrieveTransport; without that, I can't continue the first onPostExecute.
use
getStatus()
checks whether the the AsyncTask is pending, running, or finished.and when finsh start your new task.like:
if(retrieveTransport.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(retrieveTransport.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(retrieveTransport.getStatus() == AsyncTask.Status.FINISHED){
// START NEW TASK HERE
}
example for your app:
if (retrieveTransport!= null && retrieveTransport.getStatus() == AsyncTask.Status.FINISHED) {
//START retrieveData TASK HERE
}
else
{
//IGNORE
}

Toast message if there is not data from server

i want to show in my search if it wont recieve similar result to my word i enterd it should Toast me "No Result.but problem is that it gets data after 0.5 seconds.so when i click button first it Toasts No results then gets data and show them in recyclerview.I want if there is not similar word it toast me No result at the end;
String text = txtsearch.getText().toString();
new AsyncTaskSearch("http://192.168.1.100/afgApp/search.php", text).execute();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!Activity_Search.data.equals("")) {
Toast.makeText(Activity_Search.this, data, Toast.LENGTH_SHORT).show();
timer.cancel();
}else {
Toast.makeText(Activity_Search.this, "No results", Toast.LENGTH_SHORT).show();
}
}
});
}
},1,500);
Activity_Search.data = "";
}
//Asynctask.java
public class AsyncTaskSearch extends AsyncTask{
public String link="";
public String text="";
public AsyncTaskSearch(String link,String text){
this.link=link;
this.text=text;
}
#Override
protected Object doInBackground(Object[] params) {
try{
String data= URLEncoder.encode("text","UTF8")+"="+URLEncoder.encode(text,"UTF8");
URL url=new URL(link);
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer=new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
builder.append(line);
}
Activity_Search.data=builder.toString();
}catch (Exception e){
}
return "";
}
}
I don't know how you are using your AysncTask. Try this code, it's working fine for me:
private class AsyncGetClass extends AsyncTask<Object, Void, String> {
ProgressDialog progressDialog;
String TAG, url;
AsyncHttpResponseHandler asyncHttpResponseHandler;
Context context;
public AsyncGetClass(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (!isProgressHiding)
if (progressDialog == null) {
progressDialog = createProgressDialog(context);
progressDialog.show();
} else {
progressDialog.show();
}
}
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(Object... params) {
// TODO Auto-generated method stub
TAG = (String) params[0];
url = (String) params[1];
asyncHttpResponseHandler = (AsyncHttpResponseHandler) params[3];
InputStream is = null;
String result = "";
// HTTP post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
Log.e(TAG, url);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e(TAG, "Error in http connection " + e.toString());
Toast.makeText(Activity_Search.this, "No results", Toast.LENGTH_SHORT).show();
}
// Convert response to string
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();
result = sb.toString();
// Log.i(TAG + ".result", result);
return result;
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
return null;
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (!isProgressHiding)
if (progressDialog != null)
progressDialog.dismiss();
if (result != null)
try {
Log.i(TAG, result);
asyncHttpResponseHandler.onSuccess(result);
} catch (Exception e) {
Log.e(TAG, "Must implement the interface " + e.toString());
}
}
}

Categories

Resources