AsyncTask get String value output and store in mainthread variable - java

I'd like to get the string value output from AsyncTask. And store it into a variable on my main thread. How can I do so?
I tried to do store = new ReceiveData().execute().get() however it throws an execution exception error. But anyway, my question is not about the execution exception error. I just need a way to get the string out, please help!
Here is my activity code:
public class MainActivity extends AppCompatActivity { //MAIN ACTIVITIES (REMOTE)
double multiplier;
int seekbarvalue, finallumens;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); //On orientation change socket will disconnect...
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toast.makeText(MainActivity.this, LoginActivity.SERVER_IP, Toast.LENGTH_LONG).show();
//================START AFTER DEFAULT ON CREATE=================
SeekBar seekbarbrightness = (SeekBar) findViewById(R.id.seekbarbrightness);
final TextView tblumens, tbvolts, tbamps;
tblumens = (TextView) findViewById(R.id.tblumens);
seekbarvalue = seekbarbrightness.getProgress();
multiplier = (double) seekbarvalue / 100;
finallumens = (int) (multiplier * LoginActivity.enterlumens);
tblumens.setText(String.valueOf(finallumens) + " Lumens");
tbvolts = (TextView) findViewById(R.id.tbvolts);
tbamps = (TextView) findViewById(R.id.tbamps);
seekbarbrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekbarbrightness, int progress, boolean b) {
if (b == true) {
seekbarvalue = seekbarbrightness.getProgress();
multiplier = (double) seekbarvalue / 100;
finallumens = (int) (multiplier * LoginActivity.enterlumens);
tblumens.setText(String.valueOf(finallumens) + " Lumens");
if (LoginActivity.getSocket() != null) {
try {
LoginActivity.getSocket().getOutputStream().write(String.valueOf(multiplier).getBytes());
new ReceiveData().execute();
//infinite loop here to keep receiving volts and amperes.
//Do a split and assign value to volt and amp
//String[] strrecv= store.split("|");
//String volts = strrecv[0];
//String amps = strrecv[1];
//tbvolts.setText("Voltage: " + volts + " V");
//tbamps.setText("Amperes:" + amps + " A");
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "NOT connected To Socket, please disconnect and reconnect!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
And in my Asynctask I am doing this.
class ReceiveData extends AsyncTask<Void, Void, String> {
String str;
protected String doInBackground(Void... args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
str = in.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
String str = "fail";
return str;
}
}
protected void onPostExecute(String str) {
//super.onPostExecute(str);
}
}

The purpose of AsyncTask is to perform asynchronous task in a separate thread to free the main thread and avoid UX issues. For your purpose, I suggest transferring all of the work inside your try block inside the AsyncTask and update the UI after execution.
Something like this
In MainThread
new ReceiveData().execute();
In AsyncTask
class ReceiveData extends AsyncTask<Void, Void, Boolean> {
String volts;
String amps;
protected Boolean doInBackground(Void... args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
str = in.readLine();
String[] strrecv= store.split("|");
volts = strrecv[0];
amps = strrecv[1];
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
protected void onPostExecute(Boolean result) {
if (result) {
tbvolts.setText("Voltage: " + volts + " V");
tbamps.setText("Amperes:" + amps + " A");
}
}
}
Note that this only works if your AsyncTask is defined inside your Activity. If not, you need to create an interface from the AsyncTask and implement it in your activity and activate it onPostExecute

Related

Java Android modifies member variables from Callback thread

Basically, I am trying to get some value from the Api callback response, then assign those value to some of my member variables, but It seems like the program has to run over my getPatientRecord() method each time before it could go to my call, which I have never encountered before.
The Log output result is :
viewPatient: paitient method
viewPatient: secondHello worldnullnull
100SN9 - David Hello H M H 1971-08-09
This is my code:
public class ViewPatientRecord extends AppCompatActivity{
TextView tvName, tvGender, tvBirthDate, tvAddress;
String pGender, pAddress, pBirthdate;
String pName = "Hello world";
Patient myPatient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_patient_record);
tvName = findViewById(R.id.tvFullName);
tvGender = findViewById(R.id.tvGender);
tvBirthDate = findViewById(R.id.tvDb);
tvAddress = findViewById(R.id.tvAddress);
myPatient= new Patient();
try {
getPatientRecord();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void getPatientRecord() throws InterruptedException {
SharedPreferences myPre = getSharedPreferences("PatientRecord", MODE_PRIVATE);
if(myPre.getString("uuid",null)!=null){
retrievePatientByUuid(myPre.getString("uuid",null));
Log.d("viewPatient", "second"+pName+pGender+pBirthdate);
tvName.setText(pName);
tvGender.setText(pGender);
tvBirthDate.setText(pBirthdate);
tvAddress.setText(pAddress);
}else{
Toast.makeText(ViewPatientRecord.this, "Something went wrong, please contact the administrator for help!", Toast.LENGTH_SHORT).show();
}
}
private void retrievePatientByUuid(String uuid) throws InterruptedException {
RestApi api = RetrofitInstance.getRetrofitInstance().create(RestApi.class);
Log.d("viewPatient", "paitient method");
Call<Patient> call = api.getPatientByUUID(uuid, null);
call.enqueue(new Callback<Patient>() {
private volatile Patient obj = new Patient();
#Override
public void onResponse(Call<Patient> call, Response<Patient> response) {
if (response.body() != null) {
Patient patient = response.body();
if (patient != null) {
if (!patient.getDisplay().isEmpty()) {
pName = patient.getDisplay();
pGender = patient.getPerson().getGender();
pBirthdate = patient.getPerson().getBirthdate();
Log.d("viewPatient", pName.toString() + " H " + pGender.toString() + " H " + pBirthdate.toString() + " ?? ");
pAddress = "";
} else {
Log.d("viewPatient", "no results");
}
} else {
Toast.makeText(ViewPatientRecord.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(ViewPatientRecord.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Patient> call, Throwable t) {
t.printStackTrace();
}
});
}
}
I don't see the problem. The call is done in retrievePatientByUuid which is called by getPatientRecord. So yes, you have to go through getPatientRecord. The call is async. It's in the callback that you should set your TextViews :
tvName.setText(pName);
tvGender.setText(pGender);
tvBirthDate.setText(pBirthdate);
tvAddress.setText(pAddress);

OnMenuButton not posting data to google spreadsheets

Hey guys i have got this problem for a while now and i cannot figure out as to why it is not working. when i use the code provided by the tutorial that i have followed on YouTube it works fine, which is posting that data as soon as the application starts. However what i am trying to do is post the data as soon as the "Save Register" button is pressed in the menu but the it doesnt work and returns the message as shown in Log Cat.
I am getting the feeling that i am supposed to create an Async task for this however because my android programming is very limited i am not to sure how i would go about creating this.
My Main activity Class:
public class MainActivity extends Activity{
boolean wasApEnabled = false;
static AccessPoint wifiAP;
private WifiManager wifi;
static Button apButton;
static TextView textView;
final String myTag = "DocsUpload";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apButton = (Button) findViewById(R.id.toggleBtn);
textView = (TextView) findViewById(R.id.wifiClients);
apButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
});
/*Log.i(myTag, "OnCreate()");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
postData();
}
});*/
//t.start();
wifiAP = new AccessPoint(this);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
postData();
scan();
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
private void scan(){
wifiAP.getClientList(false, new FinishScanListener() {
#Override
public void onFinishScan(final ArrayList<ClientScanResult> clients) {
textView.setText("WifiApState:" + wifiAP.getWifiApState()+ "\n\n");
textView.append("Clients: \n");
for (ClientScanResult clientScanResult : clients){
textView.append("====================\n");
textView.append("ipAddress: " + clientScanResult.getIpAddress() + "\n");
textView.append("Device: " + clientScanResult.getDevice() + "\n");
textView.append("macAddress: " + clientScanResult.getMacAddress() + "\n");
textView.append("isReachable: " + clientScanResult.isReachable() + "\n");
}
}
});
}
public void postData() {
String fullUrl = "https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse";
HttpRequest mReq = new HttpRequest();
String col1 = "Hello";
String col2 = "World";
String data = "entry_272641491=" + URLEncoder.encode(col1) + "&" +
"entry_130393492=" + URLEncoder.encode(col2);
String response =mReq.sendPost(fullUrl, data);
// Log.i(myTag, response);
}
#Override
public void onResume() {
super.onResume();
if (wasApEnabled) {
if (wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLED && wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLING) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
}
updateStatusDisplay();
}
#Override
public void onPause() {
super.onPause();
boolean wifiApIsOn = wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING;
if (wifiApIsOn){
wasApEnabled = true;
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}else {
wasApEnabled = false;
}
updateStatusDisplay();
}
public static void updateStatusDisplay(){
if (wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING){
apButton.setText("Turn Off");
}else {
apButton.setText("Turn on");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,0,0, "Get Clients");
menu.add(0,1,0, "Save Register");
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()){
case 0:
scan();
break;
case 1:
postData();
break;
}
return super.onMenuItemSelected(featureId, item);
}
}
This is the helper class that i have used, Credit goes to this stack overflow user for creating this class
Secure HTTP Post in Android
This is the log cat that i am getting
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance D/Your App Name Here﹕ https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse?entry_272641491=Hello&entry_130393492=World
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance E/WifiAttendance﹕ HttpUtils: android.os.NetworkOnMainThreadException
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance D/WifiAttendance﹕ Returning value:null
I am getting the feeling that i am supposed to create an Async task
for this
Correct. NetworkOnMainThreadException is thrown when you are trying to make network calls on your Main Thread (UI thread).
You can find a good tutorial on AsyncTask here.
Example from the tutorial:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
//Do your network calls here
return response;
}
#Override
protected void onPostExecute(String result) {
//When you are done, this method runs on the UI thread so you can update the UI from here
textView.setText(result);
}
}
Finally you execute it like so
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.vogella.com" });
Thank you for the #Marcus for the helpful links i managed to get it working using this code:
public class PostDataTask extends AsyncTask<String, Void, Integer>{
#Override
protected Integer doInBackground(String... params) {
HttpRequest mReq = new HttpRequest();
String data = "entry_272641491=" + URLEncoder.encode(params[1]) + "&" +
"entry_130393492=" + URLEncoder.encode(params[2]);
String response = mReq.sendPost(params[0], data);
return 200;
}
}

Returning a bitmap file from AsyncTask freezes UI thread

I have created a simple Activity. The activity is responsible for downloading data from parse.com database and populating a linear layout. In the process, I am dynamically creating the linear layout with TextViews and ImageViews according according to the content.
The problem is that, whenever I try to download an image, I use as AsyncTask Downloading class, which results in slowing down the UI thread! I am currently trying to return the bitmap file from the AsyncTask Image downloading class using: returnedBitmap = new LoadImage().execute(src).get(); which might be responsible for slowing down the UI thread. I have to do this because the caller method geneterImageView will return an imageview when it receives the bitmap file.
The complete Activity code:
public class MainActivity extends ActionBarActivity {
ArrayList<String> heightList = new ArrayList<String>();
ArrayList<String> reversedList = new ArrayList<String>();
ImageView imageView1;
Bitmap bitmap;
RelativeLayout parent_layout;
ParseObject user;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// imageView1 = (ImageView)findViewById(R.id.imageView1);
parent_layout = (RelativeLayout) findViewById(R.id.parent_layout);
login("xyz#xyz.com", "xyz");
}
private void loopThroughArrayAndAttach(){
LinearLayout llInner = new LinearLayout(this);
llInner.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
parent_layout.addView(llInner);
for (int i = 0; i < heightList.size(); i++) {
if (hasNoImagess(heightList.get(i)) == true) {
// No images.
TextView myText = geneterTextView(heightList.get(i));
llInner.addView(myText);
// geneterTextView(heightList.get(i));
} else {
ImageView myImage = geneterImageView(heightList.get(i));
llInner.addView(myImage);
// geneterImageView(heightList.get(i));
}
}
}
public static boolean hasNoImagess(String contents){
Document doc = Jsoup.parse(contents);
Element element = doc.body();
Elements elements = element.select("img");
if (elements.isEmpty()) {
return true;
} else {
return false;
}
}
public ImageView geneterImageView(String imgContent){
// Will need to run via background thread - like aysnc
// Extract the image file via jsoup
// Insert it into a imagevieww
// Inser that into a layout.
Log.d("IN IMAGE ", " " + imgContent);
Document doc = Jsoup.parse(imgContent);
Elements img = doc.getElementsByTag("img");
Bitmap returnedBitmap = null;
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("src attribute is : " + src);
// new DownloadImageTask((ImageView)
// findViewById(R.id.imageView1)).execute(src);
try {
returnedBitmap = new LoadImage().execute(src).get();
// imageView1.setImageBitmap(returnedBitmap);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageView iv = new ImageView(this);
iv.setImageBitmap(returnedBitmap);
return iv;
}
public TextView geneterTextView(String textContent){
// Will need to run via background thread.
Log.i("In TEXT ", " " + textContent);
TextView tv = new TextView(this);
tv.setText(Html.fromHtml(textContent));
return tv;
}
// to download images
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
protected Bitmap doInBackground(String... args){
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image){
if (image != null) {
} else {
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
// to login to parse
private void login(final String username, String password){
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e){
if (e == null) {
// if login sucess
// Start intent
// loginSuccess();
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
CloudCallStudentPosts(user);
} else {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
}
});
}
// //to get data from parse
public void CloudCallStudentPosts(ParseObject s){
setRichStory(s);
}
private void setRichStory(ParseObject s){
// Simialr to setStory, once implemented delete setStory()
new AddStoryAsync(s).execute();
}
class AddStoryAsync extends AsyncTask<Void, Object, Void> {
private static final String TAG = "LazyListView";
ParseObject s;
public AddStoryAsync(ParseObject s) {
this.s = s;
Log.w("In richStory", "ParseObject Id: " + s.getObjectId());
}
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... unused){
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userid", this.s.getObjectId());
params.put("skip", 0);
ParseCloud.callFunctionInBackground("studentsPosts", params, new FunctionCallback<List<List<ParseObject>>>() {
#Override
public void done(List<List<ParseObject>> postList, com.parse.ParseException arg1){
if (postList == null) {
} else {
if (postList.size() > 0) {
// CustomWebView cwb;
for (int i = 0; i < postList.size(); i++) {
// final Post post = new Post();
if (postList.get(i).get(0).get("htmlContent") == null) {
}
if (postList.get(i).get(0).get("htmlContent") != null) {
Log.e("htmlContent parse", postList.get(i).get(0).get("htmlContent").toString());
// Parse HTML String using JSoup library
String HTMLSTring = postList.get(i).get(0).get("htmlContent").toString();
Document html = Jsoup.parse(HTMLSTring);
Elements paragraphs = html.getElementsByTag("p");
for (org.jsoup.nodes.Element paragraph : paragraphs) {
String paragraphText = paragraph.toString();
Log.e("paragraphText", paragraphText);
heightList.add(paragraphText);
}
loopThroughArrayAndAttach();
}
}
}
}
}
});
return (null);
}
#Override
protected void onProgressUpdate(Object... object){
Log.w("onProgressUpdate ", " " + object[0].getClass());
Log.w("adding to arrayPostList ", " " + object[0].getClass());
}
#Override
protected void onPostExecute(Void unused){
}
}
}
Is there any substitute for getting the bitmap from the AsyncTask and set it in the imageview? Should there be a logical alteration in the approach?
try this :
dont call get() #praveen. instead pass the imageview Reference in the constructor
WorkerThread mWorkerThread = new WorkerThread(mImageView);
mWorkerThread.execute(src);
private class WorkerThread extends AsyncTask<String, String, Bitmap> {
private WeakReference<ImageView> imageViewReference;
public WorkerThread(ImageView imageView) {
super();
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... args) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null && imageViewReference.get() != null) {
imageViewReference.get().setImageBitmap(result);
}
}
}
Don't call get() method on AsyncTask it makes main thread to wait for AsyncTask to complete. If you really want to start something only after AsyncTask completes put that into onPostExecute() of your AsynTask
As others have mentioned, your code has several design flaws which makes it difficult to provide you a solution to your problem.
The whole purpose of an AsyncTask is to execute on a background thread. Executing networking and bitmap processing on the main thread will never work. You must refactor your code to accommodate this. Consider the following solution to this particular problem at least:
// to download images
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... args) {
String imgContent = args[0];
Document doc = Jsoup.parse(imgContent);
Elements img = doc.getElementsByTag("img");
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("src attribute is : " + src);
try {
return BitmapFactory.decodeStream((InputStream) new URL(src).getContent());
} catch (Exception e) {
// log
}
}
return null;
}
protected void onPostExecute(Bitmap b) {
ImageView iv = new ImageView(MainActivity.this);
iv.setImageBitmap(b);
llInner.addView(iv);
}
}
You can then do something like:
for (int i = 0; i < heightList.size(); i++) {
new LoadImage(heightList.get(i)).execute();
}
However, this may not be desirable depending on how many AsyncTasks you end up creating. But this is the idea.

android AsyncTask in foreach

Have the following AsyncTask code:
private class checkChangesTask extends AsyncTask<String, Void, String> {
protected ProgressDialog mProgressDialog2;
protected String _url = "", _idautor="", _idbook="";
#Override
protected void onPreExecute() {
super.onPreExecute();
this.mProgressDialog2 = new ProgressDialog(MainActivity.this);
this.mProgressDialog2.setMessage("Check changes ...");
this.mProgressDialog2.setIndeterminate(false);
this.mProgressDialog2.setCanceledOnTouchOutside(false);
this.mProgressDialog2.setCancelable(true);
this.mProgressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.mProgressDialog2.setMax(100);
this.mProgressDialog2.setProgress(0);
this.mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[0];
_idbook = params[1];
_url = params[2];
try {
doc = Jsoup.connect(_url).userAgent("Mozilla").get();
Elements dd = doc.select("dd");
int size = dd.size();
int p = 1;
for (Element src : dd) {
this.mProgressDialog2.setProgress(p*100/size);
if (p <= size-1){
_html += src.outerHtml();
++p;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
String lastfile = readPageFile(_idautor + "_" + _idbook);
if(!lastfile.equals(result)){
savePageToFile(_idautor + "_" + _idbook, result);
}
}else{
Toast.makeText(MainActivity.this, "Error checkChangesTask", Toast.LENGTH_SHORT).show();
}
this.mProgressDialog2.dismiss();
}
the previous code I call in a loop:
public void checkChanges() {
String[][] db_books = db.selectAllBOOKS();
if (db_books.length>0){
for (int j = 0; j < db_books.length; j++){
new checkChangesTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, db_books[j][1], db_books[j][0], db_books[j][2]);
}
}
}
Everything works fine, but the dialog does not display the correct value. First, it is worth it to 0% and then abruptly switches to 100%.
AsyncTask called in sequence (...executeOnExecutor(AsyncTask.SERIAL_EXECUTOR...).
If you run a AsyncTask not in the loop, all the displays are just perfect!
android: targetSdkVersion = "14"
I ask your help.
You need to use onProgressUpdate() inside the AsyncTask. Something like this (at a guess)
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
this.mProgressDialog2.setProgress(progress[0] * 100/progress[1]);
}
And replace this line:
this.mProgressDialog2.setProgress(p*100/size);
With this:
publishProgress(new int[]{p,size})

Android: Progress Bar to Upload Data to the Server

In my application some data is there which is wrapped into an object.
I am sending this object to the server. Everything work correctly.
Here I want to show progress bar when the data is loading to the server.
For this I am using this code:
ProgressThread progThread;
ProgressDialog progDialog;
int typeBar;
int delay = 40;
int maxBarValue = 200;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
progDialog = new ProgressDialog(this);
progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progDialog.setMax(maxBarValue);
progDialog.setMessage("Data uploading to the Server..");
progThread = new ProgressThread(handler);
progThread.start();
return progDialog;
default:
return null;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// Get the current value of the variable total from the message data
// and update the progress bar.
int total = msg.getData().getInt("total");
progDialog.setProgress(total);
if (total <= 0) {
dismissDialog(typeBar);
progThread.setState(ProgressThread.DONE);
}
}
};
private class ProgressThread extends Thread {
final static int DONE = 0;
final static int RUNNING = 1;
Handler mHandler;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
#Override
public void run() {
mState = RUNNING;
total = maxBarValue;
while (mState == RUNNING) {
connectServerClass.saveOnServer(Object);
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total--; // Count down
}
}
public void setState(int state) {
mState = state;
}
}
When user click on button then:
typeBar = 1;
showDialog(typeBar);
connectServerClass.saveOnServer(Object)
by the above line I am sending object to the server. Actually I am sending data to the other class which is connectServerClass and this class send object to the server.
but this code not work correctly. This code connect to the server lots of time.
I use the following Code :
private class Uploader extends AsyncTask<Void, String, Integer>
{
private List<File> files;
private boolean canceled;
private int uploaded;
private Account account;
private ProgressDialog uploadSeekBar;
public Uploader(Account a, List<File> files)
{
this.account = a;
this.files = files;
}
#Override
protected void onPreExecute()
{
uploadSeekBar.setMax(files.size());
uploadSeekBar.setProgress(0);
uploadSeekBar.setVisibility(View.VISIBLE); //Error: the method setVisibility is undefined
}
#Override
protected void onPostExecute(Integer result)
{
uploadSeekBar.setVisibility(View.INVISIBLE);
Toast.makeText(Upload.this, result + " files uploaded", // Error: Upload cannot be resolved to a type
Toast.LENGTH_LONG).show();
}
#Override
protected void onCancelled()
{
// XXX need a way to actually cancel the last upload
Toast.makeText(Upload.this, "canceling upload", Toast.LENGTH_LONG)
.show();
this.canceled = true;
uploadSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected Integer doInBackground(Void... voids)
{
uploaded = 0;
try
{
Iterator<File> it = this.files.iterator();
while (!canceled && it.hasNext())
{
File file = it.next();
it.remove();
String msg = "";
try
{
if (debugMode) // what is this debugMode
{
//Put your uploading code here.
msg = ("fake uploading " + file);
Thread.sleep(3000);
} else
{
msg = ("uploading: " + file);
controller.uploadFile(file, this.account); //Error: controller cannot be resolved
}
uploaded++;
publishProgress(msg);
} catch (IOException e)
{
controller.te("error uploading file: " + file);
controller.te("error uploading file: " + e);
} catch (InterruptedException e)
{
}
}
} catch (Exception e)
{
publishProgress("error uploading: " + e);
}
return uploaded;
}
#Override
protected void onProgressUpdate(String... strings)
{
uploadSeekBar.setProgress(uploaded);
updateUploadMessage(files.size());
Toast.makeText(Upload.this, strings[0], Toast.LENGTH_LONG).show(); //Error: The method updateUploadMessage(int) is undefined for the type FirstActivity.Uploader
}
}
But I facing some error which I mention as comment in the right side of that line. Please suggest me.
I will strongly recommend you to Use AsyncTask.
Below Code snippet will help you on How your AsyncTask should look like.
package org.sample;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import android.accounts.Account;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Toast;
private class Uploader extends AsyncTask<Void, String, Integer>
{
private List<File> files;
private boolean canceled;
private int uploaded;
public Uploader(Account a, List<File> files)
{
this.account = a;
this.files = files;
}
#Override
protected void onPreExecute()
{
uploadSeekBar.setMax(files.size());
uploadSeekBar.setProgress(0);
uploadSeekBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Integer result)
{
uploadSeekBar.setVisibility(View.INVISIBLE);
Toast.makeText(Upload.this, result + " files uploaded",
Toast.LENGTH_LONG).show();
}
#Override
protected void onCancelled()
{
// XXX need a way to actually cancel the last upload
Toast.makeText(Upload.this, "canceling upload", Toast.LENGTH_LONG)
.show();
this.canceled = true;
uploadSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected Integer doInBackground(Void... voids)
{
uploaded = 0;
try
{
Iterator<File> it = this.files.iterator();
while (!canceled && it.hasNext())
{
File file = it.next();
it.remove();
String msg = "";
try
{
if (debugMode)
{
//Put your uploading code here.
msg = ("fake uploading " + file);
Thread.sleep(3000);
} else
{
msg = ("uploading: " + file);
controller.uploadFile(file, this.account);
}
uploaded++;
publishProgress(msg);
} catch (IOException e)
{
controller.te("error uploading file: " + file);
controller.te("error uploading file: " + e);
} catch (InterruptedException e)
{
}
}
} catch (Exception e)
{
publishProgress("error uploading: " + e);
}
return uploaded;
}
#Override
protected void onProgressUpdate(String... strings)
{
uploadSeekBar.setProgress(uploaded);
updateUploadMessage(files.size());
Toast.makeText(Upload.this, strings[0], Toast.LENGTH_LONG).show();
}
}

Categories

Resources