I have a function name CreateVideo(), the problems are:
Because function must be run until it finishs to create a video, I cannot know how many percent completed of the video.
Did I put the function at a right place?
Here is the code:
private class MyVideo extends AsyncTask<Void, Void, String> {
private Context context;
private String output;
private String quality;
private FramePackage framePackage;
CreateMP4Video createMP4Video;
public MyVideo(Context context, FramePackage framePackage, String output, String quality) {
// TODO Auto-generated constructor stub
this.context = context;
this.output = output;
this.quality = quality;
this.framePackage = framePackage;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create Video Maker
createMP4Video = new CreateMP4Video(context, framePackage, output, quality);
// Create progress
mProgress = new ProgressDialog(MainActivity.this);
mProgress.setTitle("Please Wait..");
mProgress.setMessage("Creating Video...");
mProgress.setProgressStyle(mProgress.STYLE_HORIZONTAL);
mProgress.setProgress(0);
// set Max = total number of frame
mProgress.setMax(framePackage.getCount());
mProgress.setCancelable(false);
mProgress.show();
};
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
createMP4Video.CreateVideo();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (mProgress.getProgress() <= mProgress.getMax()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateBarHandler.post(new Runnable() {
public void run() {
// get the current frame (frame 1, 2, 3,...)
// that already added to video
// In thist case, it always get the last frame
// progress bar run from 0% to 100% directly
mProgress.setProgress(createMP4Video.getCurrentFrame());
}
});
if (mProgress.getProgress() == mProgress.getMax()) {
mProgress.dismiss();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
}
}
Thank you in advance!
Put theprogress dialog in onPreExecute() method as u have done
// Create progress
mProgress = new ProgressDialog(MainActivity.this);
mProgress.setTitle("Please Wait..");
mProgress.setMessage("Creating Video...");
mProgress.setProgressStyle(mProgress.STYLE_HORIZONTAL);
mProgress.setProgress(0);
// set Max = total number of frame
mProgress.setMax(framePackage.getCount());
mProgress.setCancelable(false);
mProgress.show();
Dismiss the dialog in onPostExecute
You can take a look at the progressupdate example ONPROGRESS UPDATE
Related
I have an app that sends a file through a socket. While doing this I want to show the progress in a ProgressDialog. The app sends the file perfectly but I'm not able to make the dialog appear.
public class ProgressDialogActivity extends Activity {
private ProgressDialog downloadDialog = null;
private String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
filePath = getIntent().getExtras().getString("filePath");
downloadDialog = new ProgressDialog(this);
Task myTask = new Task();
myTask.execute(0);
}
private void showMessage(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), msg, `enter code here`Toast.LENGTH_SHORT).show();
}
});
}
private class Task extends AsyncTask<Integer, Integer, Boolean> implements Observer
{
private Thread t;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
downloadDialog.setTitle("SENDING");
downloadDialog.setMessage("................");
downloadDialog.setCancelable(false);
downloadDialog.setIndeterminate(false);
// downloadDialog.setMax(100);
downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downloadDialog.show();
}
#Override
protected Boolean doInBackground(Integer... params) {
SendFile send = new SendFile(filePath);
downloadDialog.setMax(0);
t = new Thread(send);
send.registerObserver(this);
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
t.start();
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
int counter = values[0].intValue();
downloadDialog.setProgress(counter);
if(filePath != null)
{
downloadDialog.setMessage(filePath+"...");
}
}
#Override
public void update(Subject subject) {
// TODO Auto-generated method stub
if(subject instanceof SendFile)
{
SendFile e = (SendFile) subject;
if(e.getException() != null)
{
t.interrupt();
showMessage(e.getException());
} else
{
if(!e.isStarted())
{
initializeProgressBar(e.getNumIter());
} else
{
refreshProgressBar(e.getNumIter());
}
if(e.isSent())
{
t.interrupt();
showMessage("File sent");
}
}
}
}
public void initializeProgressBar(int max){
downloadDialog.setMax(max);
}
public void refreshProgressBar(int amount){
publishProgress(downloadDialog.getMax()-amount);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(downloadDialog != null)
{
downloadDialog.dismiss();
}
finish();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
t.interrupt();
showMessage("TASK CANCELLED");
}
};
}
SendFile is the class that contains the socket to send the files.
I think the problem is due to I'm calling the thread inside the AssyncTask because when I make Thread.sleep(10000) I can see the ProgressDialog for that time, but I don't know how to fix it.
Also, when I run the debugger I can see that the variable 'counter' is incremented every time I call it, but if I add a watch with 'downloadDialog.getProgress()' the progress is always 0.
You are creating an AsyncTask, which doInBackground() method RUNS IN BACKGROUND. In there, you don't do anything, but start a new thread... Now this thread does the work, but your AsyncTask finishes, because it has nothing to do after starting the other thread... So, your ProgressDialog is shown for some milliseconds, then your AsyncTask finishes and the ProgressDialog is hidden again. But the thread that is doing the work is still running, only your AsyncTask has finished.
Solution : Either use an AsyncTask OR use a thread.
You need to call publishProgress on doinBackground()
Example:
protected String doInBackground(Void... params) {
try {
int i = 0;
Log.i("Thread","1");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","2");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","3");
Thread.sleep(1000);
Log.i("Thread","4");
Thread.sleep(1000);
Log.i("Thread","5");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "done";
}
I have custom adapter list view with two spinner view.
Each spinner has a background process. On initializing, the spinner view.OnItemSelectedListener is recursively called unnecessarily without any external input to the listener
Class file
public class ClientListAdapter extends BaseAdapter implements SpinnerAdapter {
Context context;
int layoutResourceId;
ArrayList<GetClientListDetail> data = null;
ArrayList<GetClientListDetail> temp = null;
String ID, str;
Typeface typeface;
PopupWindow cp;
private ProgressDialog progressDialog;
String[] Status1 = new String[] { "Waiting", "Away","No Show"};
String[] Status2 = new String[] { "In Service",
"Generate Bill", "Completed" };
SpinnerAdapterlist TherapistAdapter = null;
ArrayAdapter<String> StatusAdapter = null;
ArrayList<GetTherapistProperties> TherapistList ;
private LayoutInflater inflater;
RemoveClient RC;
ChangeStatus CS;
ChangeTherapist CT;
ClientListHolder holder ;
int _therapistID;
GetClientListDetail ap;
GetTherapistProperties tp;
boolean networkavailable=false;
public ClientListAdapter(Context context, int textViewResourceId,
ArrayList<GetClientListDetail> gld, ArrayList<GetTherapistProperties> therapislist) {
super();
this.layoutResourceId = textViewResourceId;
this.context = context;
this.data = gld;
this.mGalleryCount1 = gld.size();
this.mGalleryCount2=gld.size();
this.TherapistList=therapislist;
inflater=LayoutInflater.from(context);
Resources res = context.getResources();
TherapistAdapter = new SpinnerAdapterlist(context,
R.layout.spinnerlayout, TherapistList);
StatusAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_dropdown_item_1line, Status1);
}
#Override
public int getCount() {
return data.size();
}
#Override
public GetClientListDetail getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
holder = new ClientListHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.tv_no = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_no);
holder.tv_name = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_name);
holder.tv_status = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_status);
holder.tv_therapist = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_therapist);
holder.iv_edit=(ImageView) row.findViewById(R.id.btn_clientwaitlayout_edit);
holder.iv_action = (ImageView) row
.findViewById(R.id.btn_clientwaitlayout_action);
holder.tv_unchange_therapist=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_name);
holder.tv_unchange_status=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_status);
row.setTag(holder);
} else {
holder = (ClientListHolder) row.getTag();
}
holder.tv_therapist.setAdapter(TherapistAdapter);
holder.tv_status.setAdapter(StatusAdapter);
ap = data.get(position);
tp=TherapistList.get(position);
holder.tv_name.setText(ap.getCLDName());
holder.tv_no.setText(ap.getCLDNo());
if(ap.getCLDStatus().equals("1") ){
Log.d("LOOP","Sub If condition");
holder.tv_therapist.setVisibility(View.VISIBLE);
holder.tv_status.setVisibility(View.VISIBLE);
holder.tv_unchange_therapist.setVisibility(View.GONE);
holder.tv_unchange_status.setVisibility(View.GONE);
holder.iv_action.setVisibility(View.GONE);
holder.iv_edit.setVisibility(View.VISIBLE);
try {
for(int x=0;x<TherapistList.size();x++){
if(ap.getCLDTherapist().equals(TherapistList.get(x).getID())){
holder.tv_therapist.setSelection(x);
}else{
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
holder.tv_status.setSelection(Integer.parseInt(ap.getCLDStatus()) - 1);
} catch (ArrayIndexOutOfBoundsException e2) {
// TODO Auto-generated catch block
holder.tv_status.setSelection(0);
}
}else if(ap.getCLDStatus().equals("2") | ap.getCLDStatus().equals("6")){
holder.tv_therapist.setVisibility(View.VISIBLE);
holder.tv_status.setVisibility(View.VISIBLE);
holder.tv_unchange_therapist.setVisibility(View.GONE);
holder.tv_unchange_status.setVisibility(View.GONE);
holder.iv_action.setVisibility(View.GONE);
holder.iv_edit.setVisibility(View.GONE);
try {
for(int x=0;x<TherapistList.size();x++){
if(ap.getCLDTherapist().equals(TherapistList.get(x).getID())){
holder.tv_therapist.setSelection(x);
}else{
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(ap.getCLDStatus().equals("2")){
holder.tv_status.setSelection(1);
}else{
holder.tv_status.setSelection(2);
}
} catch (ArrayIndexOutOfBoundsException e2) {
// TODO Auto-generated catch block
holder.tv_status.setSelection(0);
}
}else{
holder.tv_therapist.setVisibility(View.GONE);
holder.tv_status.setVisibility(View.GONE);
holder.tv_unchange_therapist.setVisibility(View.VISIBLE);
holder.tv_unchange_status.setVisibility(View.VISIBLE);
holder.iv_action.setVisibility(View.VISIBLE);
holder.iv_edit.setVisibility(View.GONE);
for(int y=0;y<TherapistList.size();y++){
if(ap.getCLDTherapist().equals(TherapistList.get(y).getID())){
holder.tv_unchange_therapist.setText(TherapistList.get(y).getName());
break;
}else{
holder.tv_unchange_therapist.setText("Not Available");
}
}
if (ap.getCLDStatus().equals("2")) {
holder.tv_unchange_status.setText(Status1[1]);
} else if (ap.getCLDStatus().equals("3")) {
holder.tv_unchange_status.setText(Status2[0]);
} else if (ap.getCLDStatus().equals("4")) {
holder.tv_unchange_status.setText(Status2[1]);
} else if (ap.getCLDStatus().equals("5")) {
holder.tv_unchange_status.setText(Status2[2]);
} else if (ap.getCLDStatus().equals("6")) {
holder.tv_unchange_status.setText(Status1[2]);
}
}
holder.tv_therapist.setTag(ap.getCLDClientID());
holder.tv_status.setTag(ap.getCLDClientID());
holder.iv_edit.setTag(ap.getCLDClientID());
holder.iv_action.setTag(ap.getCLDClientID());
holder.iv_action.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
ImageView b = (ImageView) v;
String id = b.getTag().toString();
Log.d("ID is", id);
Intent CDV=new Intent(context, TabSample.class);
CDV.putExtra("ID", id);
//CDV.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//context.startActivity(CDV);
((Activity) context).startActivityForResult(CDV,5);
try {
Log.d("POSITION", "" + position + " "
+ data.get(position).getCLDClientID());
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
holder.tv_status
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int id=arg2+1;
try {
try {
CS=new ChangeStatus();
CS.setClientID(data.get(position).getCLDClientID());
CS.setSalonID("1");
if(id==3){
CS.setStatus("6");
}else{
CS.setStatus(String.valueOf(id));
}
new LoadChangeStatus().execute();
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
holder.tv_therapist
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
try {
try {
Spinner sp = (Spinner) arg0;
String str = sp.getTag().toString();
TextView th_id=(TextView)arg1.findViewById(R.id.spnradptno);
CT=new ChangeTherapist();
CT.setClientID(str);
CT.setSalonID("1");
CT.setTherapist(th_id.getText().toString());
new LoadChangeTherapist().execute();
Log.d("SPR TXT", th_id.getText().toString()+" "+position+" "+str);
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
Log.d("Error in spinner",e.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Error2 in spinner",e.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.d("Nothing","Selected");
}
});
holder.iv_edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
ImageView b = (ImageView) v;
String id = b.getTag().toString();
Log.d("ID is", id);
Intent CDV=new Intent(context, TabSample.class);
CDV.putExtra("ID", id);
((Activity) context).startActivityForResult(CDV,5);
try {
Log.d("POSITION", "" + position + " "
+ data.get(position).getCLDClientID());
} catch (ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
return row;
}
static class ClientListHolder {
TextView tv_no;
TextView tv_name;
Spinner tv_therapist;
Spinner tv_status;
ImageView iv_action;
ImageView iv_edit;
TextView tv_unchange_therapist;
TextView tv_unchange_status;
}
public class LoadChangeStatus extends AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadChangeStatus= 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
try {
// temp.clear();
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = CS.Change_Status(CS, context);
LoadChangeStatus=1;
}else{
LoadChangeStatus=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ERROR", "LoadChangeStatus backgroung");
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if(LoadChangeStatus==1){
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(LoadChangeStatus==2){
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Changing Status Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
public class LoadChangeTherapist extends
AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadChangeTherapist = 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
try {
// temp.clear();
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = CT.Get_Change_Therapist(CT, context);
LoadChangeTherapist=1;
}else{
LoadChangeTherapist=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("ERROR", "LoadChangeStatus backgroung");
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if (LoadChangeTherapist == 1) {
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (LoadChangeTherapist == 2) {
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Removing Client Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
public class LoadRemoveClient extends AsyncTask<Integer, Integer, Integer> {
// Before running code in the separate thread
int LoadRemoveClient = 0;
#Override
protected void onPreExecute() {
// Create a new progress dialog
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal progress bar
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// Set the dialog title to 'Loading...'
progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'
progressDialog.setMessage("Loading, please wait...");
// This dialog can't be canceled by pressing the back key
progressDialog.setCancelable(false);
// This dialog isn't indeterminate
progressDialog.setIndeterminate(false);
// The maximum number of items is 100
// Set the current progress to zero
// Display the progress dialog
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected Integer doInBackground(Integer... params) {
Log.d("ERROR", "LoadRemoveClient backgroung");
try {
networkavailable=new Network().isNetworkAvailable(context);
if(networkavailable){
temp = RC.Get_Client_List_Detail(RC, context);
LoadRemoveClient=1;
}else{
LoadRemoveClient=2;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
}
// after executing the code in the thread
#Override
protected void onPostExecute(Integer result) {
// close the progress dialog
progressDialog.dismiss();
if (LoadRemoveClient == 1) {
try {
data.clear();
data.addAll(temp);
notifyDataSetChanged();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (LoadRemoveClient == 2) {
Toast.makeText(context, "Network Not Available", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Removing Client Failed. Please Try Again", Toast.LENGTH_LONG).show();
}
}
}
}
How to avoid unnecessarily calling of view.OnItemSelectedListener of spinner view On initializing custom adapter list view
You can't stop or avoid calling of onItemSelectedListener on initialization. But you can prevent this by declare an integer and set value as 0 and while on calling getview method, check the integer with size of data(Your array list size).if the integer is less than the size than increment the integer value else do your background work. But it's not right way to do because when you scroll the listview the same problem rise again. You do this if you have fixed array list size. It is better to use AutoCompleteTextView instead of SpinnerView.
It gets called for the selection of the first item(Kind of default value).
Try one thing don't set adapter to spinner if row!=null for ex:
if (row == null) {
holder = new ClientListHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.tv_no = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_no);
holder.tv_name = (TextView) row
.findViewById(R.id.tv_clientwaitlayout_name);
holder.tv_status = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_status);
holder.tv_therapist = (Spinner) row
.findViewById(R.id.tv_clientwaitlayout_therapist);
holder.iv_edit=(ImageView) row.findViewById(R.id.btn_clientwaitlayout_edit);
holder.iv_action = (ImageView) row
.findViewById(R.id.btn_clientwaitlayout_action);
holder.tv_unchange_therapist=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_name);
holder.tv_unchange_status=(TextView) row.findViewById(R.id.tv_clientwaitlayout_unchange_status);
holder.tv_therapist.setAdapter(TherapistAdapter);
holder.tv_status.setAdapter(StatusAdapter);
row.setTag(holder);
} else {
holder = (ClientListHolder) row.getTag();
}
I am reading lat/lon from file, creating polygon and adding it to the map in AsyncTask. Everything is working fine - except progressDialog allways freezes at start of the action and dismissed after action is completed.This is my code:
UPDATED CODE:
private class shpLoading extends AsyncTask<GoogleMap, List<LatLng>, String> {
private ProgressDialog dialog;
private String path;
private int loaded;
public void setPath(String p){
this.path = p;
}
#Override
protected String doInBackground(GoogleMap... params) {
final ShpReader shpRead = new ShpReader();
try {
shpRead.read(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidShapeFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.setMax(shpRead.daugiakampiai().size());
int i = 0;
for(List<LatLng> a: shpRead.polygons()){
function.arAntLinijos(a);
for(int h = 0; h < a.size()-1; h++){
LatLng point = function.midPoint(a.get(h), a.get(h+1));
a.add(h+1, point);
h++;
if(i > 3000){
message("You reached max count!");
break;
}
}
publishProgress(a);
i++;
}
return "Done";
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(Measuring.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage(getString(R.string.loading));
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.show();
}
}
#Override
protected void onProgressUpdate(List<LatLng>... values) {
dialog.setProgress(loaded++);
Polygon daug = mMap.addPolygon(new PolygonOptions()
.addAll(values[0])
.strokeWidth(1)
.strokeColor(Color.RED)
.fillColor(0x3F00FF00));
plotai.add(new Polygons(db.getMaxFieldID()+1, daug));
daug = null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
Because you should draw your polygons not in onProgressUpdate method, but in doInBackground method. In onProgressUpdate method you have to update progress in your ProgressDialog object (in your code ProgressDialog is showed, but not updated its progress at all).
Hi i want to display progressdialog until a command is executed through telnet.
so i use asynctask for that purpose.
private class AsyncAction extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pd.dismiss();
}
// pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
And i call asynctask in oncreate() like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
The problem is that i could not see progressdialog until command executes.
please help me solve the issue.
Thanks in advance.
EDIT
The code to send and read command
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length()-1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar)
{
if (sb.toString().endsWith(pattern))
{
if (sb.toString().contains("cdkk"))
{
disconnect();
break;
}
else
{
return sb.toString();
}
}
else
{
disconnect();
break;
}
}
else if(sb.toString().contains("Failed"))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String error="Invalid username or password!";
alertbox.setMessage(error);
alertbox.setTitle("Error");
alertbox.show();
System.out.println("bad user name");
disconnect();
break;
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently you are trying to do Network operations from onPostExecute because this method called from UI Thread . change your code as to get work in proper way
private class AsyncAction extends AsyncTask<String, Void, String>
{
public static boolean status=false;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
// make status true or false if command successfully executed
status=true;
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
// check status if true then show AlertDialog
if(status==true){
AlertDialog.Builder alertbox =
new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
else{
// your code here
}
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
You need to show the progress bar in onPreExecute() do the work in doInBackground() and then hide the progress bar in onPostExecute(). onPreExecute() and onPostExecute() are both executed on the main thread, where as doInBackground is executed in the background.
You are doing your work on onPostExecute() method which should be inside doInBackground()
show your progress dialog inside onPreExecute() and dismiss inside onPostExecute().
I am developing an android application where I receive eeg signal from bluetooth and display it in real time using achartengine. I use an async task to display the chart and update it. But, I get ConcurrentModificationException everytime. The graph is displayed for sometime and then it gives that error. Below is my code.
mstart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
// tv.setText("Fetal Heart rate loading..");
// index = 0;
flag = true;
if(fhr_alg!=null)
fhr_alg = null;
fhr_alg = new AddStringTask();
algo_done = false;
/*curr = 5;
counter = 0;*/
//// a1.setFlag(true);
//a1.setMax(0);
Thread tt = new Thread()
{
public void run()
{
try{
sleep(600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
fhr_alg.execute();
}
}
};tt.start();
if (view_eeg1== null) {
LinearLayout layout_eeg1 = (LinearLayout) findViewById(R.id.layout2);
view_eeg1= ChartFactory.getLineChartView(BluetoothConnect.this, eeg1, renderer_eeg1);
// layout_eeg1.
layout_eeg1.addView(view_eeg1);
} else {
view_eeg1.repaint();}
// w1.loadUrl("javascript:callJS()");
mstart.setEnabled(false);
}
});
class AddStringTask extends android.os.AsyncTask<Void, Integer, Integer> {
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
algo_done=true;
//Toast.makeText(Html.this, "Done Algo !", Toast.LENGTH_SHORT).show();
}
#SuppressLint("UseValueOf")
#Override
protected Integer doInBackground(Void... unused) {
try {
for(int r=0;r<=5000;r++){
//Thread.sleep(300);
series1.add(r,data[r]);
// w2.loadUrl("javascript:count(\""+data[r]+"\")");
if(r<=250){
renderer_eeg1.setXAxisMax(250);
}
else if(r>250){
double maxX = series1.getMaxX();
double minX = maxX - 250;
renderer_eeg1.setXAxisMin(minX);
renderer_eeg1.setXAxisMax(maxX);
}
view_eeg1.repaint();
publishProgress((int)data[r]);
SystemClock.sleep(600);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (0);
}
#Override
protected void onProgressUpdate(Integer ... value) {
int fhr=value[0];
view_eeg1.repaint();
w2.loadUrl("javascript:count(\""+fhr+"\")");
//a1.setfhr(curr, fhr);
//curr++;
}
}
can anyone tell me why am I getting this error and how to solve it.
Thanks
problem updating the UI into a Thread that is not an UI Thread so u
have to use a doinbackground as below and remove the code that
modifies the UI in doInbackground