AsyncTask loading data in very different amount of times in android - java

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.

Related

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
}

Making Attendance App in Android

I have to make attendance app for college.The app will take data from colleges website and display it on app according to user login and password.
When we login into college's website we have to put id and password, same thing I want on my app so that user can see it on an app itself.
I have searched httpurlconnection, httpget, httppost, jsoup.
Up till now, I have understood that I have to make httprequest for loading the college's attendance site and then httppost to post username and password and after that jsoup to grab the data from HTML page.
But I have seen tutorials only to request JSON pages, but how to request for HTML pages?and post login to it?
Here is what I tried and collected data from JSON
private TextView textresponse1;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Get= (Button) findViewById(R.id.httprequest);
textresponse1= (TextView)findViewById(R.id.textresponse);
progressDialog=new ProgressDialog(this);
Get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
progressDialog.setMessage("Collecting Data");
progressDialog.show();
}
public class JSONTask extends AsyncTask<String,String,String >{
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
String line="";
StringBuffer buffer=new StringBuffer();
while ((line = reader.readLine())!=null) {
buffer.append(line);
}
String finaljosn=buffer.toString();
StringBuffer add =new StringBuffer();
JSONObject parentobject=new JSONObject(finaljosn);
JSONArray parentarray=parentobject.getJSONArray("movies");
for(int i=0;i<parentarray.length();i++) {
JSONObject moviename = parentarray.getJSONObject(i);
String finalmovie = moviename.getString("movie");
int finalyear = moviename.getInt("year");
add.append(finalmovie +"- "+finalyear + "\n");
}
return add.toString();
// return finalmovie +" -Rushabh- " +finalyear;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException 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);
progressDialog.dismiss();
textresponse1.setText(result);
}
}
String mLoadURL="http://www.google.com";
public class LoadHtml extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(mLoadURL);
StringBuilder stringBuilder = new StringBuilder();
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.trim().isEmpty()) {
//load html to webview
}
}
}
Call Above AsyncTask using:
LoadHtml loadHtml= new LoadHtml();
load.execute();

OnClick event only works second time

I have a button that when used to run a asyntask class, I use it for set into a value in a textView. When he returns to the class that called the method, the value of the TextView caught and put in a Toast but the first time I click the Toast not appear any message, in the second works. What to do?
This is the method that calls the button
btnDadosPessoais.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pega = TextAux.getText().toString();
Toast.makeText(getActivity(), pega, Toast.LENGTH_SHORT).show();
gravarDadoss(view);
}
});
TV is my TextView, I'm putting a simple string
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}
Asyntask here
`public class BackgroudCadPessoa extends AsyncTask {
ProgressDialog dialog;
Context ctx;
String pega;
ConnectivityManager connectivityManager;
TextView tv;
BackgroudCadPessoa(Context ctx, View v) {
this.ctx = ctx;
dialog = new ProgressDialog(ctx);
tv = (TextView) v.findViewById(R.id.textAux);
}
#Override
protected void onPreExecute() {
connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
dialog.setMessage("Aguarde...");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
if (connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isAvailable() && connectivityManager.getActiveNetworkInfo().isConnected()) {
String urls = "my URL";
String nome = params[0];
try {
URL url = new URL(urls);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
return "Sem acesso à Internet";
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}
public void valida(String js)
{
JSONArray jsonArray;
if (js.equals(null)) {
tv.setText("Erro ao Cadastrar");
} else {
try {
JSONObject jo = new JSONObject(js);
jsonArray = jo.getJSONArray("Resposta");
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
pega = jsonObject.getString("resposta");
count++;
}
if (pega == null)
{
tv.setText("Erro ao Cadastrar");
}
else if (pega.equals("Dados Cadastrados"))
{
tv.setText("Dados Cadastrados");
}
else if (pega.equals("Erro ao Cadastrar"))
{
tv.setText("Erro ao Cadastrar");
}
else
{
tv.setText("Dados Cadastrados");
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}
}
`
You want your Toast to appear AFTER your AsyncTask finishes its output to TextAux?
Then you need to put your toaster in the onPostExecute
#Override
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
Toast.makeText(getActivity(), resposta, Toast.LENGTH_SHORT).show();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}

AsyncTask doInBackground comes with big delay

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;
}

Categories

Resources