How can I show a progress bar when I click a button during the creation of a PDF file and hide it when I finished creating the file?
public class TwoFragment extends android.support.v4.app.Fragment {
private View v;
Intent chooser=null;
String myInt="";
String ciao="";
private String string="";
private ProgressBar pdfProgress;
ProgressTask task;
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
Button mButton = (Button) rootView.findViewById(R.id.newbutton);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//sendemail();
// pdfProgress.setVisibility(View.GONE);
/* pdfProgress.setVisibility(View.VISIBLE);
createPDF();
pdfProgress.setVisibility(View.GONE);
viewPDF();*/
/*MyAsyncTask myTask = new MyAsyncTask();
myTask.execute();
*/
showProgress();
}
});
TextView titolo3 = (TextView)rootView.findViewById(R.id.result);
TextView titolo2 = (TextView)rootView.findViewById(R.id.result2);
TextView titolo4 = (TextView)rootView.findViewById(R.id.resultpizze);
pdfProgress = (ProgressBar)rootView.findViewById(R.id.progressbar);
pdfProgress.setVisibility(View.GONE);
//pdfProgress.setVisibility(View.INVISIBLE);
//TextView titolo = (TextView)rootView.findViewById(R.id.quantità 3);
/* class MyAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// This runs in new thread!!!
// Always run long operations in another thread, so GUI will never be blocked
createPDF();
return null;
}
#Override
protected void onPostExecute(Void v) {
// This runs in MAIN thread, after the job's done.
// You always have to update gui from main thread
pdfProgress.setVisibility(View.GONE);
viewPDF();
}
}
*/
Bundle bundle2=getArguments();
if(bundle2 != null){
string = bundle2.getString("scelta2");
titolo3.setText(string);
}
/* Bundle bundle2=getArguments();
if(bundle2 != null){
// myInt = bundle2.getString("scelta2",myInt);
cacca=bundle2.getString("result",null);
//cacca=myInt;
// Log.d("ciao",cacca);
titolo3.setText(cacca);
}*/
//titolo3.setText(myInt);
/* Bundle bundle3=getArguments();
if(bundle3 != null){
// String myInt3 = bundle3.getString("totalebirre", null);
// cazzo2=Integer.parseInt(myInt3);
int cazzo2=bundle3.getInt("totalebirre");
titolo2.setText(String.valueOf(cazzo2));
}
Bundle bundle=getArguments();
if(bundle != null){
// String myInt2 = bundle2.getString("totalepizze", null);
// cazzo=Integer.parseInt(myInt2);
//titolo2.setText(myInt2);
String string=bundle.getString("scelta3", null);
titolo4.setText(string);
}
*/
return rootView;
}
/* public void sendemail(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse("mailto:"));
String[] to={"marco_marcoletto#hotmail.it"};
intent.putExtra(Intent.EXTRA_EMAIL,to);
intent.putExtra(Intent.EXTRA_SUBJECT, "ciao");
intent.putExtra(Intent.EXTRA_TEXT, "zao");
intent.setType("message/rfc822");
chooser=intent.createChooser(intent,"manda email");
startActivity(chooser);
}*/
//#TargetApi(Build.VERSION_CODES.M)
public void createPDF() {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/droidText";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
//File file = new File(dir, "sample.pdf");
File file = new File(dir, "salve.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
// open the document
doc.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.androtuto);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
Paragraph p1 = new Paragraph(string);
Font paraFont = new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
// add paragraph to document
doc.add(p1);
Paragraph p2 = new Paragraph("Bonjour Android Tuto");
Font paraFont2 = new Font(Font.COURIER, 14.0f, Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);
doc.add(p2);
stream = new ByteArrayOutputStream();
bitmap = BitmapFactory.decodeResource(getContext()
.getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
// add image to document
doc.add(myImg);
// set footer
Phrase footerText = new Phrase("Pied de page ");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
} catch (DocumentException de) {
// Log.e("PDFCreator", "DocumentException:" + de);
Log.e("PDFCreator", "DocumentException:" + de.getMessage());
} catch (IOException e) {
// Log.e("PDFCreator", "ioException:" + e);
Log.e("PDFCreator", "DocumentException:" + e.getMessage());
} finally {
doc.close();
}
}
public void viewPDF(){
String path = "/sdcard/droidText/salve.pdf";
File targetFile = new File(path);
Uri targetUri = Uri.fromFile(targetFile);
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
startActivity(intent);
}
private class ProgressTask extends AsyncTask<Integer,Integer,Void> {
protected void onPreExecute() {
pdfProgress.setMax(100); // set maximum progress to 100.
}
protected void onCancelled() {
pdfProgress.setMax(0); // stop the progress
}
protected Void doInBackground(Integer... params) {
int start=params[0];
for(int i=start;i<=100;i+=5){
try {
boolean cancelled=isCancelled();
if(!cancelled) {
publishProgress(i);
Log.v("Progress","increment " + i);
//onProgressUpdate(i);
SystemClock.sleep(1000);
}
createPDF();
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
return null;
}
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
//setProgress(10);
}
protected void onPostExecute(Void result) {
// async task finished
Log.v("Progress", "Finished");
viewPDF();
}
}
public void showProgress() {
task = new ProgressTask();
// start progress bar with initial progress 10
///////////////////task.execute(10,10,null);
task.execute(10);
}
}
Define a ProgressDialog in your Fragment as follows. The following code will add a ProgessDialog; to update it to show a Progress Bar too, read this.
private ProgressDialog processingDialog;
Now, in your onClick()
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
processingDialog = ProgressDialog.show(this, "Creating PDF", "Please wait ...", true, false);
createPDF();
processingDialog.dismiss();
viewPDF();
}
});
This should do the task, however, I have some more recommendations for you. As creating a PDF (I assume) will be time consuming, it might not be a good idea to do it on the UI Thread. Instead, use an AsyncTask to generate your PDF in doInBackground(), show the ProgressDialog, and finally dismiss() it in onPostExecute().
This code will do what you want using AsyncTask which is reccomended way of doing this!
private class MakePDF extends AsyncTask<Void, Void, Void> {
private ProgressDialog processingDialog;
Context cnt = null;
MakePDF(Context cnt)
{
this.cnt = cnt;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
processingDialog = ProgressDialog.show( this.cnt, "Creating PDF", "Please wait ...", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
createPDF();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
processingDialog.dismiss();
viewPDF();
}
}
Now call above AsyncTask using
new MakePDF(ActivityName.this).execute(); //here in constructor pass context of an calling activity.
from your activity class
Related
In my application, I have an expandablelistview and I want to open a PDF downloaded from the internet when I click on a specific child. The problem is that the pdf file (Read.pdf) is always empty, meaning that the download is not working.
Downloader Class:
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Part of the Activity:
private void registerClick() {
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if ((groupPosition == 0) && (childPosition == 0)){
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE", "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf", file);
AbrirPDF.showPdf();
} else {
}
return false;
}
});
}
I think the OpenPDF (AbrirPDF) doesn't have any problem, but I will post it...
public class AbrirPDF {
public static void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE/Read.pdf");
PackageManager packageManager = ContextGetter.getAppContext().getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ContextGetter.getAppContext().startActivity(intent);
}
}
Thank you.
Ideally, your download should happen in a separate thread to avoid locking your app.
Here is an example that also includes a progress bar.
public class MainActivity extends Activity {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute(file_url);
}
#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.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/2011.kml");
byte data[] = new byte[1024];
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;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}
This is my activity code, when click on capture picture button, it will load camera from your phone. after i take a picture with camera, the picture will show at the imageView. Then i will click upload image picture button to upload my picture to server. Here the problem i faced, the code works well on all android version 4.4 and below, when i test this code with android 5.0, the picture taken from camera wasn't show on the imageView. I had tried many solution and yet keep fail. Can anyone help me with this? thank you.
Activity code
public class TestUpload extends Activity implements OnItemSelectedListener {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello camera";
private Uri fileUri;
private ImageView imgPreview;
private Button btnCapturePicture, btnUploadImage;
private EditText itemname;
private EditText description;
private EditText price;
private EditText contact;
private String randNum, uname;
Random random = new Random();
private static final String _CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int RANDOM_STR_LENGTH = 12;
private Spinner spinCat, spinLoc;
private String [] Category = {"IT Gadgets","Men Fashion","Women Fashion","Beauty","Sports","Cars and Motors","Furnitures","Music Instrument","Books","Property","Photography","Games and Toys","kids and Baby","Others"};
private String [] Location = {"Kuala Lumpur","Melacca","Johor","Selangor","Kelantan","Kedah","Negeri Sembilan",
"Pahang","Perak","Perlis","Penang","Sabah","Sarawak","Terengganu"};
private static final String TAG_SUCCESS = "success";
JSONParser2 jsonParser2 = new JSONParser2();
private static String url_create_image = "http://gemini888.tk/GP_trade_api_v2/image_connect/create_product.php";
private SweetAlertDialog pDialog;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_test);
ActionBar ab = getActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#96ead7")));
ab.setDisplayHomeAsUpEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
btnCapturePicture = (Button) findViewById(R.id.btn_camera);
btnUploadImage = (Button) findViewById(R.id.btn_upload);
itemname = (EditText) findViewById(R.id.input_upload_item_name);
description = (EditText) findViewById(R.id.input_item_desc);
price = (EditText) findViewById(R.id.upload_input_item_price);
contact = (EditText) findViewById(R.id.input_contact);
spinCat = (Spinner) findViewById(R.id.spin_category);
spinLoc = (Spinner) findViewById(R.id.spin_location);
ArrayAdapter<String> adapter_Category = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Category);
ArrayAdapter<String> adapter_Location = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Location);
adapter_Category.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter_Location.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCat.setAdapter(adapter_Category);
spinLoc.setAdapter(adapter_Location);
spinCat.setOnItemSelectedListener(this);
spinLoc.setOnItemSelectedListener(this);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();
uname = user.get("uname");
//timeStamp = new SimpleDateFormat ("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
randNum = getRandomString();
//capture image button click event
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//capture image
captureImage();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//uploading the file to server
new UploadFileToServer().execute();
}
});
}
//capturing Camera image will lunch camera app request image capture
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Start image capture intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
//Receiving activity result method will be called after closing the camera
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//if the result i capture image
if(requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
//success capture image, display it on imageview
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
//user cancel image capture
Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
//failed to capture image
Toast.makeText(getApplicationContext(), "Sorry, failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
//Display image from a path to imageview
private void previewCapturedImage() {
imgPreview.setVisibility(View.VISIBLE);
//bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
//downsize image as it throws Outofmemory execption for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
//store the file url as it will be null after returning from camera app
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save file url in bundle as it will be null on screen orientation change
outState.putParcelable("file_uri", fileUri);
}
//restore the fileUri again
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get the Urifile
fileUri = savedInstanceState.getParcelable("file_uri");
}
//create file Uri to store image
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
//returning image
private File getOutputMediaFile(int type) {
//External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), UserFunctions.IMAGE_DIRECTORY_NAME);
//create the storage directory if it does not exist
if(!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Failed create" + UserFunctions.IMAGE_DIRECTORY_NAME + "directory");
return null;
}
}
//Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + uname + randNum + ".jpg");
} else {
return null;
}
return mediaFile;
}
//upload image to server
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new SweetAlertDialog(TestUpload.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Picture uploading, please wait..");
//pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void...params) {
String iname = itemname.getText().toString();
String des = description.getText().toString();
String iprice = price.getText().toString();
String icontact = contact.getText().toString();
String cat = spinCat.getSelectedItem().toString();
String loc = spinLoc.getSelectedItem().toString();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("name", iname));
param.add(new BasicNameValuePair("description", des));
param.add(new BasicNameValuePair("price", iprice));
param.add(new BasicNameValuePair("username", uname));
param.add(new BasicNameValuePair("category", cat));
param.add(new BasicNameValuePair("location", loc));
param.add(new BasicNameValuePair("timestamp", randNum));
param.add(new BasicNameValuePair("contact", icontact));
JSONObject json = jsonParser2.makeHttpRequest(url_create_image,
"POST", param);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Log.d("Create Response", "success");
} else {
// failed to create product
Toast.makeText(getApplicationContext(),"failed",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return uploadFile();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
}
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(UserFunctions.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
setProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(fileUri.getPath());
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("http://gemini888.tk"));
entity.addPart("email", new StringBody("thegemini888#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
public String getRandomString() {
StringBuffer randStr = new StringBuffer();
for (int i =0; i<RANDOM_STR_LENGTH; i++) {
int number = getRandomNumber();
char ch = _CHAR.charAt(number);
randStr.append(ch);
}
return randStr.toString();
}
private int getRandomNumber() {
int randomInt = 0;
randomInt = random.nextInt(_CHAR.length());
if (randomInt - 1 == -1) {
return randomInt;
} else {
return randomInt - 1;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinCat.setSelection(position);
String CatList = (String) spinCat.getSelectedItem();
CatList.toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
in captureImage() method try this.
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
//Start image capture intent
}
//first of all create a directory to store your captured Images
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/PGallery");
if (!myDir.exists()) {
myDir.mkdirs();
}
//Give name to your captured Image
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss",java.util.Locale.getDefault());
Date date = new Date();
String sDate = formatter.format(date);
imageName = "PRAVA"+sDate+".jpg";
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
filePath = new File(myDir,imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePath));
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
catch (ActivityNotFoundException e) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
On Actvity Result:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
ImagePath = filePath.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(ImagePath, bitmapOptions);
ImageView mImageView = (ImageView) findViewById(R.id.ivCamreaPic);
mImageView.setImageBitmap(bitmap);
}
I have created a simple Activity. The activity is responsible for downloading data from parse.com database and populating a linear layout. In the process, I am dynamically creating the linear layout with TextViews and ImageViews according according to the content.
The problem is that, whenever I try to download an image, I use as AsyncTask Downloading class, which results in slowing down the UI thread! I am currently trying to return the bitmap file from the AsyncTask Image downloading class using: returnedBitmap = new LoadImage().execute(src).get(); which might be responsible for slowing down the UI thread. I have to do this because the caller method geneterImageView will return an imageview when it receives the bitmap file.
The complete Activity code:
public class MainActivity extends ActionBarActivity {
ArrayList<String> heightList = new ArrayList<String>();
ArrayList<String> reversedList = new ArrayList<String>();
ImageView imageView1;
Bitmap bitmap;
RelativeLayout parent_layout;
ParseObject user;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// imageView1 = (ImageView)findViewById(R.id.imageView1);
parent_layout = (RelativeLayout) findViewById(R.id.parent_layout);
login("xyz#xyz.com", "xyz");
}
private void loopThroughArrayAndAttach(){
LinearLayout llInner = new LinearLayout(this);
llInner.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
parent_layout.addView(llInner);
for (int i = 0; i < heightList.size(); i++) {
if (hasNoImagess(heightList.get(i)) == true) {
// No images.
TextView myText = geneterTextView(heightList.get(i));
llInner.addView(myText);
// geneterTextView(heightList.get(i));
} else {
ImageView myImage = geneterImageView(heightList.get(i));
llInner.addView(myImage);
// geneterImageView(heightList.get(i));
}
}
}
public static boolean hasNoImagess(String contents){
Document doc = Jsoup.parse(contents);
Element element = doc.body();
Elements elements = element.select("img");
if (elements.isEmpty()) {
return true;
} else {
return false;
}
}
public ImageView geneterImageView(String imgContent){
// Will need to run via background thread - like aysnc
// Extract the image file via jsoup
// Insert it into a imagevieww
// Inser that into a layout.
Log.d("IN IMAGE ", " " + imgContent);
Document doc = Jsoup.parse(imgContent);
Elements img = doc.getElementsByTag("img");
Bitmap returnedBitmap = null;
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("src attribute is : " + src);
// new DownloadImageTask((ImageView)
// findViewById(R.id.imageView1)).execute(src);
try {
returnedBitmap = new LoadImage().execute(src).get();
// imageView1.setImageBitmap(returnedBitmap);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageView iv = new ImageView(this);
iv.setImageBitmap(returnedBitmap);
return iv;
}
public TextView geneterTextView(String textContent){
// Will need to run via background thread.
Log.i("In TEXT ", " " + textContent);
TextView tv = new TextView(this);
tv.setText(Html.fromHtml(textContent));
return tv;
}
// to download images
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
protected Bitmap doInBackground(String... args){
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image){
if (image != null) {
} else {
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
// to login to parse
private void login(final String username, String password){
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e){
if (e == null) {
// if login sucess
// Start intent
// loginSuccess();
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
CloudCallStudentPosts(user);
} else {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
}
});
}
// //to get data from parse
public void CloudCallStudentPosts(ParseObject s){
setRichStory(s);
}
private void setRichStory(ParseObject s){
// Simialr to setStory, once implemented delete setStory()
new AddStoryAsync(s).execute();
}
class AddStoryAsync extends AsyncTask<Void, Object, Void> {
private static final String TAG = "LazyListView";
ParseObject s;
public AddStoryAsync(ParseObject s) {
this.s = s;
Log.w("In richStory", "ParseObject Id: " + s.getObjectId());
}
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... unused){
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userid", this.s.getObjectId());
params.put("skip", 0);
ParseCloud.callFunctionInBackground("studentsPosts", params, new FunctionCallback<List<List<ParseObject>>>() {
#Override
public void done(List<List<ParseObject>> postList, com.parse.ParseException arg1){
if (postList == null) {
} else {
if (postList.size() > 0) {
// CustomWebView cwb;
for (int i = 0; i < postList.size(); i++) {
// final Post post = new Post();
if (postList.get(i).get(0).get("htmlContent") == null) {
}
if (postList.get(i).get(0).get("htmlContent") != null) {
Log.e("htmlContent parse", postList.get(i).get(0).get("htmlContent").toString());
// Parse HTML String using JSoup library
String HTMLSTring = postList.get(i).get(0).get("htmlContent").toString();
Document html = Jsoup.parse(HTMLSTring);
Elements paragraphs = html.getElementsByTag("p");
for (org.jsoup.nodes.Element paragraph : paragraphs) {
String paragraphText = paragraph.toString();
Log.e("paragraphText", paragraphText);
heightList.add(paragraphText);
}
loopThroughArrayAndAttach();
}
}
}
}
}
});
return (null);
}
#Override
protected void onProgressUpdate(Object... object){
Log.w("onProgressUpdate ", " " + object[0].getClass());
Log.w("adding to arrayPostList ", " " + object[0].getClass());
}
#Override
protected void onPostExecute(Void unused){
}
}
}
Is there any substitute for getting the bitmap from the AsyncTask and set it in the imageview? Should there be a logical alteration in the approach?
try this :
dont call get() #praveen. instead pass the imageview Reference in the constructor
WorkerThread mWorkerThread = new WorkerThread(mImageView);
mWorkerThread.execute(src);
private class WorkerThread extends AsyncTask<String, String, Bitmap> {
private WeakReference<ImageView> imageViewReference;
public WorkerThread(ImageView imageView) {
super();
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... args) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null && imageViewReference.get() != null) {
imageViewReference.get().setImageBitmap(result);
}
}
}
Don't call get() method on AsyncTask it makes main thread to wait for AsyncTask to complete. If you really want to start something only after AsyncTask completes put that into onPostExecute() of your AsynTask
As others have mentioned, your code has several design flaws which makes it difficult to provide you a solution to your problem.
The whole purpose of an AsyncTask is to execute on a background thread. Executing networking and bitmap processing on the main thread will never work. You must refactor your code to accommodate this. Consider the following solution to this particular problem at least:
// to download images
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... args) {
String imgContent = args[0];
Document doc = Jsoup.parse(imgContent);
Elements img = doc.getElementsByTag("img");
for (Element el : img) {
String src = el.absUrl("src");
System.out.println("src attribute is : " + src);
try {
return BitmapFactory.decodeStream((InputStream) new URL(src).getContent());
} catch (Exception e) {
// log
}
}
return null;
}
protected void onPostExecute(Bitmap b) {
ImageView iv = new ImageView(MainActivity.this);
iv.setImageBitmap(b);
llInner.addView(iv);
}
}
You can then do something like:
for (int i = 0; i < heightList.size(); i++) {
new LoadImage(heightList.get(i)).execute();
}
However, this may not be desirable depending on how many AsyncTasks you end up creating. But this is the idea.
My application pulls data from a web service that generates different sections for each user. Then I am going to use these sections to create tabs using FragmentPagerAdapter.
I have used an Async task to pull data from the web service. However the overridden methods such as getCount() and getPageTitle() in the FragmentPagerAdapter executed prior to my asynctask and completes its job. How can I prevent this and generate dynamic number of tabs and their title name based on the data fetched from the web service?
In other words how can I create dynamic number of tabs and titles based on the data fetch from the web service
My Code for FragmentPagerAdapter as below. As you can see I have hard coded the amount of tabs as well as their title names.
public class SectionsPagerAdapter extends FragmentPagerAdapter{
private boolean proceedStatus = false;
private String requestURL = "xxxxxxxxxxxxxxxxxxxxxxxx";
//list of fragments need to be added dynamically
public final ArrayList<Fragment> screens = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new SectionFragment();
Bundle args = new Bundle();
args.putInt(SectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Camera".toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return "SECTION 4";
}
return null;
}
//setting the section title
private void setSectionTitle(){
}
//count the number of sections
private int countNumberofSections(){
int numberOfSection = 0;
return numberOfSection;
}
}
Then I have my Fragment code as below which has the the caller to the Async Task
public static class SectionFragment extends Fragment implements OnTaskCompleted {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private Slider adapter;
private ViewPager viewPager;
public static final String ARG_SECTION_NUMBER = "section_number";
Button thumbUpBut;
Button thumbDownBut;
Button captureButton;
ImageView genImage;
TextView genCaption;
private Camera mCamera;
private CameraPreview mPreview;
private static File mediaFile;
private ProgressDialog progress;
private static String imageSaveLocation;
private static String file_name_without_extension;
private ImageView imageView;
private Button uploadButton;
private Button cancelButton;
private Collection<Place> places = null;
private Collection<Happenings> events = null;
private Collection<General> general = null;
private ArrayList<String> sections;
public int getNumberOfPages(){
return sections.size();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
FeedRequest task = new FeedRequest(this);
task.execute("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
captureButton = (Button) rootView.findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
thumbUpBut = (Button) rootView.findViewById(R.id.thumbUp);
thumbUpBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("thumbPress", "thumbPressUp");
thumb("up");
}
});
thumbDownBut = (Button) rootView.findViewById(R.id.thumbDown);
thumbDownBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("thumbPress", "thumbPressDown");
thumb("down");
}
});
//allocating the activity one to the camera
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
mCamera = getCameraInstance();
mPreview = new CameraPreview(this.getActivity(), mCamera);
FrameLayout preview = (FrameLayout)rootView.findViewById(R.id.camera_preview);
preview.addView(mPreview);
//hide buttons
thumbDownBut.setVisibility(rootView.INVISIBLE);
thumbUpBut.setVisibility(rootView.INVISIBLE);
}else{
thumbDownBut.setVisibility(rootView.VISIBLE);
thumbUpBut.setVisibility(rootView.VISIBLE);
captureButton.setVisibility(rootView.INVISIBLE);
}
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
return rootView;
}
//take photo function
private void takePhoto() {
//get coordinates of the location
UserLocation userLocation = new UserLocation();
userLocation.getUserLocation(getActivity());
coordinates[0] = userLocation.longitude;
coordinates[1] = userLocation.latitude;
PictureCallback pictureCB = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera cam) {
new SavePhotoAndMetadata().execute(data);
cam.startPreview();
}
};
mCamera.takePicture(null, null, pictureCB);
}
//get camera instance
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
//get the media out
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
file_name_without_extension = "IMG_" + timeStamp;
imageSaveLocation = mediaFile.toString();
return mediaFile;
}
//saving the image and metadata together
class SavePhotoAndMetadata extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... data) {
File picFile = getOutputMediaFile();
if (picFile == null) {
return null;
}
byte[] photoData = data[0];
try {
//save the image
FileOutputStream fos = new FileOutputStream(picFile);
fos.write(photoData);
fos.close();
} catch (FileNotFoundException e) {
e.getStackTrace();
} catch (IOException e) {
e.getStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Saving Picture..Please wait...");
progress.show();
}
#Override
protected void onPostExecute(String s) {
progress.dismiss();
imagePreviewDialog();
}
}
//save image metadata in async task
class SaveMetadataTask extends AsyncTask<Void, String, Void> {
#Override
protected Void doInBackground(Void... params) {
serializeDeserialize.serializeData("This is for testing", file_name_without_extension, Double.toString(coordinates[0]), Double.toString(coordinates[1]), deviceId, deviceEmail);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void v) {
}
}
//image preview dialog and its functionality
private void imagePreviewDialog(){
//setting the bitmap
Bitmap bmp = BitmapFactory.decodeFile(mediaFile.toString());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Image Preview");
builder.setCancelable(false);
LayoutInflater inflater = getActivity().getLayoutInflater();
ViewGroup vg = (ViewGroup)inflater.inflate(R.layout.sanp_preview_layout, null);
ImageView image = (ImageView) vg.findViewById(R.id.imageView);
image.setImageBitmap(rotateBitmap(bmp));
builder.setView(vg);
//buttons
builder.setPositiveButton("Upload",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(checkInternetConnection.haveNetworkConnection(sContext)){
//upload the image
uploadImage();
//save image metadata
new SaveMetadataTask().execute();
}else{
Toast.makeText(sContext, "Error! No internet connection detected. Image will be uploaded on an active internet connection", Toast.LENGTH_LONG).show();
new SaveMetadataTask().execute();
}
}
});
builder.setNegativeButton("Discard",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
discardImage(mediaFile.toString());
dialog.dismiss();
}
});
builder.show();
}
private Bitmap rotateBitmap(Bitmap image){
int width=image.getHeight();
int height=image.getWidth();
Bitmap srcBitmap=Bitmap.createBitmap(width, height, image.getConfig());
for (int y=width-1;y>=0;y--)
for(int x=0;x<height;x++)
srcBitmap.setPixel(width-y-1, x,image.getPixel(x, y));
return srcBitmap;
}
//device email
private String getDeviceEmail(){
AccountManager accountManager = AccountManager.get(sContext);
Account[] account = accountManager.getAccountsByType("com.google");
//device email
for(Account accLoop : account){
deviceEmail = accLoop.name;
}
return deviceEmail;
}
//upload image to the server
private void uploadImage(){
//save metadata
//call upload service
Intent intent = new Intent(sContext, HttpUploader.class);
Bundle loc = new Bundle();
loc.putDoubleArray("ss", coordinates);
intent.putExtra("url", PHOTO_UPLOAD);
intent.putExtra("paths", mediaFile.toString());
intent.putExtra("deviceid", deviceId);
intent.putExtra("deviceemail", getDeviceEmail());
intent.putExtra("posttext", "This is for testing");
intent.putExtra("filename", file_name_without_extension);
intent.putExtra("geo", loc);
sContext.startService(intent);
Toast.makeText(getActivity(), "Your image is being uploaded", Toast.LENGTH_LONG).show();
}
//discard image when the discard button is pressed
private void discardImage(String imagePath){
File file = new File(imagePath);
try{
file.delete();
}catch(Exception e){
Log.e("IMAGE_DELETION_ERROR", e.toString());
}
}
#Override
public void onTaskCompleted(boolean status, String message) {
// TODO Auto-generated method stub
Log.e("onTaskCompleted", "success" + status);
if (message == "tumb UP success") {
thumbUpBut.setSelected(true);
thumbDownBut.setSelected(false);
Log.e("tumb", "tumb");
} else if (message == "tumb DOWN success") {
thumbDownBut.setSelected(true);
thumbUpBut.setSelected(false);
Log.e("tumb", "tumb");
}
}
//listener for fetching main objects
#Override
public void onFeedCompleted(ArrayList<Posts> postArray, Multimap<String, Object> multiMap) {
// TODO Auto-generated method stub
numberOfPages = postArray.size();
adapter = new Slider(getActivity(), postArray, getContext());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(postArray.size());
//saving the keyset
Set<String> keys = multiMap.keySet();
sections = new ArrayList<String>();
//sorting the categories and creating the category list
for(String key:keys){
//getting category list
if(!sections.contains(keys)){
sections.add(key);
}
//sorting categories
if(key.equals("Place")){
places.add((Place) multiMap.get(key));
}else if(key.equals("Events")){
events.add((Happenings) multiMap.get(key));
}else if(key.equals("General")){
general.add((General) multiMap.get(key));
}
}
}
//adding the pages to the adaptor dynamically
public void addPagesDynamically(){
}
}
//create the parent directory
private void createParentDiectory(){
File dir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap");
if(!(dir.exists() && dir.isDirectory())) {
dir.mkdirs();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_post:
openPost();
return true;
case R.id.action_settings:
// openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openPost() {
/*
Intent i = new Intent(getApplicationContext(), PhotoActivity.class);
startActivity(i);
*/
}
public static void thumb(String type) {
SectionFragment d = new SectionFragment();
PostThumb task = new PostThumb(type, d);
task.execute("xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
//broadcast receiver for picture upload
public class MyWebRequestReceiver extends BroadcastReceiver {
public static final String PROCESS_RESPONSE = "asia.ceynet.intent.action.PROCESS_RESPONSE";
#Override
public void onReceive(Context context, Intent intent) {
//String responseString = intent.getStringExtra(HttpUploader.RESPONSE_STRING);
String reponseMessage = intent.getStringExtra(HttpUploader.RESPONSE_MESSAGE);
String responseStatus = intent.getStringExtra(HttpUploader.RESPONSE_STATUS);
String file_to_be_deleted = intent.getStringExtra(HttpUploader.FILE_NAME_WITHOUT_EXTENSION);
Toast.makeText(getApplicationContext(), reponseMessage + " - " + file_to_be_deleted + ".jpg", Toast.LENGTH_LONG).show();
//if uploaded successfully delete or image and metadata
if(responseStatus.equals("true")){
File temp_image_dir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img/" + file_to_be_deleted + ".jpg");
File metadata_file = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img/" + file_to_be_deleted + ".ser");
try{
temp_image_dir.delete();
metadata_file.delete();
}catch(Exception e){
Log.e("IMAGE_DELETION_ERROR", e.toString());
}
}
}
}
When you finnish pulling the async data, provide the adapter with the new data and call .notifyDataSetChanged() on that adapter instance and the framework will update the pages and count by itself.
If you wish a more detailed explanation post your FragmentPagerAdapter implementation.
First of all, let me apologize if I'm not making myself clear enough because this is one of my first participation(s) here. But I'll be always here to answer queries related to this answer and clear any confusions arose by my statements.
Since you're using fragments, so I'm assuming you must have included your fragments inside an activity (lets say MainActivity.java).
What you need, can be done inside that activity containing fragment.
Here is the example code of onCreate method inside the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
//Instance of viewpager included inside activity_main.xml
viewPager = (ViewPager) findViewById(R.id.vpMain);
SectionsPagerAdapter adapter = new SectionsPagerAdapter (fragmentManager);
//Adding some fragments right from the beginning, you could ignore it if not needed.
addFragments();
//This `OnPageChangeListener` will do the trick for you.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//Show the title of fragment
Toast.makeText(MainActivity.this, adapter.screens.get(position), Toast.LENGTH_SHORT).show();
//If fragment being loaded is later than the first one,
// then add one more fragment after the last fragment to the adapter.
// integer currentPosition is declared as a field, outside onCreate method and initially set to 0.
if(position>currentPosition){
currentPosition+=1;
adapter.addFragment(new SectionFragment(), "Fragment"+String.valueOf(position+3));
adapter.notifyDataSetChanged();
}else{
currentPosition--;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
} // onCreate ends here.
Create this method inside your MainActivity (just to add 3 fragments to give your application a head-start.
private void addFragments(){
adapter.addFragment(new SectionFragment());
adapter.addFragment(new SectionFragment());
adapter.addFragment(new SectionFragment());
}
Then modify your SectionsPagerAdapter's getItem and getCount methods as below:
public class SectionsPagerAdapter extends FragmentPagerAdapter{
private boolean proceedStatus = false;
private String requestURL = "xxxxxxxxxxxxxxxxxxxxxxxx";
//list of fragments need to be added dynamically
public final ArrayList<Fragment> screens = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return screens.get(position);
}
#Override
public int getCount() {
return screens.size();
}
//This method will dynamically add a fragment each time it is called.
public void addFragment(Fragment fragment) {
screens.add(fragment);
}
Now, no work related to "adding new fragment to the list" needs to be done inside your SectionFragment class.
How can I make my spinner not start automatically? I have seen a few solutions on here but they confused me. When the activity starts the download starts immediately and that is not what needs to happen. How can I allow the user to make the selection instead of it downloading the first item automatically?
Here is the code:
public class SpinnerActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
Spinner spDownloadFrom;
private ArrayAdapter<CharSequence> spinnerArrayAdapter;
String url[] = {
"http://www.becker.cl/bases.pdf",
"http://www.pitt.edu/documents/campusmap0607.pdf",
"http://www.aara.ca/reg3317/web_page_doc.pdf",
"http://www.dataprotection.ie/documents/guidance/GuidanceFinance.pdf",
"http://www.fmbb2012.com/JumpingQualifica1.pdf",
"http://www.consulatdumaroc.ca/coloniefh22012.pdf",
"http://www.rgrdlaw.com/media/cases/140_Complaint.pdf" };
String name[] = {"bases.pdf", "campusmap0607.pdf", "web_page_doc.pdf",
"GuidanceFinance.pdf", "JumpingQualifica1.pdf",
"coloniefh22012.pdf", "140_Complaint.pdf", };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgressDialog = new ProgressDialog(SpinnerActivity.this);
mProgressDialog.setMessage("Please be patient, file downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
spDownloadFrom = (Spinner) findViewById(R.id.Spinner01);
spinnerArrayAdapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, name);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spDownloadFrom.setAdapter(spinnerArrayAdapter);
spDownloadFrom.setOnItemSelectedListener(new SpinnerListener(
spDownloadFrom));
}
public class SpinnerListener implements OnItemSelectedListener {
Spinner sp;
public SpinnerListener(View v) {
sp = (Spinner) findViewById(v.getId());
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int arg2,
long arg3) {
// Call to download class
startDownload(arg2);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
private void startDownload(int position) {
DownloadFile downloadFile = new DownloadFile(position);
downloadFile.execute(url[position]);
}
class DownloadFile extends AsyncTask<String, Integer, String> { // put your
// download
// code
private int position;
public DownloadFile(int position) {
this.position = position;
}
#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, name[position]);
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();
mProgressDialog.dismiss();
} catch (Exception e) {
Log.e("Spinner", "exception", e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("Downloading", progress[0]);
}
#Override
protected void onPostExecute(String unused) {
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files/"
+ name[position]);
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(SpinnerActivity.this,
"No Application Available to View PDF",
Toast.LENGTH_LONG).show();
}
}
}
}
Try this code
public class SpinnerActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
Spinner spDownloadFrom;
private ArrayAdapter<CharSequence> spinnerArrayAdapter;
String url[] = {
"http://www.becker.cl/bases.pdf",
"http://www.pitt.edu/documents/campusmap0607.pdf",
"http://www.aara.ca/reg3317/web_page_doc.pdf",
"http://www.dataprotection.ie/documents/guidance/GuidanceFinance.pdf",
"http://www.fmbb2012.com/JumpingQualifica1.pdf",
"http://www.consulatdumaroc.ca/coloniefh22012.pdf",
"http://www.rgrdlaw.com/media/cases/140_Complaint.pdf" };
String name[] = { "bases.pdf", "campusmap0607.pdf", "web_page_doc.pdf",
"GuidanceFinance.pdf", "JumpingQualifica1.pdf",
"coloniefh22012.pdf", "140_Complaint.pdf", };
private boolean checkFlag = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgressDialog = new ProgressDialog(SpinnerActivity.this);
mProgressDialog.setMessage("Please be patient, file downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
spDownloadFrom = (Spinner) findViewById(R.id.Spinner01);
spinnerArrayAdapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, name);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spDownloadFrom.setAdapter(spinnerArrayAdapter);
SpinnerListener spListener = new SpinnerListener();
spDownloadFrom.setOnItemSelectedListener(spListener);
}
public class SpinnerListener implements OnItemSelectedListener {
public SpinnerListener() {
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
if(checkFlag){
startDownload(position);
}
checkFlag = true;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
private void startDownload(int position) {
DownloadFile downloadFile = new DownloadFile(position);
downloadFile.execute(url[position]);
}
class DownloadFile extends AsyncTask<String, Integer, String> { // put your
// download
// code
private int position;
public DownloadFile(int position) {
this.position = position;
}
#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, name[position]);
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();
mProgressDialog.dismiss();
} catch (Exception e) {
Log.e("Spinner", "exception", e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("Downloading", progress[0]);
}
#Override
protected void onPostExecute(String unused) {
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files/"
+ name[position]);
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(SpinnerActivity.this,
"No Application Available to View PDF",
Toast.LENGTH_LONG).show();
}
}
}
}