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.
Related
I have this function where it checks what are the choices of the users made.
So for example
there is a 4 choices:
InfoOfUp
InfoOfArt
InfoOfParish
InfoOfAteneo.
So when the user selects InfoOfUp and InfoOfArt then on the next activity, i will click a button that contains function : selected() it will check the items that was choosen by the user. if the user choose item InfoOfUp it will run a specific function and if the user choose item InfoOfArt it will also run a specific function
The problem is every item has it's own function and every item have progress dialog that marks if the function is already done or not.
So the user choose 2 items there's an error because there's 2 function being called up at the same time;
I want the function to be call 1by1 where the function waits to the other function to finish.
To avoid confusion, i call methods as function.
public void selected() {
if (InfoOfUp.select == 1) {
if (ayala == 0) {
ayala();
ayala = 1;
} else if (ayala == 1) {
}
}
if (InfoOfArt.select == 1) {
if (art == 0) {
ArtInIsland();
art = 1;
} else if (art == 1) {
}
}
if (InfoOfParish.select == 1) {
if (parish == 0) {
parish();
parish = 1;
} else if (parish == 1) {
}
}
if (InfoOfAteneo.select == 1) {
if (ateneo == 0) {
ateneogallery();
ateneo = 1;
} else if (ateneo == 1) {
}
}
Additionally, if the function calls, it will run an asynctask to get data.
here is my asynctask:
public class connectAsyncTask3 extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
private traffic traffic;
private boolean displayDestinationDetails;
String url;
boolean launchDestination;
connectAsyncTask3(String urlPass, traffic traffic, boolean displayDestinationDetails) {
this.url = urlPass;
this.traffic = traffic;
this.displayDestinationDetails = displayDestinationDetails;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
try {
super.onPreExecute();
progressDialog = new ProgressDialog(traffic.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if (result != null) {
Log.d("momo2", " : " + result);
traffic.drawPath(result);
speakOut();
}
if (displayDestinationDetails) {
Intent i = new Intent(traffic.this, poppers.class);
i.putExtra("currentMarker", traffic.markers.size());
traffic.startActivity(i);
}
}
}
Classic multi threading situation.
Create two threads, each one in the method related, start them and use
thread.join()
to begin second thread only after first finished.
great example here
Actually what i am trying to do is that call an asyncTask several times inside a loop. So, first time the asyncTask will start immediately and from second time onwards, it will check whether the AsyncTask has been finished-if finished than again call it with different values.
Below is my code for the activity:
In onCreate()
btnUpload.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
count_response = 0;
newUploadWithSeparate();
}
});
The newUploadWithSeparate() method:
private void newUploadWithSeparate()
{
responseString_concat = "";
if(filePath.length > 0)
{
for(int i=0;i<filePath.length;i++)
{
count_response = i;
if(i == 0)
{
uploadAsync.execute(filePath[0]);
mHandler = new Handler() {
#Override public void handleMessage(Message msg) {
String s=(String)msg.obj;
Log.d("logIMEI","\n Response from Asynctask: " + s);
str_response_fromAsync = s;
}
};
}
else
{
uploadAsync.getStatus();
while(uploadAsync.getStatus() == AsyncTask.Status.RUNNING) // this while loop is just to keep the loop value waitining for finishing the asyncTask
{
int rx = 0;
}
if(uploadAsync.getStatus() != AsyncTask.Status.RUNNING)
{
if(uploadAsync.getStatus() == AsyncTask.Status.FINISHED)
{
if(str_response_fromAsync != "" || !str_response_fromAsync.equals("") || !str_response_fromAsync.isEmpty())
{
uploadAsync.execute(filePath[i]);
x = i;
mHandler = new Handler() {
#Override public void handleMessage(Message msg)
{
String s=(String)msg.obj;
Log.d("logIMEI","\n Response from Asynctask_" + x + ": " + s);
str_response_fromAsync = s;
}
};
}
}
}
}
}
}
}
And the asyncTask:
private class UploadFileToServer extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... params)
{
return uploadFile(params[0]);
}
private String uploadFile(String pr)
{
//inside here calling webservice and getting a response string as result.
MyWebsrvcClass mycls = new MyWebsrvcClass();
return responseString_concat = mycls.Call(xxx,yyy) ;
}
#Override
protected void onPostExecute(String result)
{
Log.d("logIMEI" , "\n count_response : "+ count_response + " fileprath_len : " + filePath.length);
Message msg=new Message();
msg.obj=result.toString();
mHandler.sendMessage(msg);
super.onPostExecute(result);
}
}
Now the problem is that its not working as expected. The first time when value of i is equals 0 than the AsyncTask gets called and after that its not getting called anymore.
Plus, when first time AsyncTask is called- its still not directly entering to onPostExecute(). When the loop ends totally and newUploadWithSeparate() method ends then the onPostExecute() is working.
Any solutions for this or any other way to do this job done for using AsyncTask inside loop?
You cannot call execute() on the same object more than once. So create a new instance of UploadFileToServer for each iteration of the loop.
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.
I am trying to use ProgressDialog. when i run my app the Progress Dialog box show and disappear after 1 second. I want to show it on completion of my process.. Here is my code:
public class MainActivity extends Activity {
android.view.View.OnClickListener mSearchListenerListener;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new YourCustomAsyncTask().execute(new String[] {null, null});
}
private class YourCustomAsyncTask extends AsyncTask <String, Void, Void> {
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading....");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show(); //Maybe you should call it in ruinOnUIThread in doInBackGround as suggested from a previous answer
}
protected void doInBackground(String strings) {
try {
// search(strings[0], string[1]);
runOnUiThread(new Runnable() {
public void run() {
// updateMapWithResult(); //Or call it onPostExecute before progressDialog's dismiss. I believe this method updates the UI so it should run on UI thread
}
});
} catch(Exception e) {
}
}
#Override
protected void onPostExecute(Void params) {
dialog.dismiss();
//result
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}
}
Updated Question:
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
Log.i("PATH",""+mDatabase.getPath());
mDatabase.execSQL(FTS_TABLE_CREATE);
loadDictionary();
}
/**
* Starts a thread to load the database table with words
*/
private void loadDictionary() {
new Thread(new Runnable() {
public void run() {
try {
loadWords();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
for(int i=0;i<=25;i++)
{ //***//
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(raw_textFiles[i]);
//InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
StringBuilder sb = new StringBuilder();
while ((word = reader.readLine()) != null)
{
sb.append(word);
// Log.i("WORD in Parser", ""+word);
}
String contents = sb.toString();
StringTokenizer st = new StringTokenizer(contents, "||");
while (st.hasMoreElements()) {
String row = st.nextElement().toString();
String title = row.substring(0, row.indexOf("$$$"));
String desc = row.substring(row.indexOf("$$$") + 3);
// Log.i("Strings in Database",""+title+""+desc);
long id = addWord(title,desc);
if (id < 0) {
Log.e(TAG, "unable to add word: " + title);
}
}
} finally {
reader.close();
}
}
Log.d(TAG, "DONE loading words.");
}
I want to show ProgressDialogue box untill all words are not entered in the database. This code is in inner calss which extends SQLITEHELPER. so how to can i use ProgressDialogue in that inner class and run my addWords() method in background.
You cannot have this
runOnUiThread(new Runnable() {
public void run() {
// updateMapWithResult(); //Or call it onPostExecute before progressDialog's dismiss. I believe this method updates the UI so it should run on UI thread
}
});
in your doInBackground().
Progress dialog doesn't take priority when there is some other action being performed on the main UI thread. They are intended only when the actions are done in the background. runonUIthread inside doInBackground will not help you. And this is normal behavior for the progressdialog to be visible only for few seconds.
You have two doInBackground() methods inside your AsyncTask Class. Remove the runOnUiThread() from First doInBackground() and move it to second doInBackground() which has #Override annotation.
I don't know whether you wantedly written two doInBackground() methods or by mistake but it is not good to have such confusion between the Method. Your AsyncTask is not calling the first doInBackground() and it will call doInBackground() which has #Override annotation. So your ProgressDialog is dismissed in 1 second of time as it returns null immediately.
I have an asynctask that is in its own activity. I pass it a string value and it connects to my web service and downloads Json data based on the name I pass in, returning the Json resultset. Works great.
I'd like to add a progress spinner to the asynctask, but I'm stymied as to how to do it. I've perused this and many other blogs, and come close but have not yet found the solution. It seems I either need to have the asynctask in with an Activity class to get the context or I have to pass in the context as a parameter -- but I need the input parameter to be String. I've read about the possibility of building an Object that could hold the String and a Context parameter, but I'm very new to Java and don't know how to build something like that nor have I found a good explanation of how to do so. So often an explanation gets right up to what I need and then says, "... and then you do X and that's it," when X is what I need to know.
All I want is just a spinner thingie to whirl while the download happens. No text, no dialog, just a spinner.
class MyTask extends AsyncTask<Request, Void, Result> {
protected ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(YourActivity.this, "", "", true, false);
}
#Override protected Boolean doInBackground(Request... params) {
// do some work here
return true;
}
#Override protected void onPostExecute(Result res) {
progressDialog.dismiss();
}
}
Add a ProgressBar(this is what it's actually called, Spinners are like drop down menus in Android) to the layout of the Activity where you're initializing your AsyncTask.
Then make two functions startProgress() and stopProgress(), which start and stop the progress bar.
Give your AsyncTask a reference to the Activity, either by sending it during initialization or execution, or making a function in your asyncTask setActivity(MyActivity activity) and call it between your AsyncTask initialization and execution.
Override the onPreExecute() of your AsyncTask to call activity.startProgress() and onPostExecute() to call activity.stopProgress().
EDIT: You can also try passing a reference to the ProgressBar in the constructor of your AsyncTask. Get the reference to the ProgressBar in the onCreate() method of your activity, then add it in the AsyncTask constructor. In the onPreExecute() and onPostExecute() methods of the AsyncTask, start and stop the progress bars accordingly.
You can pass various parameters to an AsyncTask, not just one!
One way to do this is to make member variables in your AsyncTask and initialize them using a constructor that accepts parameters.
For example:
private class MyAsyncTask extends AsyncTask<null, null, null> {
String mFirstParam = null;
Context mContext = null;
// Constructor which accepts parameters
public MyAsyncTask(String _firstParam, Context _context){
this.mFirstParam = _firstParam;
this.mContext = _context;
}
}
When you create an instance of your AsyncTask, create it as follows:
MyAsyncTask task = new MyAsyncTask(myFirstStringParam, mySecondContextParam);
task.execute();
Now you can use both these parameters throughout the scope of your AsyncTask.
Consider passing the ImageView containing of "loading" image and set its Visibility to View.GONE once you have finished downloading your data.
i.e. download your data in the doInBackground method and then change the ImageViews visibility to View.GONE in the onPostExecute method
I think you can pass the progress bar instance to AsyncTask when your create it in its constructor. Here is a downloader example by using AsyncTask -
public void downloadFile(String url, String path, ProgressDialog progress) {
DownloadFileAsync downloader = new DownloadFileAsync(progress);
File file = new File(path);
if (file.exists()) {
file.delete();
}
downloader.execute(url, path);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
private final WeakReference<ProgressDialog> progressbarReference;
public DownloadFileAsync(ProgressDialog progress) {
progressbarReference = new WeakReference<ProgressDialog>(progress);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#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();
/*
* android.util.Log.v("downloadFile", "Lenght of file: " +
* lenghtOfFile + ":" + aurl[1]);
*/
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(aurl[1]);
try {
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);
}
} finally {
if (output != null) {
output.flush();
output.close();
}
if (input != null) {
input.close();
}
}
} catch (Exception e) {
ProgressDialog p = null;
if (progressbarReference != null) {
p = progressbarReference.get();
}
if (p != null && p.isShowing()) {
p.dismiss();
}
}
return null;
}
protected void onProgressUpdate(String... progress) {
if (progressbarReference != null) {
ProgressDialog p = progressbarReference.get();
if (p != null) {
p.setProgress(Integer.parseInt(progress[0]));
}
}
}
#Override
protected void onPostExecute(String unused) {
ProgressDialog p = null;
if (progressbarReference != null) {
p = progressbarReference.get();
}
if (p != null && p.isShowing()) {
p.dismiss();
}
}
}
ProgressDialog is a custom Dialog which have a progress bar inside it.
Hope it helps.