I'm trying to show a ProgressDialog from an AsyncTask but is not showing... if I delete the 'dialog.dismiss()' of the PostExecute, this task works like a 'post()', it shows the Dialog in the end of the task. I'm getting crazy with this!
private static class Experimento extends AsyncTask<String, Void, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog = new ProgressDialog(Config.getCurrent_Context());
dialog.setMessage("Cargando...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... params)
{
try
{
Config.getCurrent_Context().runOnUiThread(new Runnable()
{
#Override
public void run()
{
try
{
//Work, work, work...
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
dialog.dismiss();
}
}
Now tried giving the Activity in the constructor but still not working...
private static ProgressDialog dialog;
public Experimento(Activity act)
{
Log.w("Experimento", "Experimento");
dialog = new ProgressDialog(act);
dialog.setMessage("Cargando...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
You should remove setIntermidiate(true);
Try this, it works for me:
Override
protected void onPreExecute()
{
dialog = new ProgressDialog(Config.getCurrent_Context());
dialog.setMessage("Cargando...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... params)
{
String result = " ";
try
{
Config.getCurrent_Context().runOnUiThread(new Runnable()
{
#Override
public void run()
{
try
{
//Work, work, work...
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result)
{
dialog.dismiss();
}
Related
I am having a problem which is I think that I can't access th,e ListView from the asyncTask
Actually, I really don't know the real problem here
Let me show you what is happening
I have an activity which is executing AsyncTask and creates HttpURLConnection. Sometimes I get an exception (ProtocolException) because the stream un-expectedly ends.
So, I created a handler for this exception that calls a function or a method inside the class of the activity to display a message to the user
Here is a picture so you understand what is my project.
image
the problem here whenever the exception is thrown, the same function/method that I use to add the text to the listView is called, but after it called the listView disappear, but when I minimize the soft keyboard manually the everything becomes fine.
the structure of my class is
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
addMessageToListView()//works fin here
}
protected void addMessage(String message, int userMessage, ListView listView) // the function
{
try
{
messages.add(new Message(message,userMessage));
MessagesAdapter messagesAdapter = new MessagesAdapter(messages, getBaseContext());
messagesAdapter.notifyDataSetChanged();
listView.setAdapter(messagesAdapter);
}
catch (Exception exception)
{
}
}
private class HttpPostAsyncTask extends AsyncTask<String, Void, String>
{
...
#Override
protected void onPostExecute(String result)
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
}
}
protected String doInBackground(String... params)
{
String result = "";
for (int i = 0; i <= 0; ++i)
{
result = this.invokePost(params[i], this.postData);
}
return result;
}
private String invokePost(String requestURL, HashMap<String, String> postDataParams)// called from doInBackground
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
addMessageToListView()//not orking here
}
}
}
}
I don't know how to explain more actually.
You can change Views only in mainthread of your app. The doInBackground doesn't run in mainthread of your app.
Solved by adding:
new Thread()
{
#Override
public void run()
{
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
addMessageToListView()//not orking here
}
});
super.run();
}
}.start();
Editing the previous code in my question:
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
addMessageToListView()//works fin here
}
protected void addMessage(String message, int userMessage, ListView listView) // the function
{
try
{
messages.add(new Message(message,userMessage));
MessagesAdapter messagesAdapter = new MessagesAdapter(messages, getBaseContext());
messagesAdapter.notifyDataSetChanged();
listView.setAdapter(messagesAdapter);
}
catch (Exception exception)
{
}
}
private class HttpPostAsyncTask extends AsyncTask<String, Void, String>
{
...
#Override
protected void onPostExecute(String result)
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
}
}
protected String doInBackground(String... params)
{
String result = "";
for (int i = 0; i <= 0; ++i)
{
result = this.invokePost(params[i], this.postData);
}
return result;
}
private String invokePost(String requestURL, HashMap<String, String> postDataParams)// called from doInBackground
{
try
{
addMessageToListView()//works fin here
}
catch (Exception exception)
{
new Thread()
{
#Override
public void run()
{
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
addMessageToListView()//not orking here
}
});
super.run();
}
}.start();
}
}
}
}
I want to fetch data from two tables, Employee and Education, in odata4j. The common column is EmployeeId.
How can I join the tables? I use this for fetching data but it takes more time then expected.
private void DataListPosition() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
ConnectionOData4j connectionClass = new ConnectionOData4j(context);
ODataConsumer consumer = connectionClass.getConnection();
for(OEntity entity : consumer.getEntities("Employee").execute()){
final String name=entity.getProperty("Name" , String.class).getValue();
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
EmployeeName=name;
}
});
}
}catch (Exception e) {
final String strError=e.getMessage();
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, strError, Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}.execute();
}
private void DataListEducation() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
ConnectionOData4j connectionClass = new ConnectionOData4j(context);
ODataConsumer consumer = connectionClass.getConnection();
for(OEntity entity : consumer.getEntities("Education").execute()){
final String education=entity.getProperty("Education" , String.class).getValue();
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
EmployeeEducation=education;
}
});
}
}catch (Exception e) {
final String strError=e.getMessage();
((Activity)context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, strError, Toast.LENGTH_LONG).show();
}
});
}
return null;
}
}.execute();
}
This error is Showing often "The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread."
Getting the NewsList and other images and ads from API using JSON.
class LongOperation extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
}
protected String doInBackground(String... params) {
try {
AdSpotList.add(sched);
Image_view_List.add(sched);
NewsList.add(sched);
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
}
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
if (NewsList.size() != 0) {
if (NewsList.size() <= 5) {
adapter = new CustomAdapter(getActivity(),
Image_view_List, NewsList, AdSpotList, res);
lv_daily_summary.setAdapter(adapter);
} else {
getActivity().runOnUiThread(new Runnable() {
public void run() {
lv_daily_summary.invalidateViews();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
};
This complete page is on the Fragment.
This question already has answers here:
Updating progress dialog in Activity from AsyncTask
(2 answers)
How to use AsyncTask to show a ProgressDialog while doing background work in Android? [duplicate]
(2 answers)
Closed 8 years ago.
I want to add progressbar while new activity is not opened.
on next activity I am also fetching data so I want to add a progress bar on next activity also.
Here is my code.
login=(Button)dialog.findViewById(R.id.buttonLogin);
login.setOnClickListener(new OnClickListener() {
#SuppressLint("DefaultLocale")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(LoginUsername.getText()==null||LoginUsername.getText().toString().equals(""))
{
LoginUsername.setHint("Enter Username");
LoginUsername.setHintTextColor(Color.RED);
}
else if(LoginPassword.getText()==null||LoginPassword.getText().toString().equals("")||LoginPassword.getText().toString().length()<6)
{
LoginPassword.setText("");
LoginPassword.setHint("Enter Password");
LoginPassword.setHintTextColor(Color.RED);
}
else
{
String username=LoginUsername.getText().toString();
String password=LoginPassword.getText().toString();
username1=username.toLowerCase();
// fetch the Password form database for respective user name
//String loginentries=database.getSingleEntry(username1);
//type=database.getType(username1);
try{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://www.universal-cinemas.com/android/login.php");
JSONObject jobj=new JSONObject();
jobj.put("username",username1);
jobj.put("password", password);
post.setEntity(new StringEntity(jobj.toString()));
Log.i("Info", "Sending request");
HttpResponse res=client.execute(post);
Log.i("Info", "Executed");
InputStream inp=res.getEntity().getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(inp));
StringBuilder sb= new StringBuilder();
sb.append(bf.readLine()+"\n");
String tmp="0";
while((tmp=bf.readLine())!=null)
{
sb.append(tmp+"\n");
}
String result= sb.toString();
JSONArray jarray=new JSONArray(result);
for(int i=0;i<jarray.length();i++)
{
a=1;
JSONObject job=jarray.getJSONObject(i);
type=job.getString("type");
currency=job.getString("currency");
}
}
catch(Exception e)
{
e.printStackTrace();
}
if(a==1)
{
i=new Intent(getApplicationContext(),User_MainOptions_List.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(), "Welcome "+username, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Username and Password is not correct", Toast.LENGTH_SHORT).show();
}
}
}
});
dialog.show();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); // retrieves the windows attributes
lp.dimAmount=0.7f;// sets the dimming amount to zero
dialog.getWindow().setAttributes(lp); // sets the updated windows attributes
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); // adds the flag to blur bg
}
});
class MyLodingAsycTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
public void run() {
progressDialog = new ProgressDialog(CameraActivity.this);
progressDialog.setMessage("Loding...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#Override
protected Void doInBackground(Void... params) {
//call HTTP service
return null;
}
}
try this
private class MyAsync extends AsyncTask {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
//do what u want
return result;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
}
I am fairly new to Android development so I thought I would start off with a basic app. When a button is pressed, it copies a file to the location written in the code (see my code below). When I press the install button and the file is copied to its location, I want a toast message to display "Successfully Installed or Error while copying file". How would I implement this?
public class TrialActivity extends Activity {
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
runDialog(5);
}
private void runDialog(final int seconds)
{
progressDialog = ProgressDialog.show(this, "Please Wait...", "unpacking patch in progress");
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(seconds * 1000);
progressDialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
((Button)findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramView)
{
}
{
InputStream in = null;
OutputStream out = null;
String filename="savegame.bin";
try {
in = getResources().openRawResource(R.raw.savegame);
out = new FileOutputStream("/sdcard/Android/data/files/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
);
}
}
use next code:
private class AsyncTaskDialog extends AsyncTask<Void, Void, Void> {
Toast toastSuccess;
boolean flagSuccessCopy =false;
protected void onPreExecute() {
super.onPreExecute();
}
}
protected Boolean doInBackground(Void... params) {
copyFiles();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (getActivity() != null) {
if(flagSuccessCopy){
toastSuccess = Toast.makeText(context, "Success", duration);
}else{
toastSuccess = Toast.makeText(context, "Error", duration);
}
toast.show();
}
}
Allows to copy any file from any application to SD card
import ru.gelin.android.sendtosd.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ProgressDialog extends AlertDialog implements Progress {
/** Activity for which the dialog is created */
Activity activity;
/** Progress manager for the dialog */
ProgressManager manager = new ProgressManager();
/**
* Creates the customized progress dialog for
* activity.
*/
protected ProgressDialog(Activity activity) {
super(activity);
}
#Override
public void setFiles(int files) {
synchronized (manager) {
manager.setFiles(files);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateTotalProgress();
}
}
});
}
#Override
public void nextFile(final File file) {
synchronized (manager) {
manager.nextFile(file);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateFileName(file);
updateFileProgress();
updateTotalProgress();
}
}
});
}
#Override
public void processBytes(long bytes) {
synchronized (manager) {
manager.processBytes(bytes);
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
synchronized (manager) {
updateFileProgress();
}
}
});
}
void updateTotalProgress() {
ProgressBar progress = (ProgressBar)findViewById(R.id.total_progress);
progress.setMax(manager.getFiles());
progress.setProgress(manager.getFile());
TextView text = (TextView)findViewById(R.id.total_files);
text.setText(getContext().getString(R.string.files_progress,
manager.getFile(), manager.getFiles()));
}
void updateFileName(File file) {
if (file == null) {
return;
}
TextView view = (TextView)findViewById(R.id.file_name);
view.setText(file.getName());
}
void updateFileProgress() {
ProgressBar progress = (ProgressBar)findViewById(R.id.file_progress);
if (manager.getProgressInUnits() < 0) {
progress.setIndeterminate(true);
} else {
progress.setIndeterminate(false);
progress.setMax((int)(manager.getSizeInUnits() * 10));
progress.setProgress((int)(manager.getProgressInUnits() * 10));
}
TextView text = (TextView)findViewById(R.id.file_size);
text.setText(getContext().getString(manager.getSizeUnit().progressString,
manager.getProgressInUnits(), manager.getSizeInUnits()));
}
}
source: http://code.google.com/p/sendtosd-android/source/browse/src/ru/gelin/android/sendtosd/progress/ProgressDialog.java?spec=svn0933973391a12bee4759a32f5776864c64022d71&r=0933973391a12bee4759a32f5776864c64022d71