In my Project I want to download the link the user enter.
when user enter link to download I want to show progress bar to show the percentage of downloading.
In this code I can show the progress bar but it doesn't show the progress of download.How I can show the percentage or progress of downloading.
and how to finish it after download has finished successfully?
here is my code:
public class MyActivity extends Activity {
private long enqueue;
private DownloadManager dm;
final Context context = this;
public Button star_download, view_downlod;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
star_download = (Button) findViewById(R.id.start_download);
view_downlod = (Button) findViewById(R.id.view_download);
star_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.alert_custom);
dialog.setTitle("Downloading ...");
// set the custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.text);
final String link = text.getText().toString();
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(text.getText().toString()));
enqueue = dm.enqueue(request);
showDialog(progress_bar_type);
}
});
dialog.show();
}
});
view_downlod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
});
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}
I am new with android,and I am really confused, Can anyone help me?
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
getActivity().showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
Log.d("URl","Url====="+f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
extn=f_url[0].split("XYZ/");
Log.d("URlextn","Urlextn====="+extn[1]);
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// File file = new File(Environment.DIRECTORY_DOCUMENTS /);
// Output stream to write file
//OutputStream output = new FileOutputStream(Environment.getExternalStoragePublicDirectory() +extn[1]);
OutputStream output = null;
File mydir = new File(Environment.getExternalStorageDirectory() + "/xyz/");
if(!mydir.exists())
mydir.mkdirs();
output = new FileOutputStream(mydir+"/"+extn[1]);
Log.d("EXTERNAL PATH","EXTERNAL PATH===="+ Environment.getExternalStorageDirectory()+"/xyz/");
byte data[] = new byte[4096];
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;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(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);
pDialog.dismiss();
try{
imagePath = Environment.getExternalStorageDirectory()+"/"+"xyz"+"/" + extn[1];
}
catch (ArrayIndexOutOfBoundsException | NullPointerException ne)
{
System.out.println("ArrayError:" + ne);
}
System.out.println("imagePath==" + imagePath);
imgFile = new File(imagePath);
galleryAddPic(imgFile, getActivity());
}
}
Related
I am making QR scanner based android application that gets the data from QR code and send to server to check the data, but my scanner stuck after scanning an invalid QR code
here's my code
Qrresult.java
public class qrresult extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private FocusHandler focusHandler;
public ImageButton back;
public void backbut() {
back = (ImageButton) findViewById(R.id.bckbut);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//onBackPressed();
Intent back = new Intent(getApplicationContext(),mainmenu.class);
startActivity(back);
}
});
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_qrresult);
RelativeLayout zscanner = (RelativeLayout) findViewById(R.id.zxscan);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
focusHandler = new FocusHandler(new Handler(), mScannerView);
zscanner.addView(mScannerView);
backbut();
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.setAutoFocus(false);
mScannerView.startCamera();
focusHandler.start();
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
focusHandler.stop(); //Stop camera on pause
}
#Override
public void onStop(){
super.onStop();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
String qrdata= rawResult.getText();
qrresultWorker qrresultWorker= new qrresultWorker(this);
qrresultWorker.execute(qrdata);
//mScannerView.resumeCameraPreview(this);
// If you would like to resume scanning, call this method below:
//mScannerView.resumeCameraPreview(this);
}
}
QrresultWorker.java
public class qrresultWorker extends AsyncTask<String,Void,String> {
private Context context;
private AlertDialog alertDialog;
private ProgressDialog Asycdialog;
qrresultWorker(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/projects/dbcon1/qrresult.php";
try {
//Used for Sending data to Database
String qrdata = params[0];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
//httpURLConnection.setConnectTimeout(100000);
//httpURLConnection.setReadTimeout(100000);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("qrdata", "UTF-8") + "=" + URLEncoder.encode(qrdata, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//Used for Getting data from Database
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = ""; //initializing with empty string
String line = ""; //initializing with empty string
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
//progress dialog
//Asycdialog = new ProgressDialog(context);
//Asycdialog.setMessage("Scanning...");
//Asycdialog.show();
//alertdialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
//Intent go = new Intent(context.getApplicationContext(),qrresult.class);
//context.startActivity(go);
dialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.setTitle("Scan Status");
}
#Override
protected void onPostExecute(String result) {
//Asycdialog.dismiss();
/*String name = null;
int balance = 0;
String qrcode=null;
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
*/
if (result.equals("success")){
Intent intent = new Intent(context.getApplicationContext(),sendmoney.class);
context.startActivity(intent);
}
else {
Toast.makeText(context.getApplicationContext(),"Coundn't scan the QR code",Toast.LENGTH_SHORT).show();
//alertDialog.setMessage("Scanning Failed,Invalid Qrcode, please retry");
//alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Try to put condition that it scans only QR code below code scans only QR code
just add below line in gradle and use below code
compile 'com.journeyapps:zxing-android-embedded:3.5.0'
use below code to scan Qr code
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
for more reference CLICK HERE
Seems like you are missing a call to resumeCameraPreview(ZXingScannerView.ResultHandler resultHandler) on your ZXingScannerView once you have finished processing the scanned data. To do this, you need to notify your Activity to call that method on the scanner view in the onPostExecute method of your AsyncTask. Since you've implemented the AsyncTask in a separate class, you're going to have to implement some kind of callback mechanism similar to something like this: What is the best way for AsyncTask to notify parent Activity about completion?.
I tried creating an oAuth based app in android using twitter. But I am facing problems while signing out from the same as the app does not asks the user to re authorize it by asking the credentials to login and directly passes to another layout by clicking on sign in. I cleared all the shared preferences details for logout but not working still.
These are my classes:
MainActivity.java
public class MainActivity extends Activity {
static String TWITTER_CONSUMER_KEY = "key";
static String TWITTER_CONSUMER_SECRET = "sec";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLoggedIn";
private static final String PREF_USER_NAME = "twitter_user_name";
private static final String PREF_PROFILE_IMAGE = "twitter_profile_url";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter mTwitter;
private static RequestToken requestToken;
/* Any number for uniquely distinguish your request */
public static final int WEBVIEW_REQUEST_CODE = 100;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
private RelativeLayout profileLayout, loginLayout;
private TextView mProfileName;
private ImageView mProfileImage;
private EditText mTweetText;
private Bitmap mProfileBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"PREFERENCE_NAME", MODE_PRIVATE);
loginLayout = (RelativeLayout) findViewById(R.id.login_layout);
profileLayout = (RelativeLayout) findViewById(R.id.profile_layout);
mProfileName = (TextView) findViewById(R.id.user_name);
mProfileImage = (ImageView) findViewById(R.id.user_profilePicture);
mTweetText = (EditText) findViewById(R.id.tweet_text);
updateUI();
}
/**
* Check to see if user currently logged in or not and updates the UI
*/
private void updateUI() {
if (isUserLoggedIn()) {
loginLayout.setVisibility(View.GONE);
profileLayout.setVisibility(View.VISIBLE);
String username = mSharedPreferences.getString(PREF_USER_NAME, "");
String profilePictureURL = mSharedPreferences.getString(PREF_PROFILE_IMAGE, "");
new LoadProfilePicture().execute(profilePictureURL);
// Displaying in xml ui
mProfileName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} else {
loginLayout.setVisibility(View.VISIBLE);
profileLayout.setVisibility(View.GONE);
}
}
/**
* Calls when user click tweet button
* #param view
*/
public void postTweet(View view) {
// Call update status function
// Get the status from EditText
String status = mTweetText.getText().toString();
if (TextUtils.isEmpty(status)) {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
return;
}
// update status
new PostTweetOnTwitter().execute(status);
mTweetText.setText("");
}
/**
* Calls when user click login button
* #param view
*/
public void loginUser(View view) {
new LoginUserOnTwitter().execute();
}
/**
* Calls when user click logout button
* #param view
*/
public void logoutUser(View view) {
// Clear the shared preferences
getSharedPreferences("PREFERENCE_NAME", MODE_PRIVATE).edit().clear().commit();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.remove(PREF_KEY_OAUTH_TOKEN).clear().commit();
editor.remove(PREF_KEY_OAUTH_SECRET).clear().commit();
editor.remove(PREF_KEY_TWITTER_LOGIN).clear().commit();
editor.remove(PREF_USER_NAME).clear().commit();
editor.remove(PREF_PROFILE_IMAGE).clear().commit();
editor.apply();
editor.commit();
updateUI();
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
*/
private boolean isUserLoggedIn() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
/**
* Function to login user
*/
class LoginUserOnTwitter extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
configurationBuilder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = configurationBuilder.build();
mTwitter = new TwitterFactory(configuration).getInstance();
try {
requestToken = mTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
/**
* Loading twitter login page on webview for authorization
* Once authorized, results are received at onActivityResult
* */
final Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
}
/**
* Saving user information, after user is authenticated for the first time.
* You don't need to show user to login, until user has a valid access token
*/
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = mTwitter.showUser(userID);
String username = user.getName();
String profilePicture = user.getOriginalProfileImageURL();
/* Storing oAuth tokens to shared preferences */
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
editor.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
editor.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
editor.putString(PREF_USER_NAME, username);
editor.putString(PREF_PROFILE_IMAGE, profilePicture);
editor.apply();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == WEBVIEW_REQUEST_CODE && data != null) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(MainActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = mTwitter.getOAuthAccessToken(requestToken, verifier);
saveTwitterInfo(accessToken);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
updateUI();
}
});
} catch (Exception e) {
e.printStackTrace();
if (e.getMessage() != null) {
Log.e("Twitter-->", e.getMessage());
} else {
Log.e("Twitter-->", "ERROR: Twitter callback failed");
}
}
}
}).start();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
/**
* Function to update status
*/
class PostTweetOnTwitter extends AsyncTask<String, Void, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
*/
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
}
/**
* Function to load profile picture
*/
private class LoadProfilePicture extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Download image from the url
**/
protected Bitmap doInBackground(String... args) {
try {
mProfileBitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return mProfileBitmap;
}
/**
* After completing background task Dismiss the progress dialog and set bitmap to imageview
**/
protected void onPostExecute(Bitmap image) {
Bitmap image_circle = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(image_circle);
c.drawCircle(image.getWidth() / 2, image.getHeight() / 2, image.getWidth() / 2, paint);
mProfileImage.setImageBitmap(image_circle);
pDialog.hide();
}
}
}
I am using web view for calling twitter oAuth.
WebViewActivity.java
public class WebViewActivity extends Activity{
WebView webView;
public static String EXTRA_URL = "extra_url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.auth_dialog);
setTitle("Login");
final String url = this.getIntent().getStringExtra(EXTRA_URL);
if (null == url) {
Log.e("Twitter", "URL cannot be null");
finish();
}
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if( url.contains(MainActivity.TWITTER_CALLBACK_URL)){
Uri uri = Uri.parse(url);
Intent resultIntent = new Intent();
resultIntent.putExtra("KEY_URI", uri.toString());
setResult(RESULT_OK, resultIntent);
/* closing webview */
finish();
return true;
}
return false;
}
});
webView.loadUrl(url);
}
}
I am attaching the screenshots of my app and would like to show how it should work:
The thing what I need is when i tweet something and click on logout and get redirected to sign in screen, I want the app to ask me again for the authorization details. Currently my app switches directly without asking me for any details to tweet screen when used second time after login.
Any sort of help is appreciated.
You can try doing this on your logout button
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
twitter.setOAuthAccessToken(null);
CookieManager.getInstance().removeAllCookie();
CookieManager.getInstance().removeSessionCookie();
On my android app, I have my own BaseAdapter, in this I have a click button listener with the following code:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
final String id = videoIDs[position];
videoActions = new VideoActions();
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
String downloadResult = videoActions.downloadToShare(token, activity, id, videoPathURL[position], finalVideoName);
if (downloadResult.equalsIgnoreCase("POST_FAILURE") || downloadResult.equalsIgnoreCase("FAILURE_102")) {
Toast.makeText(
activity,
activity.getString(R.string.someErrorOccurred),
Toast.LENGTH_SHORT).show();
}
/*if(hfu.Download_File_To_Share(finalVideoName, videoPathURL[position])){
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
//pDialog.dismiss();
} else {
Toast.makeText(activity, "ERRO", Toast.LENGTH_LONG).show();
}*/
}
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
} catch (Exception e) {
pDialog.dismiss();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
Now here you have the function downloadToShare from the class VideoActions:
public String downloadToShare(String token, Activity activity, String videoID, String videoPath, String videoName) {
this.token = token;
this.activity = activity;
this.videoId = videoID;
this.videoPath = videoPath;
this.videoName = videoName;
DownloadToShareClass downloadAction = new DownloadToShareClass();
try {
return downloadAction.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
} // Close download
And now the downloadToShare class:
class DownloadToShareClass extends AsyncTask<String, String, String> {
String response = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Preparing video to share...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
HttpFileUpload hfu = new HttpFileUpload(videoPath, token);
hfu.Download_File_To_Share(videoName, videoPath);
return "SUCESSFULLY";
}
} // Close DownloadClass
Now the download_file_to_share:
boolean Download_File_To_Share(String fileName, String urlToDownload) {
boolean downloadResult;
try {
downloadResult = DownloadFileToShare(fileName, urlToDownload);
return downloadResult;
} catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
And for the last the DownloadFileToShare:
// Download video
boolean DownloadFileToShare(String filename, String urlToDownload)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL url = new URL(urlToDownload);
in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
System.out.println(count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
return true;
}
My Problem is as you can see on my BaseAdapter code, I'm showing a progress dialog, but it only is shown after all the rest finish (the video download). What is the problem here ? I want that the progressDialog shows when the video is being downloaded...
Thanks in advance
I've found a solution to my own problem. From my BaseAdapter I changed my click listener code to the following and it's working perfectly now:
btnShareFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoMoreLayout.setVisibility(View.GONE);
hfu = new HttpFileUpload(videoPathURL[position], token);
final ProgressDialog pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getResources().getString(R.string.preparingVideoToShare));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
if (!isOnline()) {
Toast.makeText(activity,
activity.getString(R.string.noInternetConnection),
Toast.LENGTH_SHORT).show();
} else {
try {
String arr[] = videoPathURL[position].split("/upload/videos/");
final String finalVideoName = (arr[arr.length-1]);
final File DoutFile = new File(
Environment.getExternalStorageDirectory() +
File.separator + "vidytape_shared" + File.separator + finalVideoName);
if(!DoutFile.exists()){
pDialog.show();
(new Thread(new Runnable() {
#Override
public void run() {
final String a = hfu.Download_File_To_Share(finalVideoName, videoPathURL[position]);
activity.runOnUiThread(new Runnable() {
public void run() {
if (!a.equalsIgnoreCase("ok")){
pDialog.dismiss();
Toast.makeText(activity,
activity.getResources().getString(R.string.someErrorOccurred),
Toast.LENGTH_LONG).show();
} else {
pDialog.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
}
});
}
})).start();
} else {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("video/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(DoutFile));
share.putExtra(Intent.EXTRA_TEXT,
"" + activity.getResources().getString(R.string.app_name));
share.setPackage("com.facebook.katana");
activity.startActivity(share);
}
} catch (Exception e) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
e.printStackTrace();
Toast.makeText(
activity,
activity.getString(R.string.facebookNotInstalled),
Toast.LENGTH_LONG).show();
}
}
}
});
I hope it can help someone too.
Can you add code to show progressbar in onPreExecute in class DownloadToShareClass which extends AsyncTask ?
Please refer to http://developer.android.com/reference/android/os/AsyncTask.html
From the above link --
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
class DownloadToShareClass extends AsyncTask<String, String, String> {
private ProgressDialog mdialog;
public DownloadToShareClass(yourActivity activity) {
mdialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
mdialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void result) {
if (mdialog.isShowing()) {
mdialog.dismiss();
}
}
}
I'm currently working on an android app with web services, using an external database. The app consists of several tasks and each task is assigned to each camera id. Each camera have specific long/lat stored in the database. So right now when I select a specific task, there would be a guide button showing the user current location as a marker in the google map. I want to display the long/lat of the task as a marker on the google map, so there would be 2 marker. Just need some help with the android coding. Any help would be appreciated!
GoogleMapActivity.java
public class GoogleMapActivity extends Activity implements LocationListener {
GoogleMap map;
private String cameraid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_map);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("My Current Location");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
AcceptTask.java
public class AcceptTask extends SherlockActivity {
private static String sendingURL,
url,
imageURL,
dateTimeP,
notificationID,
cameraID;
private String check = null;
// JSON Node names
private static final String TAG_GET = "jobViewResult",
TAG_IMAGEURL = "imageurl",
TAG_MESSAGE = "vmessage",
TAG_GETA = "assignResult",
TAG_STATUS = "assignStatus";
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private TextView tvCamera, tvDate;
private ImageView my_image;
// contacts JSONObject
JSONObject api = null;
private long userInteractionTime = 0;
AsyncTask<Void, Void, Void> mRegisterTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accept_task);
tvCamera = (TextView) findViewById(R.id.tv_CameraID);
tvDate = (TextView) findViewById(R.id.tv_DateR);
my_image = (ImageView) findViewById(R.id.img_Task);
//set the icon clickable
getSupportActionBar().setHomeButtonEnabled(true);
//add an < arrow on the icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
if(isNetworkConnected()){
try{
// getting intent data
Intent intent = getIntent();
/** Get values from previous intent */
dateTimeP = intent.getStringExtra("TAG_IMAGE_TIME_DATE_P");
cameraID = intent.getStringExtra("TAG_CAMERA_ID_P");
notificationID = intent.getStringExtra("TAG_NOTIFICATION_ID");
/** Display cameraID and date time */
tvCamera.setText(cameraID);
tvDate.setText(dateTimeP);
url = "url";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
api = json.getJSONObject(TAG_GET);
check = api.getString(TAG_MESSAGE);
// Storing each json item in variable
imageURL = api.getString(TAG_IMAGEURL);
} catch (JSONException e) {
e.printStackTrace();
}
if(check.equals("Job available")){
new DownloadImageTask().execute(imageURL);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Job Unavailable");
builder.setMessage(check);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{showNetworkErrorDialog();}
}
private void showServerErrorDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Server Error");
builder.setMessage("Server is currently unable to connect. Please check your network connectivity.");
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
private void showNetworkErrorDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setTitle("No Network Connection");
builder.setMessage("Please turn on your mobile 3G or connect to a network in order to use this application.");
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AcceptTask.this.finish();
}
});
builder.setNegativeButton("Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//calling setting menu
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
});
builder.show();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
return false;
} else{
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case android.R.id.home:
if(my_image.getDrawable() != null){
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
}
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return false;
}
#Override
public void onUserInteraction() {
userInteractionTime = System.currentTimeMillis();
super.onUserInteraction();
Log.i("appname","Interaction");
}
#Override
public void onUserLeaveHint() {
long uiDelta = (System.currentTimeMillis() - userInteractionTime);
super.onUserLeaveHint();
if (uiDelta < 100){
Logout();
}
}
#Override
public void onResume() {
super.onResume();
if(isNetworkConnected()){
try{
SharedPreferences checkLogin1 = getApplicationContext().getSharedPreferences( "checklogin", 0);
String staffID = checkLogin1.getString("staffID", "");
String staffPassword = checkLogin1.getString("password", "");
DefaultHttpClient httpClient = new DefaultHttpClient();
//get the unique id
SharedPreferences pref = getApplicationContext().getSharedPreferences( "checklogin", 0);
String checkID = pref.getString("loginRID", "");
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity
.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject svr = new JSONObject(new String(buffer));
JSONObject obj = svr.getJSONObject("loginTestResult");
String validation = obj.getString("valid");
String position = obj.getString("position");
String companyID = obj.getString("companyID");
String messageStatus = obj.getString("message");
if(validation.equals("1")){
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
//mDisplay = (TextView) findViewById(R.id.display);
//gcmIDtxt =(TextView) findViewById(R.id.gcmID);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
System.out.print(regId);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
// if (GCMRegistrar.isRegisteredOnServer(this)) {
// // Skips registration.
// //mDisplay.append(getString(R.string.already_registered) + "\n");
// //gcmIDtxt.setText(regId);
//
// } else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
boolean registered =
ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
// }
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Error");
builder.setMessage(messageStatus + " Please sign in again.");
// Setting Icon to Dialog
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences pref2 = getApplicationContext().getSharedPreferences("checklogin", 0);
final SharedPreferences.Editor editor1 = pref2.edit();
editor1.putInt("login", 0);
editor1.commit();
Intent intent = new Intent(AcceptTask.this, LoginPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{
showNetworkErrorDialog();
}
//runAcceptedTask();
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
//mDisplay.append(newMessage + "\n");
}
};
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private void Logout(){
if(isNetworkConnected()){
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
DefaultHttpClient httpClient = new DefaultHttpClient();
//get the unique id
SharedPreferences pref = getApplicationContext().getSharedPreferences( "checklogin", 0);
String checkID = pref.getString("loginRID", "");
String staffID = pref.getString("staffID", "");
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity
.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject svr = new JSONObject(new String(buffer));
JSONObject obj = svr.getJSONObject("logoutResult");
String messageStatus = obj.getString("userMessage");
if(messageStatus.equals("Updated Successfully!!")){
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Error");
builder.setMessage(messageStatus);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
}
} catch (Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}
else{
showNetworkErrorDialog();
}
}
//accept task button
public void acceptTask(View v) {
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
AlertDialog.Builder builder = new AlertDialog.Builder(AcceptTask.this);
builder.setTitle("Confirm Accept");
builder.setMessage("Are you sure to accept this job?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(isNetworkConnected()){
try{
// Do do my action here
SharedPreferences pref = getApplicationContext().getSharedPreferences(
"checklogin", 0);
String staffID = pref.getString("staffID", "");
//sendingURL = ""+staffID;
sendingURL = "url";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(sendingURL);
try {
api = json.getJSONObject(TAG_GETA);
check = api.getString(TAG_STATUS);
} catch (JSONException e) {
if(e != null) {
showServerErrorDialog();}
}
if(check.equals("Job available")){
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(sendingURL);
try {
HttpResponse response = httpclient.execute(httpget);
Toast.makeText(getApplicationContext(), "You accepted the job.", Toast.LENGTH_SHORT).show();
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
catch (IOException e) {
if(e != null) {
showServerErrorDialog();}
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(AcceptTask.this, R.style.AlertDialogTheme));
builder.setCancelable(false);
builder.setTitle("Job Unavailable");
builder.setMessage(check);
// Setting Icon to Dialog
builder.setIcon(R.drawable.ic_action_error);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
});
builder.show();
}
} catch(Exception e) {
if(e != null) {
showServerErrorDialog();
}
}
}else{
showNetworkErrorDialog();
}
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private class DownloadImageTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
protected String doInBackground(String... urls) {
int count;
try {
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream in = new BufferedInputStream(url.openStream(), 8192);
byte data[] = new byte[1024];
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/LocationSystem/pendingtask_temp.jpg");
long total = 0;
while((count = in.read(data)) != -1){
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
File file = new File(getExternalCacheDir(), "pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}else{
output.write(data, 0, count);
}
}
output.flush();
output.close();
in.close();
} catch (Exception e) {
Log.e("Error", e.getMessage());
if(e != null) {
showServerErrorDialog();
}
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
String imagePath = Environment.getExternalStorageDirectory().toString() + "/LocationSystem/pendingtask_temp.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
if (my_image.getDrawable() == null){
Toast.makeText(AcceptTask.this, "Please select again!",Toast.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//pDialog.setButton("Cancel", (DialogInterface.OnClickListener) null);
pDialog.setButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AcceptTask.this.finish();
}
});
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
#Override
public void onBackPressed() {
if(my_image.getDrawable() != null){
File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg" );
if (file.exists()) {
file.delete();
}
}
Intent loadIntent = new Intent();
loadIntent.putExtra("startUpdate_PList", "start");
setResult(Activity.RESULT_OK, loadIntent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.accept_task, menu);
return true;
}
}
You can do an asynck task to get the DB values and call this task in onlocationchange.
My toast doesn't show up and I am confused because I think I made it correctly, I don't understand. As you can see its a program that shows three buttons, the first one activates a download which is supposed to open the PDFs file automatically - if there is no pdf reader a toast should pop up saying there isn't a reader. the other buttons take to a new screen and operate as a back button.
public class myactivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity);
mProgressDialog = new ProgressDialog(myactivity.this);
mProgressDialog.setMessage("Please be patient, file downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Button Section = (Button) findViewById(R.id.Section);
Section.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent Section = new Intent(view.getContext(),
Section.class);
startActivity(Section);
}
});
Button Back = (Button) findViewById(R.id.Back);
Back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setResult(RESULT_OK);
finish();
}
});
startBtn = (Button) findViewById(R.id.Search);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
DownloadFile downloadFile = new DownloadFile();
downloadFile
.execute("http://www.website.com/document.pdf");
}
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
showPdf();
} catch (Exception e) {
}
return null;
}
}
private void showPdf() {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
}
}
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
The above code show toast only if you have not declared the activity in your manifeast file but not when the pdf is not present. You must use FileNotFoundException for your requirement.
Updated:::
try{
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException e) {
Toast.makeText(myactivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}