I have made a progressbar in android,Which is horizontal,i want to freeze it when any button click in my activity,I have tried as below,But progress still displays.my code is as below:I want to do something like one question loaded after another,and onClick of any button counter and progress state should be stop,but rite now my timer stop but progress still ran up..it not stops.
code
public class QuestionAnswerActivity extends Activity implements OnClickListener {
// visible gone
ArrayList<HashMap<String, String>> QuestionList;
private int progressStatus = 0;
private Handler handler = new Handler();
Intent i;
private boolean run = true;
/**
* Answer [1=true / 0 =false]
*/
int myans;
String ans;
ProgressDialog pDialog;
TextView text_player_one;
String JsonStr;
ArrayList<HashMap<String, String>> questionList;
ImageView player_one_pic;
int count;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
ImageView answer_right_one;
ProgressBar pg_loading;
private CountDownTimer countDownTimer;
TextView timer_text;
private final long startTime = 8 * 1000;
private final long interval = 1 * 1000;
Button opt_1, opt_2, opt_3, opt_4;
Thread splashThread;
TextView answer_question;
LinearLayout answer_linear_3;
// Response variables...!!
// Single player*************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.question_answer_activity);
init();
}
// ***********************************************************************************************
/**
* Initialise the views
*/
#SuppressWarnings({ "deprecation", "unchecked" })
private void init() {
answer_linear_3 = (LinearLayout) findViewById(R.id.answer_linear_3);
answer_linear_3.setVisibility(View.GONE);
questionList = new ArrayList<HashMap<String, String>>();
answer_question = (TextView) findViewById(R.id.answer_question);
player_one_pic = (ImageView) findViewById(R.id.player_one_pic);
text_player_one = (TextView) findViewById(R.id.text_player_one);
text_player_one.setText(Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_NAME, ""));
pg_loading = (ProgressBar) findViewById(R.id.pg_loading_answer);
timer_text = (TextView) findViewById(R.id.timer_text_loading11);
answer_right_one = (ImageView) findViewById(R.id.answer_right_one);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(QuestionAnswerActivity.this));
options = new DisplayImageOptions.Builder().cacheOnDisc(true)
.displayer(new RoundedBitmapDisplayer((int) 3.5f))
.showStubImage(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher).build();
imageLoader.displayImage(Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_PROFILE_PIC, ""), player_one_pic, options);
opt_1 = (Button) findViewById(R.id.option_1);
opt_2 = (Button) findViewById(R.id.option_2);
opt_3 = (Button) findViewById(R.id.option_3);
opt_4 = (Button) findViewById(R.id.option_4);
count = 0;
questionList = (ArrayList<HashMap<String, String>>) getIntent()
.getSerializableExtra("queList");
System.out.println("::::::::My questions::::::::;+++++++"
+ questionList);
/*
* answer_question.setText(questionList.get(count).get("q_title"));
* opt_1.setText(questionList.get(count).get("opt1"));
* opt_2.setText(questionList.get(count).get("opt2"));
* opt_3.setText(questionList.get(count).get("opt3"));
* opt_4.setText(questionList.get(count).get("ans"));
*/
handler.postDelayed(new ViewUpdater(answer_linear_3), 1000);
answer_question.setText(questionList.get(count).get("q_title"));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
opt_1.setOnClickListener(this);
opt_2.setOnClickListener(this);
opt_3.setOnClickListener(this);
opt_4.setOnClickListener(this);
countDownTimer = new MyCountDownTimer(startTime, interval);
/*
* Initialise NoResponse Timer
*/
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if (run) {
pg_loading.setProgress(progressStatus);
pg_loading.setProgressDrawable(getResources()
.getDrawable(R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
// ***********************************************************************************************
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
run = false;
switch (v.getId()) {
case R.id.option_1:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
/* questionTask(count); */
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_2:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_3:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
break;
case R.id.option_4:
if (count <= 7) {
count++;
progressStatus = pg_loading.getProgress();
new LeaveResponse()
.execute(questionList.get(count).get("q_id"));
}
/*
* answer_question.setText(QuestionList.get(count).get("q_title"));
* opt_1.setText(QuestionList.get(count).get("opt1"));
* opt_2.setText(QuestionList.get(count).get("opt2"));
* opt_3.setText(QuestionList.get(count).get("opt3"));
* opt_4.setText(QuestionList.get(count).get("ans"));
* timer_text.setText(timer_text.getText() +
* String.valueOf(startTime / 1000));
*
* countDownTimer.start();
* answer_right_one.setVisibility(View.VISIBLE);
* pg_loading.setVisibility(View.GONE); countDownTimer.cancel();
*
* Toast.makeText(QuestionAnswerActivity.this,
* timer_text.getText().toString(), 1).show();
*/
break;
}
}
// ***********************************************************************************************
/**
* CountDown Timer for Starting No response activity if user doesnt
* responds.
*/
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
public void onpause() {
// TODO Auto-generated method stub
Toast.makeText(QuestionAnswerActivity.this, "Clicked", 1).show();
}
#Override
public void onFinish() {
Toast.makeText(getApplicationContext(), "onFinish",
Toast.LENGTH_SHORT).show();
/*
* If finish , that is user not responding , go to NoResponse
* screen.
*/
Intent intent = null;
intent = new Intent(QuestionAnswerActivity.this,
NoResponseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
timer_text.setText("" + millisUntilFinished / 1000);
}
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
void questionTask(int count) throws InterruptedException {
if (count < 8) {
answer_linear_3.setVisibility(View.GONE);
answer_question.setText(questionList.get(count).get("q_title"));
handler.postDelayed(new ViewUpdater(answer_linear_3), 100);
myans = randomGenerator();
System.out.println(":::::::::::::;randomized answer::::::::::::;;;"
+ myans);
if (myans == 1) {
opt_1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("ans"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("opt1"));
} else if (myans == 2) {
opt_2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt2"));
opt_2.setText(questionList.get(count).get("ans"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
} else if (myans == 3) {
opt_3.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("ans"));
opt_4.setText(questionList.get(count).get("opt3"));
} else {
opt_4.setBackgroundDrawable(getResources().getDrawable(
R.drawable.true_selector));
opt_1.setText(questionList.get(count).get("opt1"));
opt_2.setText(questionList.get(count).get("opt2"));
opt_3.setText(questionList.get(count).get("opt3"));
opt_4.setText(questionList.get(count).get("ans"));
}
countDownTimer = new MyCountDownTimer(startTime, interval);
/*
* Initialise NoResponse Timer
*/
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
}
}
private class ViewUpdater implements Runnable {
private LinearLayout mView;
public ViewUpdater(LinearLayout linView) {
mView = linView;
}
#Override
public void run() {
mView.setVisibility(View.VISIBLE);
}
}
// Answer webservice call..!
private class LeaveResponse extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
countDownTimer.cancel();
pDialog = new ProgressDialog(QuestionAnswerActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
BackendAPIService sh = new BackendAPIService();
String ResponseURL = Const.API_RESPONSE
+ "?os=droid&user_id="
+ Pref.getValue(QuestionAnswerActivity.this,
Const.PREF_USER_ID, "") + "&myrole="
+ Const.MY_ROLL + "&q_id=" + params[0] + "&ans=" + ans
+ "&time=5&game_id=" + Const.GAME_ID + "";
JsonStr = sh.makeServiceCall(ResponseURL, BackendAPIService.GET);
System.out.println("::::::::::::;My Response request::::::::::;;;"
+ ResponseURL);
Log.d("Response: ", "> " + JsonStr);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
countDownTimer.cancel();
pg_loading.setProgress(0);
progressStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if (run) {
pg_loading.setProgress(progressStatus);
pg_loading
.setProgressDrawable(getResources()
.getDrawable(
R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
questionTask(count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int randomGenerator() {
Random r = new Random();
int ans = r.nextInt(4 - 1) + 1;
return ans;
}
}
You can easily hold some boolean variable for that case:
private boolean run = true;
then gather all the Buttons onClickListeners in one click listener, like the main one of the class, and upon anyclick make that variable run=false, So, check that before set the progress:
if(run){
pg_loading.setProgress(progressStatus);
}else{
//stop, finish, do whatever you want
}
in onClick listener:
public void onClick(View v) {
// TODO Auto-generated method stub
run = false;
Intent i;
switch (v.getId()) {
.
.
.
}
UPDATE:
make the thread as the following:
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
if(run){
pg_loading.setProgress(progressStatus);
pg_loading.setProgressDrawable(getResources()
.getDrawable(R.drawable.progress));
}
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
UPDATE 2:
your onPostExcute in the AsyncTask must be:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
try {
countDownTimer.cancel();
pg_loading.setProgress(0);
progressStatus = 0;
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
pg_loading.setProgress(progressStatus);
pg_loading
.setProgressDrawable(getResources()
.getDrawable(
R.drawable.progress));
}
});
Related
Hi in the below downloading images for showing progessbar to 100 but completeld 100% images are not showing still downloading and not showing .i want after 100% i want to move to activity.
But it's taking time to move next activity.
java
public class DownloadTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
final DialogProgressBarRunnable progressDialog =
new DialogProgressBarRunnable(getActivity(), false, 2);
progressDialog.show();
// the dialog box shouldn't get cancelled when clicking outside it or pressing back button.
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
// pd.setMessage("Downloading catalogue images.");
// pd.show();
}
protected String doInBackground(Void... Params) {
parsingObject = new ParsingForFinalImages(catid, responseJson);
/* ConnectionDetector cd = new ConnectionDetector(getActivity().getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent==true)
{
}
*/
// put your code here
// JSON parsing begins here via the parsing class
// Put this code in async task
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// pd.hide();
// pd.dismiss();
Intent intent = new Intent(getActivity(), ImageGallery.class);
startActivity(intent);
}
}
private class DialogProgressBarRunnable extends ProgressDialog implements
Runnable {
private boolean showSecondary;
private int incrementAfter;
public DialogProgressBarRunnable(Context context,
boolean showSecondary, int incrementAfter) {
super(context);
setCancelable(true);
setMessage(getString(R.string.download_message));
setSecondaryProgress(0);
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
setMax(100);
setProgress(0);
this.showSecondary = showSecondary;
this.incrementAfter = incrementAfter;
}
#Override
public void show() {
super.show();
new Thread(this).start();
}
#Override
public void run() {
while (progress < 100) {
progress++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// increment the first/second progress bar after every %
progressBar();
}
}
private void progressBar() {
if (progress % incrementAfter == 0) {
progressFirstBar();
}
if (showSecondary) {
progressSecondaryBar();
}
}
private void progressSecondaryBar() {
while (secondaryProgress < 100) {
secondaryProgress++;
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
setSecondaryProgress(secondaryProgress);
}
});
}
}
private void progressFirstBar() {
secondaryProgress = 0;
handler.post(new Runnable() {
#Override
public void run() {
setProgress(progress);
if (progress == 100) {
dismiss();
}
}
});
}
}
class DownloadFileFromURL extends AsyncTask {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
// Declear Variables
int count;
try {
URL url1 = new URL(url);
URLConnection conection = url1.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url1.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString() + "/Report.xls");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
Log.d("Downloding"+data,"Count"+count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String reString) {
// dismiss the dialog after the file was downloaded
super.onPostExecute(null);;
dismissDialog(progress_bar_type);
Log.d("Download","Completed");
Intent intent1=new Intent(DownloadExcle.this,MainActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
}
I am developing multiple file download app. in which, if switch is on then downloading is start and if switch is off then downloading is cancel. I am updating item value using timertask with handler. below is my code of adapter. everything is working fine but when I am scrolling listview, item value (percentage count) are conflict with other values which are other file downloaded progress.
Code:
public class DownloadAdapter extends ArrayAdapter<AudioSubModel> {
private static final String PDF_MIME_TYPE = "application/pdf";
private LayoutInflater lf;
Context mContext;
private List<ListContent> lstHolders;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
for (ListContent holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
AudioSubModel getAlarm(int position){
return ((AudioSubModel) getItem(position));
}
public DownloadAdapter(Context context, int resource, List<AudioSubModel> objects) {
super(context, resource, objects);
lf = LayoutInflater.from(context);
lstHolders = new ArrayList<ListContent>();
mContext = context;
Log.e("ADAPTER", "CONSTR");
startUpdateTimer();
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ListContent holder = null;
if (view == null) {
view = lf.inflate(R.layout.row_audio_desc_layout, null);
holder = new ListContent();
holder.ivImg = (CircleImageView)view.findViewById(R.id.row_audio_desc_ivImg);
holder.tvTitle = (TextView) view
.findViewById(R.id.row_audio_desc_tvTitle);
holder.tvDesc = (TextView) view
.findViewById(R.id.row_audio_desc_tvDesc);
holder.llDownload = (LinearLayout)view.findViewById(R.id.row_audio_desc_llDownload);
holder.PBDownload = (RoundCornerProgressBar)view.findViewById(R.id.row_audio_desc_PBDownload);
holder.tvReadPdf = (TextView)view.findViewById(R.id.row_audio_desc_tvReadPdf);
holder.tvMakeOffline = (TextView)view.findViewById(R.id.row_audio_desc_tvMakeOffline);
holder.swtchDownload = (Switch)view.findViewById(R.id.row_audio_desc_swtchDownloadOn);
holder.tvDownload = (TextView)view.findViewById(R.id.row_audio_desc_tvDownload);
holder.tvDownloadPercent = (TextView)view.findViewById(R.id.row_audio_desc_tvDownloadPercent);
holder.ivCancel = (ImageView)view.findViewById(R.id.row_audio_desc_ivCancel);
holder.ivPlay = (ImageView)view.findViewById(R.id.row_audio_desc_ivPlay);
holder.tvTitle.setTypeface(MyApplication.app_bold);
holder.tvDesc.setTypeface(MyApplication.app_light);
holder.tvReadPdf.setTypeface(MyApplication.app_bold);
holder.tvMakeOffline.setTypeface(MyApplication.app_bold);
holder.swtchDownload.setTypeface(MyApplication.app_bold);
holder.tvDownload.setTypeface(MyApplication.app_bold);
holder.tvDownloadPercent.setTypeface(MyApplication.app_bold);
view.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ListContent) view.getTag();
}
holder.setData(getAlarm(position));
// convertView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// ((MainActivity)mContext).ItemClickFetch(getItem(position).getId());
// }
// });
return view;
}
class ListContent {
LinearLayout llDownload;
RoundCornerProgressBar PBDownload;
CircleImageView ivImg;
ImageView ivCancel, ivPlay;
TextView tvTitle, tvDesc, tvReadPdf, tvMakeOffline, tvDownload, tvDownloadPercent;
Switch swtchDownload;
private AudioSubModel aItem;
DownloadFileFromURL dwnldFileUrl;
public void setData(AudioSubModel item) {
aItem = item;
dwnldFileUrl = new DownloadFileFromURL();
if(item.isPlaying()){
ivPlay.setImageResource(R.drawable.pausebtn);
}else{
ivPlay.setImageResource(R.drawable.playbtn);
}
if(aItem.isDownloading()){
swtchDownload.setOnCheckedChangeListener(null);
swtchDownload.setChecked(true);
tvDownloadPercent.setText(aItem.getPercent() + "");
}else{
swtchDownload.setOnCheckedChangeListener(null);
swtchDownload.setChecked(false);
tvDownloadPercent.setText("0");
}
// holder.tvDownloadPercent.setText(data.get(position).getPercent()+" %");
tvDownload.setText(aItem.getDwnLbl());
tvTitle.setText(aItem.getTitle());
tvDesc.setText(aItem.getDesc());
Bitmap bmp = BitmapFactory.decodeFile(aItem.getImage());
ivImg.setImageBitmap(bmp);
// Log.e("MAIN", "IS DONE: " + aItem.isOn());
tvReadPdf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isPDFSupported(mContext)){
Uri path = Uri.fromFile(new File(aItem.getPdf()));
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(objIntent);
}else{
if(GeneralClass.getConnectivityStatusString(mContext)){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://docs.google.com/gview?embedded=true&url="+aItem.getPdfurl()));
mContext.startActivity(browserIntent);
}else{
GeneralClass.showToast("Check internet connection to view pdf file", mContext);
}
}
}
});
ivPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(aItem.isPlaying()){
aItem.setPlaying(false);
((MainActivity)mContext).stopAudioFile();
}else{
aItem.setPlaying(true);
((MainActivity)mContext).playAudioFile(aItem);
}
}
});
swtchDownload.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// updateView(position, arg1);
Log.e("Audio ADAPTER", "file: " + arg1);
if(arg1){
aItem.setDownloading(true);
aItem.setDwnLbl("Downloading");
dwnldFileUrl.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, aItem.getAudiourl());
}else if(!arg1){
aItem.setDownloading(false);
aItem.setDwnLbl("Download");
dwnldFileUrl.cancel(true);
}
}
});
ivCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
aItem.setDownloading(false);
aItem.setDwnLbl("Download");
dwnldFileUrl.cancel(true);
// updateView(position, false);
// new DownloadFileFromURL(holder, position).execute(data.get(position).getAudiourl());
}
});
updateTimeRemaining();
}
public void updateTimeRemaining() {
// Log.e("MAIN", "GET TIME: " + aItem.getTimeStamp());
if(aItem.isDownloading()){
llDownload.setVisibility(View.VISIBLE);
tvDownloadPercent.setVisibility(View.VISIBLE);
tvDownloadPercent.setText(aItem.getPercent()+"");
// PBDownload.setProgress(aItem.getPercent());
tvDownload.setText(aItem.getDwnLbl());
}else{
llDownload.setVisibility(View.INVISIBLE);
tvDownloadPercent.setVisibility(View.INVISIBLE);
tvDownloadPercent.setText("0");
// PBDownload.setProgress(0);
tvDownload.setText(aItem.getDwnLbl());
}
// if(aItem.isOn()){
// tvTitle.setText(aItem.getPercent()+"");
// }else{
// tvTitle.setText("0");
// }
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private volatile boolean running = true;
String finalFilePath="";
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
// URL url = new URL(f_url[0]);
URL url = new URL("http://www.robtowns.com/music/blind_willie.mp3");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String outputFile = extStorageDirectory+"/"+GeneralClass.FILE_PATH;
finalFilePath = outputFile+"/audio"+aItem.getId()+".mp3";
OutputStream output = new FileOutputStream(finalFilePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1 && running) {
if(isCancelled()){
Log.e("ADAPTER", "Async break");
break;
}
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onCancelled() {
running = false;
Log.e("ADAPTER", "Async cancelled");
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
aItem.setPercent(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
Log.e("ADAPTER", "DONE ID: " + aItem.getId());
((MainActivity)mContext).updateAudioFileDownload(aItem.getId(), finalFilePath);
ivCancel.setVisibility(View.INVISIBLE);
}
}
}
public static boolean isPDFSupported(Context context) {
Intent i = new Intent( Intent.ACTION_VIEW );
final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}
}
Help me with this major issue.
I have a question about the progress bar. There is activity with question and answers. When user click on one of those answers. activity calls itself and generate new question with answers. In the header, I have progress bar, and the progress bar is full for N seconds. Every time the activity calls itself, the progress bar is full for N/2 seconds. I want to the progress bar to be full for N seconds, not for N/2. If you can help me, I'd be grateful. Problem is in the curiProgress function. Here is my code.
{
public class beze2 extends Activity{
String FILENAME = "HighScore";
FileOutputStream fos;
private boolean tocan = false;
private int c, progressStatus=400, id_odgovor, rezultat;
private myCountDownTimer timer;
private static int myProgress=400;
private ProgressBar progressBar;
private Handler myHandler=new Handler();
private TextView text, t;
private int[] b;
private String d, f, strin;
private ArrayList numbers;
private ArrayList<Pitanja> pitanja;
private ArrayList<Odgovor> odgovori;
private TestAdapter mDbHelper;
private Random r;
private LinearLayout ln;
LinearLayout.LayoutParams buttonParams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getIntents();
initializeVariables();
dodajVrijednostiUb();
postaviPitanje();
postaviOdgovore();
curiProgress();
}
private void getIntents(){
Intent i = getIntent();
String reza = i.getStringExtra("REZULTAT");
strin = i.getStringExtra("EXTRA_M");
rezultat = Integer.parseInt(reza);
}
private void initializeVariables(){
progressBar=(ProgressBar)findViewById(R.id.myProgress);
text = (TextView) findViewById(R.id.vrijeme);
timer = new myCountDownTimer(20*1000,1*1000);
numbers = new ArrayList();
mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
pitanja = mDbHelper.getPitanje(Integer.parseInt(strin));
b = new int[pitanja.size()];
t = (TextView) findViewById(R.id.text_pitanja);
myProgress=400;
r = new Random();
progressBar.setMax(400);
ln = (LinearLayout) findViewById(R.id.layoutOdgovori);
buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
private void curiProgress(){
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(progressStatus>=0)
{
progressStatus=performTask();
myHandler.post(new Runnable()
{
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
myHandler.post(new Runnable() {
#Override
public void run() {
progressStatus=0;
myProgress=0;
}
});
}
private int performTask()
{
try {
//---Do some task---
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return --myProgress;
}
}).start();
}
private void dodajVrijednostiUb(){
for (int z=0;z<pitanja.size(); z++){
b[z] = pitanja.get(z).getId_pitanja();
numbers.add(b[z]);
}
}
private void postaviPitanje(){
while (!numbers.contains(c)){
c = r.nextInt(22) + 1;
}
for (int i=0;i<pitanja.size(); i++){
if (c==b[i]){
d = pitanja.get(i).getTekst_pitanja();
id_odgovor = pitanja.get(i).getOdgovor();
}
}
t.setText(d);
}
private void postaviOdgovore(){
odgovori = mDbHelper.getOdgovor(c);
for (int i = 0; i<odgovori.size(); i++){
final Button bt = new Button(this);
bt.setId(odgovori.get(i).getId_odgovor());
bt.setBackgroundResource(getResources().getIdentifier("buttoni", "drawable", getPackageName()));
final String text = odgovori.get(i).getOdgovor();
int l = odgovori.get(i).getId_odgovor();
final String s = Integer.toString(l);
bt.setText(text);
buttonParams.setMargins(20, 5, 20, 5);
bt.setLayoutParams(buttonParams);
ln.addView(bt);
bt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
f = Integer.toString(id_odgovor);
if (f.equals(s)){
tocan = true;
bt.setTextColor(Color.GREEN);
} else {
tocan = false;
bt.setTextColor(Color.RED);
Button newbutton = (Button) findViewById(id_odgovor);
newbutton.setTextColor(Color.GREEN);
}
timer.cancel();
if (tocan){
rezultat++;
timer.cancel();
Toast.makeText(beze2.this, "Tocan odgovor, vas score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), beze2.class);
i.putExtra("REZULTAT", Integer.toString(rezultat));
i.putExtra("EXTRA_M", strin);
startActivity(i);
}
else {
Toast.makeText(beze2.this, "Netocan odgovor, vas konacni score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
upisiDatoteku("Guest", rezultat);
Intent i = new Intent(beze2.this, MainActivity.class);
startActivity(i);
}
}
}
});
}
timer.start();
}
private void upisiDatoteku(String s, int rez){
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
String newOne = s + "\t" + Integer.toString(rez);
fos.write(newOne.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class myCountDownTimer extends CountDownTimer{
public myCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
text.setText("Time's up");
myHandler.post(new Runnable(){
#Override
public void run() {
try {
Thread.sleep(3000);
Intent i = new Intent(beze2.this, beze.class);
startActivity(i);
Toast.makeText(beze2.this, "Isteklo vam je vrijeme, Vas score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
upisiDatoteku("Guest",rezultat);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onTick(long millisUntilFinished) {
int i = (int) millisUntilFinished / 1000;
text.setText(Integer.toString(i));
}
}
I am writing a code in which I need to move all file and folders to the sdcard. I used Async task for this purpose. During this activity I am showing a progressbar with percentage on my screen instead of just showing me the "Loading..." popup. But it does not meet my requirement.
public class syncMgr extends AsyncTask<String, Long, String> {
public LoginActivity activity;
public Context context;
syncMgr(LoginActivity activity1,Context c)
{
activity = activity1;
context=c;
}
//public ProgressDialog progress;
protected void onPreExecute() {
super.onPreExecute();
activity.progress = ProgressDialog.show(context,"","Files Downloading, Please Wait...",true);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
copyFilesToSdCard();
return null;
}
private void copyFilesToSdCard() {
copyFileOrDir("");
}
private void copyFileOrDir(String path) {
AssetManager assetManager = activity.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() " + path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
publishProgress((int) ((i / (float) 658) * 100));
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
copyFileOrDir(p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void publishProgress(int i) {
// TODO Auto-generated method stub
activity.progress.setProgress(i);
}
#Override
protected void onProgressUpdate(Long... values) {
activity.progress.setProgress(values[0].intValue());
}
#Override
protected void onPostExecute(String result) {
activity.progress.dismiss();
super.onPostExecute(result);
//return "asdas";
//return result;
}
}
Here is my Activity Class Code...
ProgressDialog progress;
public static final int progress_bar_type = 0;
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
progress = new ProgressDialog(this);
progress.setMessage("Downloading file. Please wait...");
progress.setIndeterminate(false);
progress.setMax(100);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setCancelable(true);
progress.show();
return progress;
default:
return null;
}
}
Have you tried putting the asyncTask initiation code into a worker thread like this?
// set progressBar .VISIBLE first
// then...
new Thread(new Runnable() {
public void run() {
// webview initiation code
}
}).start();
I turn on progressBar visibility beforehand and not in onPreExecute().
Here is how it solved my own problem & here are the docs.
I have a horizontal progress bar in android. I need to make it complete in 60 seconds.
Why doesn't the below code work?
int progress = 0;
progressBarHorizontal.setMax(60);
while(progress < 60) {
progressHandler.postDelayed((new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
}),progress * 1000);
progress++;
}
Please suggest some other methods. I tried this:
new Thread(new Runnable() {
int progress = 0;
public void run() {
long timerEnd = System.currentTimeMillis() + 60 * 1000;
while (timerEnd > System.currentTimeMillis() ) {
progress = (int) (timerEnd - System.currentTimeMillis()) / 1000;
// Update the progress bar
progressHandler.post(new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.w("tag","Progress thread cannot sleep");
}
}
}
}).start();
But it is not working either.
The second piece of code actually works, the problem was with my logic.
you can try the CountDownTimer :
pd = ProgressDialog.show(MovementEntry.this, "", "Please Wait...",
true, false);
pd.show();
new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
//this will be done every 1000 milliseconds ( 1 seconds )
int progress = (60000 - millisUntilFinished) / 1000;
pd.setProgress(progress);
}
#Override
public void onFinish() {
//the progressBar will be invisible after 60 000 miliseconds ( 1 minute)
pd.dismiss();
}
}.start();
This one will update the statusbar until it reaches its maximum value:
private int progress = 0;
private final int pBarMax = 60;
...
final ProgressBar pBar = (ProgressBar) findViewById(R.id.progressBar1);
pBar.setMax(pBarMax);
final Thread pBarThread = new Thread() {
#Override
public void run() {
try {
while(progress<=pBarMax) {
pBar.setProgress(progress);
sleep(1000);
++progress;
}
}
catch(InterruptedException e) {
}
}
};
pBarThread.start();
You can try this code for that:
Thread timer = new Thread(){
public void run(){
try{
sleep(10000);
while(progressBarStatus < 10000){
StartPoint.this.runOnUIThread(new Runnable(){
public void run()
{
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
});
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
}
}
};
timer.start();
This code works for me
new Thread(new Runnable() {
public void run() {
long timerEnd = System.currentTimeMillis() + 60 * 1000;
while (timerEnd > System.currentTimeMillis()) {
progress = 60 - (int) (timerEnd - System.currentTimeMillis()) / 1000;
// Update the progress bar
progressHandler.post(new Runnable() {
public void run() {
progressBarHorizontal.setProgress(progress);
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.w("App","Progress thread cannot sleep");
}
}
progressHandler.post(new Runnable() {
public void run() {
okButton.performClick();
}
});
}
}).start();