how to check the amount of data in each time uploaded to the server, this is my code which I call inside a AsyncTask
public String conxDatosInPost(String Direccion, ArrayList<NameValuePair> Parametros) throws Exception {
BufferedReader in = null;
try {
HttpClient client = ClienteHttp();
HttpPost request = new HttpPost(Direccion);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(Parametros);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
//long logitud = response.getEntity().getContentLength();
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();
Log.d("El resultado de cnxposin es :----------- ", result +"fn");
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This is my class CLienteHttp();
private HttpClient ClienteHttp() {
if (mHttpCliente == null) {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
mHttpCliente = new DefaultHttpClient();
final HttpParams params = mHttpCliente.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpCliente;
}
And this is my class asyncTask
public class NuevoPostImagen extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
objAcceso = new AccesoBd();
String jsRes="";
SharedPreferences userDetails = getParent().getSharedPreferences("MisPreferencias", MODE_PRIVATE);
ArrayList<NameValuePair> ParametrosDeEnvio = new ArrayList<NameValuePair>();
ParametrosDeEnvio.add(new BasicNameValuePair("from",Integer.toString(userDetails.getInt("Id",0))));
ParametrosDeEnvio.add(new BasicNameValuePair("idrecurso",Integer.toString(idEvento)));
ParametrosDeEnvio.add(new BasicNameValuePair("texto","nada"));
ParametrosDeEnvio.add(new BasicNameValuePair("titulo",txtFTitulo.getText().toString()));
ParametrosDeEnvio.add(new BasicNameValuePair("imageFile",sImagenBsase64));
try{
//here
String jes=objAcceso.conxDatosInPost(params[0],ParametrosDeEnvio);
jsRes = "ok";
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{return jsRes;}
}
#Override
public void onProgressUpdate(Integer... args){
Pro.setProgress(args[0]);
}
#Override
protected void onPostExecute( String result) {
Pro.dismiss();
if (result.toString().equals("ok")){
LlenarEvento();
dOpciones.dismiss();
dHacerFoto.dismiss();
}
}
#Override
protected void onPreExecute() {
Pro = ProgressDialog.show(getParent(), "", "Enviando",true,true);
Pro.setCancelable(false);
}
}
Can I update my progress bar with the existing code?
Once the cliente.execute (httpost).
I wonder how I can put a listener or something to check the number of bytes uploaded being updated every second or every time you upload them? I need to update my progress bar, according to the quantity that has been uploaded.
Please, I can help?
You can use async task for this. you have to over ride 3 methods.
doinbackground()
onpreexecute()
onpostexecute()
onProgressUpdate
i think this will help u to understand hw to do it . How to implement file upload progress bar in android
Related
Fantastic morg. Below this code to get data from mysql database and displayed into the EditText element.There is no problem with getting data from db its working good using this asyn tesk new checkUserPermission().execute("");.
Problem is
I want to make some calculation from code and dispaly in another Edittext. so i need values thats why i get data from db.while OnCreate() to get the data from db(its working). whenever i call this calculatePL(); method i could not get value.
LOGCAT:
System.out: Empty Value
Why its empty or something. but above my edittext elements hold the
values.
...some declaration of variables and etc....
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.five_activity);
new checkUserPermission().execute(""); //call here
calculatePL();//call the method
}
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
String[] splited = Allvalues.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
//Log.d("Splited String ", "Splited String" + totalamt+expen);
runOnUiThread(new Runnable() {
#Override
public void run() {
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
}
});
Log.i("TAG", "Result Retrieved");
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
// Close progress dialog
Dialog.dismiss();
}
}
public void calculatePL(){
try {
String a_value =totamt.getText().toString().trim();
System.out.println(a_value);
}catch(NumberFormatException numberEx)
{
System.out.println(numberEx);
}
}
Your checkUserPermission executes in background. And immediately you are calling calculatePL() so your main thread is not waiting for checkUserPermission execution to complete.
What you need to do is, make wait your main thread so that after full execution of checkUserPermission calculatePL() will get called. You can achieve it by adding ProgressDialog. Show the ProgressDialog in onPreExecute() and dismiss it in onPostExecute()
Hope it will do your job.
Override protected void onPostExecute in your asyncTask and call calculatePl() here. And you should set Edittext's text in onPostExecute too, because this method is main thread and you don't need to use runOnUIThread.
EDIT with example code:
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return Allvalues;
}
protected void onPostExecute(String result){
String[] splited = result.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
// Close progress dialog
Dialog.dismiss();
calculatePL();
}
}
Make sure totamt is declared as a global. Try logging the value of totamt or an object of the same. Finally check where you have declared it.
I want to show huge data (+50,000 records) in android listview using Async.
The data comes from web services(dot net) in pages(1000 records in each page).
As I get 1000 records I have to update the listview automatically (without scrolling).This process continues till all the records are fetched.
Am able to fetch all the records but unable to update listview.
My code is :
class XYZ extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params) {
for(int i=1;i<=noOfPagesFromServer;i++)
{
String url="http://182.72.123.138:9523/Service.svc/GetData/"+i;
try
{
HttpGet get =new HttpGet(url );
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String responseString = stringBuilder.toString();
JSONObject serverJSONObj = new JSONObject(responseString);
JSONArray serverJSONArray = serverJSONObj .getJSONArray("ABC");
for(int l=0;l<serverJSONArray.length();l++)
{
JSONObject tempJSONObject=serverJSONArray.getJSONObject(l);
a = tempJSONObject.getString("A");
b =tempJSONObject.getString("B");
Model model=new Model(a,b);
arrayList.add(model);}
} catch (Exception e) {
e.printStackTrace();
}
publishProgress(null);
SystemClock.sleep(6000);
}return null;}
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
adapter1 = new CustomListViewAdapter(SearchActivity.this,R.layout.row,arrayList);
listView.setAdapter(adapter1);
listView.this.adapter1.notifyDataSetChanged();
}
#Override
protected void onPostExecute(String result) {
try{
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter1 = new CustomListViewAdapter(SearchActivity.this,R.layout.row,arrayList);
adapter1.notifyDataSetChanged();
listView.setAdapter(adapter1);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
Thanks for your replies
You can use onProgressUpdate() and acheive the required result...update your model once you receive the 1000 records and update the list...
I have created a separate class for Asynchronous task. How can I pass the string value to that Asynchronous task class? Please refer my code below.
In Main class to call Asynchronous task class
String product_id,av_quantity;
Stock_updatetask = new Stock_update();
Stock_updatetask.execute(product_id,av_quantity);
How to send String product_id,av_quantity values to Asynchronous task Class
Asynchronous task Class
public class Stock_update extends AsyncTask<String, Void, String> {
JSONObject json = new JSONObject();
JSONArray jsonarray;
protected String doInBackground(String... params) {
try {
// checkInternetConnection();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),20000);
HttpConnectionParams.setSoTimeout(client.getParams(), 20000);
HttpResponse response;
HttpPost post = new HttpPost("http://www.name.in/cakefoodnew/customer/stockUpdate?json=");
/*json.put("submenu_id", "" + product_id);
json.put("available_quantity", "" + av_quantity);*/
// Log.v("id", ""+json);
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
if (response != null) {
// get a data
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
// Log.v("id", ""+a);
try {
jsonarray = new JSONArray("[" + a + "]");
json = jsonarray.getJSONObject(0);
//stock_update = (json.getString("Success"));
} catch (Exception e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
// Json response
private String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
get product_id,av_quantity values inside doInBackground method as :
//....your code here...
json.put("submenu_id", "" + params[0]); //<<<< get product_id
json.put("available_quantity", "" + params[1]); //<<< get av_quantity
// Log.v("id", ""+json);
post.setHeader("json", json.toString());
because doInBackground method parameter is Varargs you can get more about Varargs here
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
or second way is you can pass both values by creating an Stock_update constructor as :
public class Stock_update extends AsyncTask<String, Void, String> {
String product_id,av_quantity;
public Stock_update(String product_id,String av_quantity){
this.product_id=product_id;
this.av_quantity=av_quantity;
}
//your code here
}
pass both values at time of object creation of Stock_update class :
Stock_updatetask = new Stock_update(product_id,av_quantity);
now you are able to use product_id,av_quantity in whole Stock_update class including doInBackground
See this code
DownloadingProgressTask downloadingProgressTask = new DownloadingProgressTask(
Utilities.arrayRSSDownload.get(0).getUrl(),
mainprogressbar, Utilities.arrayRSSDownload
.get(0).getTitle());
downloadingProgressTask.execute();
And then in class
private class DownloadingProgressTask extends
AsyncTask<String, Integer, Boolean> {
String fileName;
ProgressBar progressbar;
/** progress dialog to show user that the backup is processing. */
public DownloadingProgressTask(String url1, ProgressBar progress,
String filetitle) {
urllink = url1;
fileName = filetitle;
progressbar = progress;
}
protected void onPreExecute() {
mainprogressbar.setProgress(0);
progressbar.setProgress(0);
myDatabase.updateDownloadStatus(fileName, 2);
// Updating the home screen list
setListData();
}
--- rest of code
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();
(I'm using 2.3.3)
The following code is an async task that puts up a progress dialog (pd), does an HttpPost in doInBackground(), and dismisses the progress dialog in onPostExecute(). It works perfectly about 75% of the time. But, 25% of the time the pd gets displayed and never goes away(the post gets done however). The only way the user can get rid of the pd is to go into settings and kill the app (even though "cancelable is set to true").
A timeout exception is NOT happening.
onPostExecute() is not getting executed or the pd.dismiss() is not working.
If I eliminate the pd everything always works perfectly 100% of the time.
What an be happening? Thanks.
class postStringToURLTask extends AsyncTask<URL, Void, String> {
String responseString = "";
#Override
protected void onPreExecute() {
String myEmailAddress = getPref("emailaddress");
pd = ProgressDialog.show(PSActivity.this,
"Emailing Trip to " + myEmailAddress, "", true);
}
#Override
protected String doInBackground(URL... urls) {
try {
URL onlyURL = urls[0]; //there is only one url
HttpResponse response = null;
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams,4000);
HttpConnectionParams.setSoTimeout(myParams, 4000);
HttpClient httpclient = new DefaultHttpClient(myParams);
HttpPost myPost = new HttpPost(onlyURL.toString());
StringEntity se = new StringEntity(payloadString);
myPost.setEntity(se);
myPost.setHeader("Accept", "application/json");
myPost.setHeader("Content-type", "text/plain");
response = httpclient.execute(myPost);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
responseString = line;
}
} catch (Exception e) {
debugLog("postStringToURLTask got exception" + e.getMessage().toString() , 1);
responseString = "error " + e.getMessage().toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
pd.dismiss();
debugLog("just dismissed progress dialog", 1);
result = result.replace("[","");
result = result.replace("\"","");
result = result.replace("]","");
////log.w(getClass().getName(), "onPostExecute received: " + result);
if (result == "") {
mpGood.start();
} else {
sdTripSentProblem(); //bad news dialog
logToServer(result);
}
}
}