Android IllegalArgumentException for dismissDialog - android

I have used following code for download some files from our internet.
public class SplashDownload extends Activity {
public static final int PROGRESS_DIALOG = 0;
private ProgressDialog mProgressDialog;
private WordDataHelper wordDataHelper;
private ExtraDataHelper extraDataHelper;
// put your file path here
private String filePath = "http://test.com/Assets/";
// put your filename here
private String fileName;
// put your download directory name here
private String downloadDir;
private int wordCounter = 0, extraCounter = 0, counter = 1;
private boolean wordDLOn = true;
private int totalFileNo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashdllayout);
getDownloadList();
}
private void goForward() {
Intent intent = new Intent().setClass(this, LangH.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
private void doNext() {
if (wordDLOn) {
System.out.print("wordDetails update: "
+ wordDetails[wordCounter - 1][0]
+ extraDetails[extraCounter][0] + fileName);
wordDataHelper.updateDLStat(Long
.valueOf(wordDetails[wordCounter - 1][0]));
} else {
System.out.print("extraDetails update: "
+ extraDetails[extraCounter - 1][0] + fileName);
extraDataHelper.updateDLStat(Long
.valueOf(extraDetails[extraCounter - 1][0]));
}
if (wordCounter < wordDetails.length) {
System.out.print("wordCounter: " + wordCounter + "/"
+ wordDetails.length);
startDownload(wordDetails[wordCounter][1]);
wordCounter++;
} else if (extraCounter < extraDetails.length) {
wordDLOn = false;
downloadDir = "LanH/extras";
System.out.print("extraCounter: " + extraCounter + "/"
+ extraDetails.length);
startDownload(extraDetails[extraCounter][1]);
extraCounter++;
} else {
goForward();
}
}
private void getDownloadList() {
// lessons download..........
String[] wordDetails = {"1.mp4","2.mp4","3.mp4","4.mp4","5.mp4","6.mp4","7.mp4","8.mp4",};
downloadDir = "LanH/words";
String[] extraDetails = {"a.mp4","b.mp4","c.mp4","d.mp4","e.mp4","f.mp4","g.mp4","h.mp4",};
totalFileNo = extraDetails.length + wordDetails.length;
if (wordDetails.length != 0) {
startDownload(wordDetails[wordCounter]);
wordCounter++;
} else if (extraDetails.length != 0) {
wordDLOn = false;
startDownload(extraDetails[extraCounter]);
extraCounter++;
} else {
goForward();
}
}
private void startDownload(String dlFilename) {
// tv = (TextView) findViewById(R.id.tv1);
fileName = dlFilename;
System.out.print("fileName: " + fileName);
File dir = new File(android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/"
+ downloadDir);
// creates the directory if it doesn't exists
if (dir.exists() == false) {
dir.mkdirs();
}
dir = null;
if (checkNet()) {
if (checkExternalMedia() == true) {
String url = filePath + fileName;
new DownloadFileAsync().execute(url, fileName);
mProgressDialog.setMessage("Downloading file.." + fileName);
} else {
Toast.makeText(getApplicationContext(),
"External Media is NOT readable/writable",
Toast.LENGTH_SHORT).show();
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No Internet Connectivity. Check the connection and retry the app.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
/** Method to check whether external media available and writable. */
private boolean checkExternalMedia() {
boolean stat;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
stat = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
stat = false;
} else {
// Can't read or write
stat = false;
}
return stat;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file.." + fileName);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(PROGRESS_DIALOG);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("DOWNLOAD_TEST", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
android.os.Environment.getExternalStorageDirectory()
+ "/" + downloadDir + "/" + aurl[1]);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("DOWNLOAD_TEST", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(PROGRESS_DIALOG);
// tv.append("\n\nFile Download Complete!");
// Button btn = (Button) findViewById(R.id.btn1);
// btn.setVisibility(View.GONE);
// you can call a second intent here to redirect to another screen
doNext();
}
}
private boolean checkNet() {
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// we are connected to a network
connected = true;
} else
connected = false;
return connected;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
The process is running fine. It is reported following crash report:
java.lang.IllegalArgumentException: no dialog with id 0 was ever shown via Activity#showDialog
at android.app.Activity.missingDialog(Activity.java:2663)
at android.app.Activity.dismissDialog(Activity.java:2648)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:264)
at com.langhost.main.SplashDownload$DownloadFileAsync.onPostExecute(SplashDownload.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:417)
at android.os.AsyncTask.access$300(AsyncTask.java:127)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5068)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
What is the problem in my code? Is isShowing() check before dismissDialog will solve the prob?

Does your progress dialog actually show up?
Instead of dismissing it you could try using removeDialog(PROGRESS_DIALOG); to have it cleaned up.

See if this thread helps - AlerDialog is not created - java.lang.IllegalArgumentException: Activity#onCreateDialog did not create a dialog for id X

When you do the
mProgressDialog.show();
during
protected Dialog onCreateDialog(int id)
you already set the ID for the Dialog to some random or null value.
So when you call to dismiss it, the Application thinks you are crazy.

Related

android app install programmatically targetSDK 24 , compileSDK 28 , minSDK 19

I have implemented autoUpdate functionality which downloads the new app if update available and removes the old app and installs a new app. but After target SDK 24 or updating Phone os above API Level 2 this functionality not working Whenever I install it shows package parsing error. because of an old app is already there and we are trying to install a new app.
public class UpdateActivity extends AppCompatActivity implements
AppConstants {
public static final String TAG = UpdateActivity.class.getSimpleName();
private String appName = "demo.apk";
private int UNINSTALL_REQUEST_CODE = 1;
private final Handler mHideHandler = new Handler();
private View mContentView;
private BiColoredProgress numberProgressBar;
private Runnable backgroundRunnable;
private Runnable finishRunnable;
private Handler handler;
private static final int INSTALL = 1;
private static final int DOWNLOAD = 0;
private static int flag = 0;
private String updateUrl = "";
private class BackgroundDownloadRunnable implements Runnable {
BackgroundDownloadRunnable() {
}
public void run() {
DownloadFileFromURL d = new DownloadFileFromURL();
d.execute();
return;
}
}
private class FinishDownloadRunnable implements Runnable {
FinishDownloadRunnable() {
}
public void run() {
uninstallApp();
}
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
flag = getIntent().getIntExtra("flag", 0);
updateUrl = getIntent().getStringExtra("updateUrl");
StrictMode.setThreadPolicy(new
StrictMode.ThreadPolicy.Builder().permitAll().build());
handler = new Handler();
mContentView = findViewById(R.id.fullscreen_content);
mHideHandler.post(mHidePart2Runnable);
finishRunnable = new BackgroundDownloadRunnable();
backgroundRunnable = new FinishDownloadRunnable();
numberProgressBar = findViewById(R.id.numberbar8);
try {
if (flag == DOWNLOAD) {
DownloadFileFromURL d = new DownloadFileFromURL();
d.execute();
flag = 1;
} else if (flag == INSTALL) {
installApp();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class DownloadFileFromURL extends AsyncTask<String, Integer,
String> {
DownloadFileFromURL() {
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... f_url) {
try {
HttpURLConnection c = (HttpURLConnection) new
URL(updateUrl).openConnection();
c.setRequestMethod("POST");
c.setDoOutput(false);
c.connect();
int lengthOfFile = c.getContentLength();
File file = new
File(Environment.getExternalStorageDirectory().getPath() + "/Download/");
file.mkdirs();
File outputFile = new File(file, appName);
if (outputFile.exists()) {
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] data = new
byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
long total1 = 0;
while (true) {
int count = is.read(data);
if (count == -1) {
break;
}
total1 += (long) count;
Integer[] strArr = new Integer[1];
strArr[0] = DOWNLOAD_COUNT + ((int) ((100 * total1) /
((long) lengthOfFile)));
publishProgress(strArr);
fos.write(data, 0, count);
}
fos.close();
is.close();
installApp();
new Thread(backgroundRunnable, "VersionChecker").start();
//uninstallApp();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
try {
if (progress[0] > 0 && progress[0] <= 20) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#d63232"));
}
if (progress[0] > 20 && progress[0] <= 40) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#F1E84B"));
}
if (progress[0] > 40 && progress[0] <= 60) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#2CACE3"));
}
if (progress[0] > 60 && progress[0] <= 80) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#4CBB17"));
}
if (progress[0] > 80 && progress[0] <= 100) {
numberProgressBar.setProgress(progress[0]);
numberProgressBar.setColor(Color.parseColor("#39FF14"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onPostExecute(String file_url) {
numberProgressBar.setVisibility(View.GONE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == this.UNINSTALL_REQUEST_CODE && resultCode != -1) {
if (resultCode == 0) {
super.onBackPressed();
startActivity(intent);
} else if (resultCode == 1) {
super.onBackPressed();
}
}
}
private void uninstallApp() {
Intent intentDEl = new Intent("android.intent.action.DELETE");
intentDEl.setData(Uri.parse("package:com.demo"));
startActivityForResult(intentDEl, UNINSTALL_REQUEST_CODE);
}
private void installApp() {
File apkFile = new
File(Environment.getExternalStorageDirectory().getPath() + "/Download/",
appName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}

Textview value changes during scroll in listview android

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.

Download service and update another activity

I have three activities: MainActivity, DownloadServiceTest, ViewDetailDownload. Now, i want download files using Service (IntentService).
Corporeality :
MainActivity have buttons. When i click button_1 it to start a service (DownloadServiceTestextends IntentSerive ) perform download and I want when click button_2 it will startup ViewDetailDownload and update progress.
But when i start ViewDetailDownload i don't receive data(percent download, speed ) from DownloadServiceTest
My code here.
class MainActivity :
public class MainActivity extends Activity implements OnClickListener {
private final String LINK_MP3 = "http://data.chiasenhac.com/downloads/1471/5/1470643-c6ef1a26/320/Vo%20Hinh%20Trong%20Tim%20Em%20-%20Mr%20Siro%20%5BMP3%20320kbps%5D.mp3";
Activity activity;
Button btnDownload_1, btnDownload_2, btnDownload_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_control);
activity = MainActivity.this;
btnDownload_1 = (Button) findViewById(R.id.btn_startdownload_1);
btnDownload_2 = (Button) findViewById(R.id.btn_startdownload_2);
btnDownload_3 = (Button) findViewById(R.id.btn_startdownload_3);
btnDownload_1.setOnClickListener(this);
btnDownload_2.setOnClickListener(this);
btnDownload_3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_startdownload_1) {
Intent intent = new Intent(activity, DownloadServiceTest.class);
intent.putExtra(DownloadServiceTest.REQUEST_STRING, LINK_MP3);
startService(intent);
}
if (v.getId() == R.id.btn_startdownload_2) {
Intent intent = new Intent(MainActivity.this,
ViewDetailDownload.class);
startActivity(intent);
}
}
}
class DownloadServiceTest :
public class DownloadServiceTest extends IntentService {
public static final String REQUEST_STRING = "REQUEST_LINK";
public static final String PROGRESS_UPDATE_ACTION = DownloadServiceTest.class
.getName() + ".progress_update";
private LocalBroadcastManager mLocalBroadcastManager;
private String mUrl_mp3;
public DownloadServiceTest(String name) {
super(name);
}
public DownloadServiceTest() {
super("DownloadService");
}
#Override
public void onCreate() {
mLocalBroadcastManager = LocalBroadcastManager
.getInstance(DownloadServiceTest.this);
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onHandleIntent(Intent intent) {
mUrl_mp3 = intent.getStringExtra(REQUEST_STRING);
DownloadTask task = new DownloadTask();
if (mUrl_mp3 != null) {
task.execute(mUrl_mp3);
}
}
private void onProgressUpdateReceiver(int progress, int speed) {
Intent intent = new Intent();
intent.setAction(PROGRESS_UPDATE_ACTION);
intent.putExtra("progress", progress);
intent.putExtra("speed", speed);
Log.i("", "abc onProgressUpdateReceiver progress "+progress);
Log.i("", "abc onProgressUpdateReceiver speed "+speed);
mLocalBroadcastManager.sendBroadcast(intent);
}
private class DownloadTask extends AsyncTask<String, Void, Void> {
String filename;
int mProgress;
int mSpeed;
private int checkExist;
File SDCardRoot;
private FileOutputStream fileOut;
private InputStream fileIn;
File file;
#Override
protected void onPreExecute() {
filename = mUrl_mp3.substring(mUrl_mp3.lastIndexOf("/") + 1);
try {
filename = URLDecoder.decode(filename, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
int contentLengh = 0;
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
if (HttpURLConnection.HTTP_OK == urlConnection
.getResponseCode()) {
contentLengh = urlConnection.getContentLength();
Log.i("", "abc " + contentLengh);
fileIn = urlConnection.getInputStream();
SDCardRoot = Environment.getExternalStorageDirectory();
file = new File(Environment.getExternalStorageDirectory()
+ "/Blog Radio");
boolean success = true;
if (!file.exists()) {
success = file.mkdir();
}
String getTypeFile = filename.substring(filename
.indexOf("."));
if (success) {
file = new File(SDCardRoot.getAbsolutePath()
+ "/Blog Radio/" + filename);
if (file.exists()) {
checkExist++;
String PATH = Environment
.getExternalStorageDirectory()
+ "/Blog Radio/"
+ filename.replace(filename
.substring(filename.indexOf(".")),
"")
+ "_"
+ checkExist
+ getTypeFile;
file = new File(PATH);
}
} else {
file = new File(SDCardRoot.getAbsolutePath()
+ "/Blog Radio/" + filename);
if (file.exists()) {
checkExist++;
String PATH = Environment
.getExternalStorageDirectory()
+ "/Blog Radio/"
+ filename.replace(filename
.substring(filename.indexOf(".")),
"")
+ "_"
+ checkExist
+ getTypeFile;
file = new File(PATH);
}
}
fileOut = new FileOutputStream(file);
int downloadSize = 0;
byte[] buffer = new byte[8192];
long tempTotal = 0;
long startTime = System.currentTimeMillis();
int bufferLengh = 0;
while ((bufferLengh = fileIn.read(buffer)) != -1) {
long interval = System.currentTimeMillis() - startTime;
if (isCancelled()) {
fileIn.close();
}
if (contentLengh > 0) {
downloadSize += bufferLengh;
tempTotal += bufferLengh;
mProgress = (int) ((downloadSize * 100L) / contentLengh);
if (interval >= 1000) {
Log.i("now = ", String.valueOf(System
.currentTimeMillis()));
Log.i("last = ", String.valueOf(startTime));
Log.i("currentDump = ",
String.valueOf(tempTotal));
mSpeed = (int) (tempTotal * 1000 / interval / 1024);
startTime = System.currentTimeMillis();
tempTotal = 0;
}
fileOut.write(buffer, 0, bufferLengh);
onProgressUpdateReceiver(mProgress, mSpeed);
}
}
fileOut.flush();
fileOut.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
class ViewDetailDownload :
public class ViewDetailDownload extends Activity {
TextView tv_Title, tv_Info;
ProgressBar progressBar;
ImageView img;
MyRequestReceiver receiver;
IntentFilter intentToReceiveFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_service_layout);
img = (ImageView) findViewById(R.id.img);
tv_Title = (TextView) findViewById(R.id.title);
tv_Info = (TextView) findViewById(R.id.info);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
intentToReceiveFilter = new IntentFilter();
intentToReceiveFilter
.addAction(DownloadServiceTest.PROGRESS_UPDATE_ACTION);
receiver = new MyRequestReceiver();
}
#Override
protected void onResume() {
registerReceiver();
super.onResume();
}
private void registerReceiver() {
this.registerReceiver(receiver, intentToReceiveFilter);
}
#Override
protected void onPause() {
unregisterReceiver();
super.onPause();
}
protected void onProgressUpdate(int progress, int speed) {
progressBar.setProgress(progress);
tv_Info.setText(speed);
}
protected void onProgressUpdateOneShot(int progresses, int speeds) {
int progress = progresses;
int speed = speeds;
onProgressUpdate(progress, speed);
}
private void unregisterReceiver() {
this.unregisterReceiver(receiver);
}
public class MyRequestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
DownloadServiceTest.PROGRESS_UPDATE_ACTION)) {
int progresses = intent.getIntExtra("progress", -1);
int speeds = intent.getIntExtra("speed", -1);
Log.i("", "abc progresses onReceive" + progresses);
Log.i("", "abc speeds onReceive" + speeds);
onProgressUpdateOneShot(progresses, speeds);
}
}
}
}
I need help !
If you know... please give example.
Thanks all
add this in DownloadServiceTest.java in onCreate() method.
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String mname =(String) b.getString("LINK_MP3");
}
Now you can use this string mname anywhere in your DownloadServiceTest

Progressbar with percentage in Asynctask Android

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.

Local broadcast manager for downloading files

I'm creating a local broadcast receiver for notifying an activity when a download has started and finished. I have two classes, one is the DownloadFileFromURL class that i call to download certain file, and in it I've defined this:
Intent intent = new Intent("completeDownloadItem");
// You can also include some extra data.
intent.putExtra("completedItem", suraName);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
that in my opinion should send a broadcast to my DownloadManager class that has this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_manager);
LocalBroadcastManager.getInstance(this).registerReceiver(itemReceiver,
new IntentFilter("addDownloadItem"));
LocalBroadcastManager.getInstance(this).registerReceiver(
completeReceiever, new IntentFilter("completeDownloadItem"));
}
private BroadcastReceiver itemReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
Songs s = (Songs) intent.getSerializableExtra("newItems");
Log.d("receiver", "Got song: " + s.getTitle());
}
};
private BroadcastReceiver completeReceiever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("completedItem");
Log.d("receiver", "Downloaded: " + message);
}
};
Can any one tell me what am I missing, should I define local broadcast receiver in the manifest or something?
here is the DownloadFileFromURL class:
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog dialog;
private String reciterName, suraName;
private String file_url, filePath;
private MediaScannerConnection msc;
private DatabaseHelper db;
private int songNumber;
public DownloadFileFromURL(Context context, String reciterName,
String suraName, String fileURL, int songNumber) {
this.context = context;
this.songNumber = songNumber;
this.reciterName = reciterName;
this.suraName = suraName;
this.file_url = fileURL;
db = new DatabaseHelper(context);
}
protected void createDialog() {
// switch (id) {
// case progress_bar_type: // we set this to 0
dialog = new ProgressDialog(context);
// dialog.setMessage(context.getString(R.string.downloading) + " "
// + songName);
/*
* dialog.setIndeterminate(false); dialog.setMax(100);
*/
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(false);
dialog.show();
// default:
// return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// createDialog();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(file_url);
URLConnection conection = url.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(url.openStream(), 8192);
// Output stream
File appDir = new File(Environment.getExternalStorageDirectory()
.getPath() + "/" + context.getString(R.string.app_name));
appDir.mkdirs();
File albumDir = new File(appDir.getPath().toString() + "/"
+ reciterName);
albumDir.mkdirs();
OutputStream output = new FileOutputStream(appDir + "/"
+ reciterName + "/" + suraName + ".mp3");
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);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
// dialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
msc = new MediaScannerConnection(context,
new MediaScannerConnection.MediaScannerConnectionClient() {
#Override
public void onScanCompleted(String path, Uri uri) {
msc.disconnect();
}
#Override
public void onMediaScannerConnected() {
msc.scanFile(filePath, null);
}
});
if (!msc.isConnected()) {
}
// dialog.dismiss();
db.openDB();
db.addDownloaded(songNumber, reciterName);
db.closeDB();
Intent intent = new Intent("completeDownloadItem");
// You can also include some extra data.
intent.putExtra("completedItem", suraName);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Toast.makeText(context, "Sucessfully downloaded " + suraName,
Toast.LENGTH_SHORT).show();
}
}
No, local broadcast receivers don't need to be configured in the AndroidManifest.xml. I have to say that I am as well a bit puzzled why the notification does not work; have you debugged into the code and checked if the broadcast is actually send out and whether the receiver is registered properly?
If you cannot get it working (for whatever reason), consider using a library like EventBus for your inter-component communication needs. Personally I haven't used the LocalBroadcastManager in ages...

Categories

Resources