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.
Related
iam developing an android app for parsing a json data set into my app. But everytime iam getting a NetworkOnMainThred exception:
android.os.NetworkOnMainThreadException
On this line:
HttpResponse response = httpclient.execute(httppost);
After that ive tried fixing it by puttin the progress in an AsyncTask Inner Class. But that has no effect iam getting the same error. Is the AsyncTask really essential?
Here the whole context:
question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Connector db = new Connector();
db.executeAction();//calls AsyncTask
}
});
public class Connector extends Activity {
View rootView;
ArrayList<String> resultset = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void executeAction() {
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
testDB2();
return null;
}
public void testDB2() {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1980"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://quizmaster.esy.es/db_con.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
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();
} catch (Exception e) {
//(TextView)rootView.findViewById(R.id.question)
Log.e("log_tag", "Error converting result " + e.toString());
}
ArrayList<String> resultset = new ArrayList<String>();
//parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
resultset.add(String.format(json_data.getString("Frage")));
Log.i("log_tag", "id: " + json_data.getInt("ID") +
", Frage: " + json_data.getString("Frage")
);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
Invocation:
public class Connector extends Activity {
View rootView;
ArrayList<String> resultset = new ArrayList<String>();
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void executeAction() {
new LongOperation().doInBackground();
}
Your onPostExecute() contains a call to testDB2(). onPostExecute() is executed on the main thread. Thus the exception.
Further, you never call doInBackground() directly. Instead, you would invoke the AsyncTask as:
new LongOperation().execute();
I want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.
Methods of Async task include:-
OnPreExecute()-Want to start progress dialog same for each class.
doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.
onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.
Now I'm writing the async task in my every class as inner class like the following:-
class loaddata extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddNewLineitem.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
compoment = json.getJSONArray(COMPONENT_CODE);
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
loadSpinnerData();
pDialog.dismiss();
}
}
And JSON parser class is as follows:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And in oncreate() I call this and it works fine:-
new loaddata().execute();
We can reuse Aysntask with different parameters. For this
1.Create an Interface so that we can reuse,pass and receive parameters
public interface BackgroundListener {
public Object[] startBackgroundWork(Object... objs);
public void endBackgroundWork(Object... objs);
public void beforeBackgroundWork();
}
2.Create a Class Extending Asyntask
BackgroundHandler.java
import android.os.AsyncTask;
public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
BackgroundListener backgroundListener;
public void setBackgroundListener(BackgroundListener aBackgroundListener)
{
this.backgroundListener = aBackgroundListener;
}
#Override
protected void onPreExecute() {
backgroundListener.beforeBackgroundWork();
}
#Override
protected Object[] doInBackground(Object... objs) {
return backgroundListener.startBackgroundWork(objs);
}
#Override
protected void onPostExecute(Object result[]) {
backgroundListener.endBackgroundWork(result);
}
}
Using in Activity
A.java
Class A extends Activity implements BackgroundListener
{
...onCreate()
{
BackgroundHandler backgroundHandler = new BackgroundHandler()
backgroundHandler.setBackgroundListner(this);
backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type
// show loading bar
}
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(A.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url_foralldropdowns = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();// hide loading bar
//access resultant parameters like objs[0], objs[1]
//user list_component will be in obj[0]
}
}
Similarly we can reuse in B.java
Class B extends Activity implements BackgroundListener
{
...
....
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(B.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url2 = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url2,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();
.....
//user list_component will be in obj[0]
}
}
Asyntask is just a class like others. Apart from the main inhertited methods of AsyncTask you can create your own methods, constructor etc. So just create a separate class in separate file. pass the context as parameter of the constructor. you can pass other values also to define the tasks.
class Loaddata extends AsyncTask<String, String, String> {
public Loaddata( pass the params){
... set the params
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Data. Please wait...");
pDialog.show();
}
protected void onPostExecute() {
// pDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}
I 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...
In the application that I'm building, I have to load some datas from a database.
I load the datas when the user select an item from an alert dialog.
I use an AsyncTask class to connect to the database. Here's the code:
public class GetTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... arg0) {
getProdotti();
return null;
}
#Override
protected void onPostExecute(Void result) {
pg.dismiss();
for(int w=0;w<all_id.length;w++){
_id.add(all_id[w]);
nomi.add(all_names[w]);
foto.add(all_images[w]);
prezzi.add(all_prices[w]);
descr.add(all_desc[w]);
}
lista = (ListView)findViewById(R.id.lista_prodotti);
ListViewAdapter lva = new ListViewAdapter(nomi , foto , prezzi , _id , descr , context);
lista.setAdapter(lva);
}
protected void onPreExecute(Void result) {
pg = ProgressDialog.show(context, "", "Caricamento in corso...");
}
#Override
protected void onProgressUpdate(Void... values) {
}
}/**/
And i call it so
GetTask cat = new GetTask();
cat.execute();
The progress dialog is shown, but it doesn't disappear and the ListView is not populated.
What i'm doing wrong?
Here's getProdotti():
private void getProdotti(){
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost(host_url);
datas = new ArrayList<NameValuePair>(1);
datas.add(new BasicNameValuePair("categoria",selected));
Log.d("INVIO",selected);
httppost.setEntity(new UrlEncodedFormEntity(datas));
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
}catch (Exception e){
Toast.makeText(Catalogo.this, "error"+e.toString(), Toast.LENGTH_LONG).show();
}
if(inputStream != null){
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
result = sb.toString();
Log.d("RESULT",result);
}catch(Exception e){
Log.e("TEST", "Errore nel convertire il risultato "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
all_id = new String[jArray.length()];
all_names = new String[jArray.length()];
all_prices = new String[jArray.length()];
all_images = new String[jArray.length()];
all_desc = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
JSONObject json_prod = jArray.getJSONObject(i);
Log.d("Debug",json_prod.getString("id_prodotto")+"--"+json_prod.getString("nome_prodotto"));
all_id[i]=json_prod.getString("id_prodotto");
all_names[i]=json_prod.getString("nome_prodotto");
all_prices[i]=json_prod.getString("prezzo");
all_images[i]=json_prod.getString("foto_prodotto");
all_desc[i]=json_prod.getString("descrizione");
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Try adding lva.notifyDataSetChanged() inside onPostExecute like this :
lista = (ListView)findViewById(R.id.lista_prodotti);
ListViewAdapter lva = new ListViewAdapter(nomi , foto , prezzi , _id , descr , context);
lista.setAdapter(lva);
lva.notifyDataSetChanged();
Hope this helps, good luck ^^
Actually you have to tell the progress bar to disappear
you have tow ways
first
after setting the adapter to the list call
#Override
protected void onPostExecute(Void result) {
.....
pg.dismiss();
Or you can use handler
define a hanlder such
Handler handler = new Handler (){
#Override
protected void handleMessage(int what){
if(pg.isShowing()){
pg.dismiss();
}
}
}
And in onPostExecute method call
handler.sendEmptyMessage(0);
this will help !!!
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