Android Progress Dialog Set Message From a Class File - android

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.

Related

Get too many results

I'm trying to create Favorites class. I search for title I get from the user and adds the video to the Favorites class. But, I always get more than one result. ( I get the maximum results which is 10 ).
How can I get only 1 result for each title?
This is the on create:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_layout);
getSupportActionBar().setTitle("Favorites");
initializeViews();
extras = getIntent().getExtras();
this.vidTitle = extras.getString("title");
this.vidID = extras.getString("id");
//Checking where to add the new Video
for(int i=0;i<favorites.length;i++){
if(favorites[i]==null){
favorites[i] = vidTitle;
}
break; // Break so it won't add same video to all array
}
AppUtils.showToast("Loading Favorites");
getVideo2();
}
This is the code which gets the 10 results:
public void getVideo(){
AppUtils.showToast("Loading Favorites");
mServiceTask = new ServiceTask(SEARCH_VIDEO);
mServiceTask.setmServerResponseListener(this);
for (int i=0; i<favorites.length;i++) {
if(favorites[i]!=null){
mServiceTask.execute(new Object[]{favorites[i]}); <--- Problem here
break;
}
else{
break;
}
}
}
ServiceTask:
public class ServiceTask extends AsyncTask<Object, Void, Object[]> implements ServiceTaskInterface{
private static final String TAG = ServiceTask.class.getSimpleName();
private ServerResponseListener mServerResponseListener = null;
private int mRequestCode = 0;
public void setmServerResponseListener(ServerResponseListener mServerResponseListener){
this.mServerResponseListener = mServerResponseListener;
}
public ServiceTask(int iReqCode){
mRequestCode = iReqCode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mServerResponseListener.prepareRequest(mRequestCode);
}
#Override
protected Object[] doInBackground(Object... params) {
if(params == null)
throw new NullPointerException("Parameters to the async task can never be null");
mServerResponseListener.goBackground();
Object[] resultDetails = new Object[2];
resultDetails[0] = mRequestCode;
switch (mRequestCode){
case AppConstants.SEARCH_VIDEO:
try {
resultDetails[1] = loadVideos((String) params[0]);
break;
}catch (Exception e){
AppUtils.showToast("BLABLABLA");}
}
return resultDetails;
}
#Override
protected void onPostExecute(Object[] result) {
super.onPostExecute(result);
mServerResponseListener.completedRequest(result);
}
//Loading the videos, with help of Google's code.
private List<SearchResult> loadVideos(String queryTerm){
try{
YouTube youTube = new YouTube.Builder(transport,jsonFactory,new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest httpRequest) throws IOException {}
}).setApplicationName(YoutubeApplication.appName()).build();
YouTube.Search.List search = youTube.search().list("id,snippet");
search.setKey(AppConstants.KEY);
search.setQ(queryTerm);
//Only including videos
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url,snippet/thumbnails/medium/url)");
search.setMaxResults(AppConstants.NUMBER_OF_VIDEOS_RETURNED);
//Call the API to print results
SearchListResponse searchListResponse = search.execute();
List<SearchResult> searchResultList = searchListResponse.getItems();
if(searchResultList != null){
return searchResultList;
}
}catch (GoogleJsonResponseException e){
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
}catch (IOException e){
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
}catch (Throwable t){
t.printStackTrace();
}
return null;
}
}
How can I get only 1 result at time but still have place for 10 results ( like 10 different videos) ?
At first, comment your break; lines or your loop is useless. Then collect your not null objects in list and place it in execute method with toArray.
LinkedList<Object> list = new LinkedList<Object>();
for (int i=0; i<favorites.length; i++) {
if(favorites[i]!=null){
//mServiceTask.execute(new Object[]{favorites[i]}); //<--- Problem here
list.add(favorites[i]);
//break;
}
else{
//break;
}
}
mServiceTask.execute(list.toArray());
UPDATE
And about ServiceTask class. In doInBackground you are using only params[0] - the first array element. So there should be:
for (int i=0; i<params.length; i++) {
loadVideos((String) params[i]);
}

AsyncTask doesn't working with finding a file

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");

Splash screen with background task

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.

android AsyncTask - can't execute onPostExecute method

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.)

AsyncTask and JSOUP Parsing

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.

Categories

Resources