I've written this code for training but it's always returning null (I checked the sdcard and file exists, and also checked required permissions).
private class FindRec extends AsyncTask<String, Integer, File>{
ProgressDialog pd = ProgressDialog.show(Albums.this, "Finding...", "");
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected File doInBackground(String... album) {
File e1 = new File(Environment.getExternalStorageDirectory() + "/bluetooth/" + album + ".zip");
if (e1.exists()) {
return e1;
}
return null;
}
#Override
protected void onPostExecute(File result) {
pd.dismiss();
if (result == null) {
//I always get this toast.
Toast.makeText(getApplicationContext(), "Album Not Found!", Toast.LENGTH_SHORT).show();
} else {
setfile(result);
}
}
then in my oncreate:
...
new FindRec().execute(albumname);
You receive an array of strings in doInBackground, so fetch the first element of that array instead of implicitly converting the array to a string.
File e1 = new File(Environment.getExternalStorageDirectory() +
"/bluetooth/" +
album[0] + ".zip");
Related
I have a splash screen that loads URLs from the Internal Storage and downloads their content from the Web (with an AsynkTask). It puts the downloaded data into an ArrayList, calls the main Activity and finishes. The main activity adapter manages the ArrayList and sets a ListView containing its data.
While I'm in the main Activity, if I press the back button the application exits (I set the android:nohistory="true" for the splash screen activity), but when I return to the app, the splash screen gets loaded and downloads the data again, "doubling" the list view.
How can I prevent the splash screen to be loaded when I return to the app?
Splash screen code:
Context mContext;
ProgressBar progress = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_launcher);
progress = (ProgressBar)findViewById(R.id.progress);
progress.setIndeterminate(true);
if(canWriteOnExternalStorage()) {
try {
setupStorage();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
//dialog appears
}
AsynkTask code:
private class LoadGames extends
AsyncTask<String, Integer, Boolean> {
private ProgressDialog mProgressDialog = null;
private String remoteUrl = null;
#Override
protected void onCancelled() {
Log.e(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: onCancelled !");
super.onCancelled();
}
#Override
protected void onPreExecute() {
Log.d(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: onPreExecute !");
}
#Override
protected Boolean doInBackground(String... params) {
if (params.length == 0)
return false;
else
for (int k = 0; k < (params.length)/2; ++k)
{
this.remoteUrl = params[k*2];
Log.d(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: doInBackground ! ("
+ this.remoteUrl + ")");
// HTTP Request to retrieve the videogames list in JSON format
try {
// Creates the remote request
Log.d(com.example.ludos2_0.MainActivity.TAG,
this.remoteUrl);
RESTRequest request = new RESTRequest(this.remoteUrl);
request.isMethodGET(true);
// Executes the request and print the received response
String response = RESTRequestExecutor.execute(request);
// Custom/Manual parsing using GSON
JsonParser parser = new JsonParser();
if (response != null && response.length() > 0) {
Log.d(com.example.ludos2_0.MainActivity.TAG, "Response: "
+ response);
JsonObject jsonObject = (JsonObject) parser.parse(response);
JsonObject itemObj = jsonObject.getAsJsonObject("results");
String id = null;
String title = null;
String thumbnail = null;
String description = null;
String image = null;
String platform = null;
id = itemObj.get("id").getAsString();
title = itemObj.get("name").getAsString();
if (!(itemObj.get("image").isJsonNull()))
{
thumbnail = ((JsonObject)itemObj.get("image")).get("tiny_url").getAsString();
image = ((JsonObject)itemObj.get("image")).get("small_url").getAsString();
}
else
{
thumbnail = "http://www.persicetometeo.com/images/not_available.jpg";
image = "http://www.persicetometeo.com/images/not_available.jpg";
}
description = itemObj.get("deck").getAsString();
platform = params[k*2 + 1];
Log.d(com.example.ludos2_0.MainActivity.TAG,
title);
ListsManager.getInstance().addVideogame(new Videogame(id, title, thumbnail, image, description, platform));
} else {
Log.d(com.example.ludos2_0.MainActivity.TAG,
"Error getting response ...");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(com.example.ludos2_0.MainActivity.TAG,
"Exception: " + e.getLocalizedMessage());
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: onPostExecute !");
progress.setVisibility(View.GONE);
if (result == false) {
Log.e(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: Error Downloading Data !");
} else {
Log.d(com.example.ludos2_0.MainActivity.TAG,
"AsyncTask->LoadGames: Data Correctly Downloaded !");
Intent intent = new Intent(mContext, MainActivity.class);
startActivity(intent);
finish();
}
super.onPostExecute(result);
}
}
The setupStorage() method loads the file from the Storage and executes the AsynkTask.
Maybe could the overriding of the onRestart() method be a solution?
Or should I prevent the AsyncTask from loading the data already downloaded?
Thanks!
It would be better to prevent AsynkTask to download it again. Or better to clear your listview data. Means if use ArrayList with your List adapter then just clear it before storing putting new data.
My application loads images using url. I tried using the library UrlImageViewHelper. It works. But I want to add a spinning progressbar. So i tried modifying a portion for the progressbar.
The problem is that when i tried to run my application, only at some images the progressbar will appear, then disappear when the iamge is already loaded. at some image, it continued to display..Is this the right place to add my progressbar control?
final Runnable completion = new Runnable() {
#Override
public void run() {
assert (Looper.myLooper().equals(Looper.getMainLooper()));
Bitmap bitmap = loader.result;
Drawable usableResult = null;
if (bitmap != null) {
usableResult = new ZombieDrawable(url, mResources, bitmap);
}
if (usableResult == null) {
clog("No usable result, defaulting " + url);
usableResult = defaultDrawable;
mLiveCache.put(url, usableResult);
}
mPendingDownloads.remove(url);
// mLiveCache.put(url, usableResult);
if (callback != null && imageView == null)
callback.onLoaded(null, loader.result, url, false);
int waitingCount = 0;
for (final ImageView iv: downloads) {
// validate the url it is waiting for
final String pendingUrl = mPendingViews.get(iv);
if (!url.equals(pendingUrl)) {
clog("Ignoring out of date request to update view for " + url + " " + pendingUrl + " " + iv);
continue;
}
waitingCount++;
mPendingViews.remove(iv);
if (usableResult != null) {
// System.out.println(String.format("imageView: %dx%d, %dx%d", imageView.getMeasuredWidth(), imageView.getMeasuredHeight(), imageView.getWidth(), imageView.getHeight()));
iv.setImageDrawable(usableResult);
// System.out.println(String.format("imageView: %dx%d, %dx%d", imageView.getMeasuredWidth(), imageView.getMeasuredHeight(), imageView.getWidth(), imageView.getHeight()));
// onLoaded is called with the loader's result (not what is actually used). null indicates failure.
}
if (callback != null && iv == imageView)
callback.onLoaded(iv, loader.result, url, false);
}
clog("Populated: " + waitingCount);
// if(imageView.isShown())
// if(progressBar != null) progressBar.setVisibility(View.GONE);
}
};
if (file.exists()) {
try {
if (checkCacheDuration(file, cacheDurationMs)) {
clog("File Cache hit on: " + url + ". " + (System.currentTimeMillis() - file.lastModified()) + "ms old.");
final AsyncTask<Void, Void, Void> fileloader = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(final Void... params) {
loader.onDownloadComplete(null, null, filename);
return null;
}
#Override
protected void onPostExecute(final Void result) {
completion.run();
}
};
executeTask(fileloader);
return;
}
else {
clog("File cache has expired. Refreshing.");
}
}
catch (final Exception ex) {
}
}
for (UrlDownloader downloader: mDownloaders) {
if (downloader.canDownloadUrl(url)) {
downloader.download(context, url, filename, loader, completion);
return;
}
}
imageView.setImageDrawable(defaultDrawable);
// if(imageView.isShown())
// if(progressBar != null) progressBar.setVisibility(View.GONE);
}
If someone familiar with this library, can you help achieve my objective? Thanks
In this situation I would be inclined to use an ASyncTask rather than Runnable. The ASyncTask was designed specifically for this purpose and contains methods which are run directly on the UI thread (onProgressUpdate(), onPreExecute() and onPostExecute()). These methods are ideal for showing, hiding and updating a progress bar as required.
This tutorial should provide you with a fairly good starting point.
ASyncTask is what you are looking for, whenever there is Resource Fetching or rendering like UI components and images and etc ASYNCTask is the answer but when you are looking for Data Fetching always use Runnable Threads.
class ImageFetch extends AsyncTask {
private final ProgressDialog dialog = new ProgressDialog(this.context);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Fecthing Image");
this.dialog.setTitle("Please Wait");
this.dialog.setIcon(R.drawable."Any Image here");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// Put your Image Fetching code here
}
#Override
protected void onPostExecute(Void aVoid) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
and after that in the Activity code do it like this new ImageFetch().execute();
you are done.
I have wrote an app to run an AsyncTask and part of the code is listed as follow. The problem is when the AsyncTask start by execute the code - "new AddImageTask().execute();" in the thread handler, the task will start and everything seems right. However, eventually the app will stay in "doInBackground" method after all code in "doInBackground" method has been executed. The task can't go to "onPostExecute" method. (i.e. can't dismiss the dialog...) What get wrong?
Thanks for the help......
private Handler handleFetchResult = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
Log.d(TAG, "Start handle fetch result");
try {
JSONArray ja = new JSONArray(fetchResult);
Log.d(TAG, "JSON Array Length = " + ja.length());
JSONObject jo = new JSONObject();
for (int i = 0; i < ja.length(); i++) {
jo = ja.getJSONObject(i);
PhotoURLs.add(PAT_url + jo.getString("filePath"));
Log.d(TAG, PhotoURLs.get(i));
}
} catch (JSONException e) {
Log.d(TAG, "Fetch result error: " + e.getLocalizedMessage());
e.printStackTrace();
}
//TODO: display thumbnail
new AddImageTask().execute();
}//void handleMessage
};//Handler handleFetchResult
class AddImageTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadThumbnailDialog.show(SitePhotoGallery.this, "Fetch thumbnails from server",
"Loading...", true, true);
Log.d("AddImageTask.onPreExecute","onPreExecute");
}
#Override
protected Void doInBackground(Void... unused) {
// TODO Auto-generated method stub
for (String url : PhotoURLs) {
String filename = url.substring(url.lastIndexOf("/") + 1, url.length());
String thumburl = url.substring(0, url.lastIndexOf("/")+1);
imgAdapter.addItem(LoadThumbnailFromURL(thumburl + filename));
publishProgress();
}
Log.d("AddImageTask.doInBackground","doInBackground");
return null ;
}
#Override
protected void onProgressUpdate(Void... unused) {
super.onProgressUpdate();
imgAdapter.notifyDataSetChanged();
Log.d("AddImageTask.onProgressUpdate","OnProgressUpdate");
}
protected void onPostExecute(Void... unused) {
super.onPostExecute(null);
loadThumbnailDialog.dismiss();
Log.d("AddImageTask.onPostExecute","onPostExecute");
}
}
I think it's because onPostExecute() should take a Void parameter and not a Void... parameter. (You should also specify #Override as Soxxeh pointed out in his/her comment above.)
so basically im trying to parse some data from website using AsyncTask, i want it to get website url from program, update ui with downloaded data and show progressdialog (spinning wheel) so i figured i need to do it like that: (UPDATE): k now its ok with variables but program force closes anyway
private class backgroundDATA extends AsyncTask<String, Void, Void> {
ProgressDialog dialog;
Document doc;
#Override
protected void onPreExecute() {
dialog = dialog.show(Result.this, " ",
" Loading. Please wait ... ", true);
}
#Override
protected Void doInBackground(String... params) {
try {
doc = Jsoup.connect(params[0]).get();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
Elements maine;
Elements titleJSOUP;
Elements recipeJSOUP;
Elements instructionsJSOUP;
String recipE;
maine = doc.select("div#recipeContent");
titleJSOUP = doc.select("title");
recipeJSOUP = maine.select("ul.recipe");
instructionsJSOUP = maine.select("p.instructions");
recipE = recipeJSOUP.toString();
drinkNameText.setText("THE "
+ Jsoup.parse(titleJSOUP.toString()).text()
);
dontListenText.setText(Jsoup.parse(titleJSOUP.toString()).text()
);
recipeText.setText(prepareDRINK(recipE));
instructionsText.setText(Jsoup.parse(instructionsJSOUP.toString())
.text());
dialog.dismiss();
}
}
Well this is going to cause a NullPointerException for a start...
#Override
protected void onPreExecute() {
dialog = dialog.show(Result.this, " ",
" Loading. Please wait ... ", true);
}
You can't call dialog.show(...) as dialog will be null.
Call the static ProgressDialog.show(...) method instead.
I have the following code that downloads a video using AsyncTask.
//DOWNLOAD VIDEOS
private class downloadVideosAsync extends AsyncTask <String, String, String>{
protected void onPreExecute(){
super.onPreExecute();
MyActivity.this.mProgressDialog.setMessage("Downloading Videos...");
}
#Override
protected String doInBackground(String... strings){
try{
VideosC.downloadVideos( VideosM.getVideoNames(), VideosM.getVideoUrls(),
VideosM.getVideoThumbs(), VideosM.getFileModified() );
}catch (NullPointerException e){
Log.e(LOG_TAG, e.toString());
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
new downloadSlideshowsAsync().execute();
}
}
As you can see I have set the message "Downloading Videos..." for my progress dialog. Now what I want to do is something like setMessage("Downloading 1 of 5"). But the problem is my downloadVideos function is in another class file VideosController.java
public void downloadVideos( ArrayList<String> VideoNames, ArrayList<String> VideoUrls,
ArrayList<String> VideoThumbs, ArrayList<String> fileModified){
try{
int x;
int videoNamesLenght = VideoNames.size();
File vidFile;
for(x = 0; x < videoNamesLenght; x++) {
String[] videoName = VideoNames.get(x).split("/");
String currentFile = videoName[0] + "." + videoName[1];
String currentFileURL = VideoUrls.get(x) + VideoNames.get(x);
Log.v(LOG_TAG, "currentFileURL: " + currentFileURL);
vidFile = new File(Environment.getExternalStorageDirectory()
+ "/MyApp/Downloads/Videos/", currentFile);
//I want to do maybe here something like
//mProgressDialog.setMessage("Downloading x of y")
downloadVideoFile(currentFile, currentFileURL, vidFile, fileModified.get(x));
}
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
}
Any ideas? Thanks a lot for any help! :)
You can define a static function in Activity which call the VideosController.
In that function you can send Handler Message and handle it.