Need help on listitem click in android - java

Hi I have created download process activity and it's run on button click. This activity opens on listitem click. But Now I want to run the download process on lisitem click, instread of button click.
ZipDownloader.java
import java.io.File;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.kabelash.sg.util.DecompressZip;
import com.kabelash.sg.util.DownloadFile;
import com.kabelash.sg.util.ExternalStorage;
import com.kabelash.sg.R;
public class ZipDownloader extends Activity {
protected ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.zipdownload );
// Keep the screen (and device) active as long as this app is frontmost.
// This is to avoid going to sleep during the download.
getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
}
/**
* Invoked when user presses "Start download" button.
*/
public void startDownload( View v ) {
String url = "http://sample.co.uk/sample.zip";
new DownloadTask().execute( url );
}
/**
* Background task to download and unpack .zip file in background.
*/
private class DownloadTask extends AsyncTask<String,Void,Exception> {
#Override
protected void onPreExecute() {
showProgress();
}
#Override
protected Exception doInBackground(String... params) {
String url = (String) params[0];
try {
downloadAllAssets(url);
} catch ( Exception e ) { return e; }
return null;
}
}
//Progress window
protected void showProgress( ) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle( R.string.progress_title );
mProgressDialog.setMessage( getString(R.string.progress_detail) );
mProgressDialog.setIndeterminate( true );
mProgressDialog.setCancelable( false );
mProgressDialog.show();
}
protected void dismissProgress() {
// You can't be too careful.
if (mProgressDialog != null && mProgressDialog.isShowing() && mProgressDialog.getWindow() != null) {
try {
mProgressDialog.dismiss();
} catch ( IllegalArgumentException ignore ) { ; }
}
mProgressDialog = null;
}
}
on MainActivity.java
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.update:
Intent intent = new Intent(this, ZipDownloader.class);
startActivity(intent);
break;
}
return true;
}
Please don't ignore this question. Thanks in advance and sorry for my English.

Have you tried bringing your AsyncTask code into the activity you want your listitem clicked, then just
switch(item.getItemId()){
case R.id.update:
String url = "http://sample.co.uk/sample.zip";
new DownloadTask().execute( url );
break;
}
return true;
call the background task onclick?

Related

How to Integrate Paypal with Current Android Webapp

I have not had prior experience with Java so please don't be too harsh.
I am making a webapp for android and most of the files paths are like assets/www/files.html
I want to integrate Paypal such that, onclicking a button in a html file, it should direct me to Paypal. I'm not really sure how to go about integrating Paypal because most tutorials do it in their MainActivity from a scratch and it would affect my MainActivity hence your advice would be appreciated!
My MainActivity is:
package com.this.myapp;
import android.os.Bundle;
import org.apache.cordova.*;
public class MainActivity extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);
}
}
I exported my file from eclipse, so my CordovaActivity file is inside CordovaLib, and its codes are:
package org.apache.cordova;
import java.util.ArrayList;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
public class CordovaActivity extends Activity {
public static String TAG = "CordovaActivity";
// The webview for our app
protected CordovaWebView appView;
private static int ACTIVITY_STARTING = 0;
private static int ACTIVITY_RUNNING = 1;
private static int ACTIVITY_EXITING = 2;
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;
// Flag to keep immersive mode if set to fullscreen
protected boolean immersiveMode;
// Read from config.xml:
protected CordovaPreferences preferences;
protected String launchUrl;
protected ArrayList<PluginEntry> pluginEntries;
protected CordovaInterfaceImpl cordovaInterface;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
LOG.i(TAG, "Apache Cordova native platform version " + CordovaWebView.CORDOVA_VERSION + " is starting");
LOG.d(TAG, "CordovaActivity.onCreate()");
// need to activate preferences before super.onCreate to avoid "requestFeature() must be called before adding content" exception
loadConfig();
if (!preferences.getBoolean("ShowTitle", false)) {
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}
if (preferences.getBoolean("SetFullscreen", false)) {
Log.d(TAG, "The SetFullscreen configuration is deprecated in favor of Fullscreen, and will be removed in a future version.");
preferences.set("Fullscreen", true);
}
if (preferences.getBoolean("Fullscreen", false)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
immersiveMode = true;
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
super.onCreate(savedInstanceState);
cordovaInterface = makeCordovaInterface();
if (savedInstanceState != null) {
cordovaInterface.restoreInstanceState(savedInstanceState);
}
}
protected void init() {
appView = makeWebView();
createViews();
if (!appView.isInitialized()) {
appView.init(cordovaInterface, pluginEntries, preferences);
}
cordovaInterface.onCordovaInit(appView.getPluginManager());
// Wire the hardware volume controls to control media if desired.
String volumePref = preferences.getString("DefaultVolumeStream", "");
if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
}
#SuppressWarnings("deprecation")
protected void loadConfig() {
ConfigXmlParser parser = new ConfigXmlParser();
parser.parse(this);
preferences = parser.getPreferences();
preferences.setPreferencesBundle(getIntent().getExtras());
launchUrl = parser.getLaunchUrl();
pluginEntries = parser.getPluginEntries();
Config.parser = parser;
}
//Suppressing warnings in AndroidStudio
#SuppressWarnings({"deprecation", "ResourceType"})
protected void createViews() {
//Why are we setting a constant as the ID? This should be investigated
appView.getView().setId(100);
appView.getView().setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
setContentView(appView.getView());
if (preferences.contains("BackgroundColor")) {
int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
// Background of activity:
appView.getView().setBackgroundColor(backgroundColor);
}
appView.getView().requestFocusFromTouch();
}
/**
* Construct the default web view object.
* <p/>
* Override this to customize the webview that is used.
*/
protected CordovaWebView makeWebView() {
return new CordovaWebViewImpl(makeWebViewEngine());
}
protected CordovaWebViewEngine makeWebViewEngine() {
return CordovaWebViewImpl.createEngine(this, preferences);
}
protected CordovaInterfaceImpl makeCordovaInterface() {
return new CordovaInterfaceImpl(this) {
#Override
public Object onMessage(String id, Object data) {
// Plumb this to CordovaActivity.onMessage for backwards compatibility
return CordovaActivity.this.onMessage(id, data);
}
};
}
/**
* Load the url into the webview.
*/
public void loadUrl(String url) {
if (appView == null) {
init();
}
// If keepRunning
this.keepRunning = preferences.getBoolean("KeepRunning", true);
appView.loadUrlIntoView(url, true);
}
/**
* Called when the system is about to start resuming a previous activity.
*/
#Override
protected void onPause() {
super.onPause();
LOG.d(TAG, "Paused the activity.");
if (this.appView != null) {
// CB-9382 If there is an activity that started for result and main activity is waiting for callback
// result, we shoudn't stop WebView Javascript timers, as activity for result might be using them
boolean keepRunning = this.keepRunning || this.cordovaInterface.activityResultCallback != null;
this.appView.handlePause(keepRunning);
}
}
/**
* Called when the activity receives a new intent
*/
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//Forward to plugins
if (this.appView != null)
this.appView.onNewIntent(intent);
}
/**
* Called when the activity will start interacting with the user.
*/
#Override
protected void onResume() {
super.onResume();
LOG.d(TAG, "Resumed the activity.");
if (this.appView == null) {
return;
}
// Force window to have focus, so application always
// receive user input. Workaround for some devices (Samsung Galaxy Note 3 at least)
this.getWindow().getDecorView().requestFocus();
this.appView.handleResume(this.keepRunning);
}
/**
* Called when the activity is no longer visible to the user.
*/
#Override
protected void onStop() {
super.onStop();
LOG.d(TAG, "Stopped the activity.");
if (this.appView == null) {
return;
}
this.appView.handleStop();
}
/**
* Called when the activity is becoming visible to the user.
*/
#Override
protected void onStart() {
super.onStart();
LOG.d(TAG, "Started the activity.");
if (this.appView == null) {
return;
}
this.appView.handleStart();
}
/**
* The final call you receive before your activity is destroyed.
*/
#Override
public void onDestroy() {
LOG.d(TAG, "CordovaActivity.onDestroy()");
super.onDestroy();
if (this.appView != null) {
appView.handleDestroy();
}
}
/**
* Called when view focus is changed
*/
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && immersiveMode) {
final int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
getWindow().getDecorView().setSystemUiVisibility(uiOptions);
}
}
#SuppressLint("NewApi")
#Override
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
// Capture requestCode here so that it is captured in the setActivityResultCallback() case.
cordovaInterface.setActivityResultRequestCode(requestCode);
super.startActivityForResult(intent, requestCode, options);
}
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* #param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* #param resultCode The integer result code returned by the child activity through its setResult().
* #param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
LOG.d(TAG, "Incoming Result. Request code = " + requestCode);
super.onActivityResult(requestCode, resultCode, intent);
cordovaInterface.onActivityResult(requestCode, resultCode, intent);
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* #param errorCode The error code corresponding to an ERROR_* value.
* #param description A String describing the error.
* #param failingUrl The url that failed to load.
*/
public void onReceivedError(final int errorCode, final String description, final String failingUrl) {
final CordovaActivity me = this;
// If errorUrl specified, then load it
final String errorUrl = preferences.getString("errorUrl", null);
if ((errorUrl != null) && (!failingUrl.equals(errorUrl)) && (appView != null)) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.appView.showWebPage(errorUrl, false, true, null);
}
});
}
// If not, then display error dialog
else {
final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
me.runOnUiThread(new Runnable() {
public void run() {
if (exit) {
me.appView.getView().setVisibility(View.GONE);
me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
}
}
});
}
}
/**
* Display an error dialog and optionally exit application.
*/
public void displayError(final String title, final String message, final String button, final boolean exit) {
final CordovaActivity me = this;
me.runOnUiThread(new Runnable() {
public void run() {
try {
AlertDialog.Builder dlg = new AlertDialog.Builder(me);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(button,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exit) {
finish();
}
}
});
dlg.create();
dlg.show();
} catch (Exception e) {
finish();
}
}
});
}
/*
* Hook in Cordova for menu plugins
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (appView != null) {
appView.getPluginManager().postMessage("onCreateOptionsMenu", menu);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (appView != null) {
appView.getPluginManager().postMessage("onPrepareOptionsMenu", menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (appView != null) {
appView.getPluginManager().postMessage("onOptionsItemSelected", item);
}
return true;
}
/**
* Called when a message is sent to plugin.
*
* #param id The message id
* #param data The message data
* #return Object or null
*/
public Object onMessage(String id, Object data) {
if ("onReceivedError".equals(id)) {
JSONObject d = (JSONObject) data;
try {
this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url"));
} catch (JSONException e) {
e.printStackTrace();
}
} else if ("exit".equals(id)) {
finish();
}
return null;
}
protected void onSaveInstanceState(Bundle outState) {
cordovaInterface.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
/**
* Called by the system when the device configuration changes while your activity is running.
*
* #param newConfig The new device configuration
*/
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (this.appView == null) {
return;
}
PluginManager pm = this.appView.getPluginManager();
if (pm != null) {
pm.onConfigurationChanged(newConfig);
}
}
/**
* Called by the system when the user grants permissions
*
* #param requestCode
* #param permissions
* #param grantResults
*/
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
try
{
cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults);
}
catch (JSONException e)
{
LOG.d(TAG, "JSONException: Parameters fed into the method are not valid");
e.printStackTrace();
}
}
}

Using Media Player inside my app

I am running a Text To Speech code, but now my new requirement is to provide "Pause" facility. I read number of SO questions and found I have to write data into a file and have to use media player class to play the file. Below is my code.
public void speak(String text)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
tts.synthesizeToFile(text, map,"ttsFile.wav");
//tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
Here I have 2 questions.
I do not want to open media player to play the file, file should be played inside the app with the media player controls (just like how you can set videoView.setMediaController(); to VideoView). How can I do this? any example please?
Is there any "Cache" place to save the above file so it will be deleted once the app is closed?
You can do something like this:
Create a video player in your application :
VideoPlayerActivity.java:
package com.camera.manual;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoPlayerActivity extends Activity {
private boolean mResumed = false;
private boolean mFocused = false;
private boolean mControlResumed = false;
private VideoView videoView = null;
private int stopPosition = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.Theme_TransparentVideo);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setContentView(R.layout.video_view);
videoView =(VideoView)findViewById(R.id.myvideoview);
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri=Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.slow);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
#Override
public void onPause() {
super.onPause();
mResumed = false;
if (mControlResumed) {
if (null != videoView)
videoView.pause();
stopPosition = videoView.getCurrentPosition();
mControlResumed = false;
}
}
#Override
public void onResume() {
super.onResume();
mResumed = true;
if (mFocused && mResumed && !mControlResumed) {
if(null != videoView) {
//videoView.resume();
videoView.seekTo(stopPosition);
videoView.start();
}
mControlResumed = true;
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
mFocused = hasFocus;
if (mFocused && mResumed && !mControlResumed) {
if (null != videoView) {
//videoView.resume();
videoView.seekTo(stopPosition);
videoView.start();
}
mControlResumed = true;
}
}
}
You can call it like this:
Intent intent = new Intent();
intent.setClass(mContext, VideoPlayerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(intent);

android webviewclient running on UI thread issue

attempting to clean up some outdated twitter authentication code Ive been using as the newer versions of android do not allow for network tasks to be done on the ui thread anymore without crashing the app.
I seemed to of solved half the problem by sticking the webview.loadurl(); call onto an async task but the app then crashes during the second part of the process when onLoadResource(); is called by the webviewclient, just cant figure out what the best way would be to place the onLoadResource(); method into an async task without breaking the code.
package com.testapp2.second.activities;
import com.testapp2.second.OTweetApplication;
import com.testapp2.second.R;
import android.app.Activity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class AuthorizationActivity extends Activity {
private OTweetApplication app;
private WebView webView;
private WebViewClient webViewClient = new WebViewClient() {
#Override
public void onLoadResource(WebView view, String url) {
// the URL we're looking for looks like this:
// http://otweet.com/authenticated?oauth_token=1234567890qwertyuiop
Uri uri = Uri.parse(url);
if (uri.getHost().equals("otweet.com")) {
String token = uri.getQueryParameter("oauth_token");
if (null != token) {
webView.setVisibility(View.INVISIBLE);
app.authorized();
finish();
} else {
// tell user to try again
}
} else {
super.onLoadResource(view, url);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (OTweetApplication)getApplication();
setContentView(R.layout.authorization_view);
setUpViews();
}
#Override
protected void onResume() {
super.onResume();
new AuthInBg().execute();
}
private void setUpViews() {
webView = (WebView)findViewById(R.id.web_view);
webView.setWebViewClient(webViewClient);
}
private class AuthInBg extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
String authURL = app.beginAuthorization();
webView.loadUrl(authURL);
return null;
}
}
}
should I change the async task result to a constructor for the OnLoadResource(); method perhaps?
I think that you need to put in runOnUIThread() method the webView.setVisibility(View.INVISIBLE); line and it should work.
it should be like this:
runOnUiThread(new Runnable() {
public void run() {
webView.setVisibility(View.INVISIBLE);
}
});

thread, MediaPlayer, ProgressDialog and context issues

I've tried and done everything that I read on internet and here on stackoverflow to solve my problem, but no success till now. What I'm trying to do is basically click on a button and show a ProgressDialog while the MediaPlayer is buffering a stream from internet. I got many types of erros with context stuff (NullPointerException) and thread problems too. Here are some details about the code:
the button is a toggle button with background image sat based on events (on, off, not connected show different image buttons);
The function prepareStream() is the one that should be ran in a thread and dismiss the ProgressDialog after load the stream. it's calling an http stream of BBC radio;
I guess that the problem is about the context... I've put some Log.d TAGs on the code to check where was happening the problem and O figured out that was on mediaPlayer.start() method.
He goes the little boy:
package com.android.iFocus;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
import com.insightoverflow.iFocus.R;
public class iFocusActivity extends Activity implements OnClickListener {
//Declare Controls
public int count = 0;
public int x = 1;
public MediaPlayer mediaPlayer = null;
ToggleButton toggleRain = null;
Button buttonAbout = null;
Button buttonMethod = null;
Button buttonLink = null;
public ProgressDialog progressDialog;
public static final String TAG = "getFocused";
public boolean isOnline() {
//Check if internet is connected
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void prepareStream(final Context context){
if(isOnline()){
// init player
new Thread()
{
public void run()
{
try {
sleep(1500);
//progressDialog.show();
mediaPlayer = MediaPlayer.create(context, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"), null);
x=2;
} catch (Exception e){
x=3;
}
//dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
} else {
x=3;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// load layout
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// load controls
toggleRain = (ToggleButton)findViewById(R.id.toggleRain);
buttonAbout = (Button)findViewById(R.id.buttonAbout);
buttonMethod = (Button)findViewById(R.id.buttonMethod);
buttonLink = (Button)findViewById(R.id.buttonLink);
//Define Listeners (click event handler)
toggleRain.setOnClickListener(this);
buttonAbout.setOnClickListener(this);
buttonMethod.setOnClickListener(this);
buttonLink.setOnClickListener(this);
// init state for player
count = 0;
//Context APP
//Context appContext = this.getApplicationContext();
if (!isOnline()){
toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.notconnectedbutton));
x=3;
}
}
public void onClick(View v) {
if( toggleRain.getId() == ((Button)v).getId() ){
//meanwhile device is offline, do this
do {
toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.notconnectedbutton));
try{
Thread.currentThread();
//do what you want to do before sleeping
Thread.sleep(1000);//sleep for 1000 ms
//do what you want to do after sleeptig
} catch(Exception ie){}
continue;
}while (!isOnline());
//If device is online, go for this
if (((CompoundButton) toggleRain).isChecked()) {
toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.stopbutton));
} else {
toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.playbutton));
}
//----> HERE GOES WHERE I THINK IS THE PROBLEM <-----
//---------------------------------------------------
if (isOnline()){
//If music is not playing, start music
if(count==0){
Log.d(TAG, "START PROGRESS DIALOG");
progressDialog = ProgressDialog.show(v.getContext(), "Load", "Loading");
//progressDialog = ProgressDialog.show(, "Load", "Loading...", true, false);
Log.d(TAG, "END PROGRESS DIALOG");
Log.d(TAG, "START PREPARE STREAM");
Context context = v.getContext();
prepareStream(context);
Log.d(TAG, "END PREPARE STREAM");
Log.d(TAG, "START MEDIA PLAYER START");
//LOG CAT START AND END ALL OF THE OTHER LOG TAGS, EXCEPT THIS mediaplayer.start()
mediaPlayer.start();
Log.d(TAG, "END MEDIAPLAYER START");
count = 1;
} else {
mediaPlayer.pause();
count = 0;
}
}
} else if( buttonAbout.getId() == ((Button)v).getId() ){
Intent i = new Intent(iFocusActivity.this, AboutActivity.class);
startActivity(i);
}
else if ( buttonMethod.getId() == ((Button)v).getId() ){
Intent o = new Intent(iFocusActivity.this, MethodActivity.class);
startActivity(o);
}
else if ( buttonLink.getId() == ((Button)v).getId() ){
Uri uri = Uri.parse( "http://getFocused.in" );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
So logcat tell me on the time mediaPlayer.start() is called the NullPointerException
You must run your ProgressDialog.show() in the runOnUiThread() method(Not in the main UI thread). See the Android docs here
Create a progress dialog object and then, write this code.
runOnUiThread(new Runnable(){
#Override
public void run() {
dialog.show();
}
});
Also the calls prepareStream() and mediaplayer.start() should go into a separate thread and not the main UI thread.
Sort out the thread related issues and you should be done.

ProgressDialog not updating after Configuration Change (orientation turns to horizontal)

ProgressDialog quits updating when orientation of screen changes. I have put into place a fix that salvages the asynctask and sets the activity of the asynctask to the new activity after it is destroyed and rebuilt. The percentage complete on the progressdialog stays at the percentage it was at before the orientation change.
What am I missing?
package net.daleroy.fungifieldguide.activities;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Toast;
import net.daleroy.fungifieldguide.R;
import net.daleroy.fungifieldguide.fungifieldguideapplication;
public class FungiFieldGuide extends Activity {
//static final int PROGRESS_DIALOG = 0;
//ProgressThread progressThread;
private final static String LOG_TAG = FungiFieldGuide.class.getSimpleName();
fungifieldguideapplication appState;
private DownloadFile mTask;
public boolean mShownDialog;
ProgressDialog progressDialog;
private final static int DIALOG_ID = 1;
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if ( id == DIALOG_ID ) {
mShownDialog = true;
}
}
private void onTaskCompleted() {
Log.i(LOG_TAG, "Activity " + this + " has been notified the task is complete.");
//Check added because dismissDialog throws an exception if the current
//activity hasn't shown it. This Happens if task finishes early enough
//before an orientation change that the dialog is already gone when
//the previous activity bundles up the dialogs to reshow.
if ( mShownDialog ) {
dismissDialog(DIALOG_ID);
Toast.makeText(this, "Finished..", Toast.LENGTH_LONG).show();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_ID:
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading Database (only first run)...");
return progressDialog;
default:
return super.onCreateDialog(id);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
appState = ((fungifieldguideapplication)this.getApplication());
Object retained = getLastNonConfigurationInstance();
if ( retained instanceof DownloadFile ) {
Log.i(LOG_TAG, "Reclaiming previous background task.");
mTask = (DownloadFile) retained;
mTask.setActivity(this);
//showDialog(DIALOG_ID);
}
else {
if(!appState.service.createDataBase())
{
Log.i(LOG_TAG, "Creating new background task.");
//showDialog(DIALOG_ID);
mTask = new DownloadFile(this);
mTask.execute("http://www.codemarshall.com/Home/Download");
}
}
//showDialog(PROGRESS_DIALOG);
View btn_Catalog = findViewById(R.id.btn_Catalog);
btn_Catalog.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(getBaseContext(), Cat_Genus.class);//new Intent(this, Total.class);
startActivity(i);
}
});
View btn_Search = findViewById(R.id.btn_Search);
btn_Search.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(getBaseContext(), Search.class);//new Intent(this, Total.class);
startActivity(i);
}
});
}
#Override
public Object onRetainNonConfigurationInstance() {
mTask.setActivity(null);
return mTask;
}
#Override
public void onDestroy()
{
super.onDestroy();
//progressDialog.dismiss();
//progressDialog = null;
appState.service.ClearSearchParameters();
}
private class DownloadFile extends AsyncTask<String, Integer, Boolean>{
private FungiFieldGuide activity;
private boolean completed;
private String Error = null;
private String Content;
private DownloadFile(FungiFieldGuide activity) {
this.activity = activity;
}
#Override
protected void onPreExecute()
{
showDialog(DIALOG_ID);
}
#Override
protected Boolean doInBackground(String... urlarg) {
int count;
try {
URL url = new URL(urlarg[0]);
URLConnection conexion = url.openConnection();
conexion.setDoInput(true);
conexion.setUseCaches(false);
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(conexion.getInputStream());
OutputStream output = new FileOutputStream("/data/data/net.daleroy.fungifieldguide/databases/Mushrooms.db");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)total*100/lenghtOfFile);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.i(LOG_TAG, e.getMessage());
}
return null;
}
#Override
public void onProgressUpdate(Integer... args){
progressDialog.setProgress(args[0]);
}
#Override
protected void onPostExecute(Boolean result)
{
completed = true;
notifyActivityTaskCompleted();
}
private void notifyActivityTaskCompleted() {
if ( null != activity ) {
activity.onTaskCompleted();
}
}
private void setActivity(FungiFieldGuide activity) {
this.activity = activity;
if ( completed ) {
notifyActivityTaskCompleted();
}
}
}
}
This is not a real solution but to prevent this I just disabled orientation changes during the life of the AsyncTask with adding first:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
and when the job is done:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
Hope this helps.

Categories