I have an image store in the firebase realtime db as a url. I am trying to download the image and display the image in an alert dialog message. When excuting the code the alert dialog appears but no image is displayed.
ImageDownloader Class:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageDownload extends AsyncTask<String, Void, Bitmap>
{
private final WeakReference<ImageView> imageViewWeakReference;
public ImageDownload(ImageView imageView)
{
imageViewWeakReference = new WeakReference<>(imageView);
}
#Override
protected Bitmap doInBackground(String... string)
{
return downloadBitmap(string[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap)
{
if(isCancelled())
{
bitmap = null ;
}
ImageView imageView = imageViewWeakReference.get();
if (imageView != null)
{
if (bitmap != null)
{
imageView.setImageBitmap(bitmap);
}
}
}
private Bitmap downloadBitmap(String url)
{
HttpURLConnection connection = null;
try
{
URL url1 = new URL(url);
connection = (HttpURLConnection) url1.openConnection();
int StatusCode = connection.getResponseCode();
if(StatusCode != connection.HTTP_OK)
{
return null;
}
InputStream inputStream = connection.getInputStream();
if(inputStream != null)
{
return BitmapFactory.decodeStream(inputStream);
}
}
catch (Exception e)
{
connection.disconnect();
}
finally
{
if(connection != null)
{
connection.disconnect();
}
}
return null;
}
}
I created a layout xml file for the alert dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/dialog_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
btVoucher1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
String qrcode = dataSnapshot.child("Voucher").child("1").getValue().toString();
Toast.makeText(getActivity(), qrcode, Toast.LENGTH_LONG).show();
AlertDialog.Builder alertVoucher1 = new AlertDialog.Builder(getContext());
alertVoucher1.setNeutralButton("Close",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
new ImageDownload(qrCodeVoucher).execute(qrcode);
AlertDialog voucher = alertVoucher1.create();
voucher.show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
});
Can anyone provide any help? Thank you.
Here I could see you are parallelly loading the image on async task , which may take some time to download the image and before that you have called the alert dialog. So before the image comes up alert is shown.
Solution : You can call of alert dialog shown from the postExecute() of asyncTask , that will work perfectly.
you have created a Layout for that but you didn't use it anywhere I think you are new here whatever you are doing can be done by using a Dialog and Not by using an AlertDialog Here I am giving you an example :
// Create a custom dialog object
final Dialog dialog = new Dialog(getContext());
// Include dialog.xml file
dialog.setContentView(R.layout.your_dialg_layout);
// Set dialog title
dialog.setTitle("Custom Dialog");
// set values for custom dialog components - text, image or button
ImageView image = dialog.findViewById(R.id.your_imageview_id);
// image.setImageResource(R.drawable.image0);
now, Instead of creating an AsyncTask I suggest you to Use Glide or Picasso (libraries to load URLs in ImageView)
and You also have to create a dismiss button in your Dialogs Layout
dialog.show();
Button declineButton = dialog.findViewById(R.id.your_dialog_button);
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
happy coding :)
Related
I am trying to code an inventory app that can work on UROVO DT40 device. I don't know how to code the barcode scanner so that it will work on keystroke and send the result to edittext. I also want to save the data from the adapter and be able to read from a PC. I am still a rookie so I don't know if am doing it the right way. I need some help please. Thanks!!
here's some of the code
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {ArrayList<String>
listitems = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextInputEditText input = findViewById(R.id.textInputEditText);
TextInputEditText input1 = findViewById(R.id.textInputEditText1);
ListView listview = findViewById(R.id.listView);
Button saveBtn = findViewById(R.id.saveBtn);
Button btn_annuler = findViewById(R.id.btn_annuler);
Button OK = findViewById(R.id.btn3);
Button btn2 = findViewById(R.id.btn2) ;
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,listitems);
listview.setAdapter(adapter);
input.setShowSoftInputOnFocus(false);
input1.setShowSoftInputOnFocus(false);
OK.setOnClickListener(v -> {
listitems.add(Objects.requireNonNull(input.getText()).toString() + ';' + Objects.requireNonNull(input1.getText()).toString());
adapter.notifyDataSetChanged();
input.setText("");
input1.setText("");
});
btn_annuler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
input.setText("");
input1.setText("");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.clear();
}
});
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!adapter.toString().equals(""))
{
String data = adapter.toString();
writeToFile(data);
Toast.makeText(MainActivity.this, "Vidage éffectué!", Toast.LENGTH_LONG).show();
}
}
});
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("ficGloba.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
There are code samples on the Urovo github page for the Android SDK, specifically also one for the Scanner
Steps 1 to 4 from from the ScannerManagerDemo.java javadoc describe how you have to setup the Scanner:
1.Obtain an instance of BarCodeReader with ScanManager scan = new ScanManager().
2.Call openScanner to power on the barcode reader.
3.After that, the default output mode is TextBox Mode that send barcode data to the focused text box. User can check the output mode
using getOutputMode and set the output mode using switchOutputMode.
4.Then, the default trigger mode is manually trigger signal. User can check the trigger mode using getTriggerMode and set the trigger mode
using setTriggerMode.
for full completeness, the extracted javacode:
private void initScan() {
mScanManager = new ScanManager();
boolean powerOn = mScanManager.getScannerState();
if (!powerOn) {
powerOn = mScanManager.openScanner();
if (!powerOn) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Scanner cannot be turned on!");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog mAlertDialog = builder.create();
mAlertDialog.show();
}
}
initBarcodeParameters();
}
That should give you enough to get cracking. Godspeed.
Currently, I am using the Picasso library to download images and save it in the device when I press the button. the problem is when I press the button the image not download and just shown the message "Image Downloaded" , so how can i fix it? Here is my code
PicassoDisplayImageAdapter.java
/*
* This class for display the image when clicking on it
* It gets the data from the class have the images "Images in ArrayList"
* Also It is for download images
*/
public class PicassoDisplayImageAdapter extends AppCompatActivity {
public static final int PERMISSION_WRITE = 0;
String fileUri;
Button download_image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_image);
/* Display the data in the ImageView with Picasso "ImageView that insert in he activity" */
final ImageView imageView = findViewById(R.id.image_display);
final Intent intent = getIntent();
if (intent.hasExtra("imageUrl")){
String url = intent.getStringExtra("imageUrl");
Picasso.with(this)
.load(url)
.fit() // to resize the image to imageView
.placeholder(R.drawable.progress_animation)
.error(R.drawable.error)
.into(imageView);
}
/* button to download the image */
download_image = findViewById(R.id.button_download);
checkPermission();
download_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
SaveImage (URL);
}
}
});
}
/* method to save image*/
private void SaveImage(String url) {
Picasso.with(getApplicationContext()).load(url).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File mydir = new File(Environment.getExternalStorageDirectory() + "/11zon");
if (!mydir.exists()) {
mydir.mkdirs();
}
fileUri = mydir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
FileOutputStream outputStream = new FileOutputStream(fileUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Image Downloaded", Toast.LENGTH_LONG).show();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
/* runtime storage permission */
public boolean checkPermission() {
int READ_EXTERNAL_PERMISSION = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if((READ_EXTERNAL_PERMISSION != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
PERMISSION_WRITE);
return false;
}
return true;
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==PERMISSION_WRITE && grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
//do somethings
}
}
}
ImagesRamadanActivity.java That has the data
/*
* This Activity for display the ramadan images
* This class has the data of images
*/
public class ImagesRamadanActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ramadan_images);
/* ArrayList for RamadanImages */
final String[] RamadanImages = {
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
};
/* make new object and find the view "GridView" */
GridView gridView2 = findViewById(R.id.gridview_image_ramadan);
// display all the images from Array on it
gridView2.setAdapter(new PicassoImagesAdapter(ImagesRamadanActivity.this, RamadanImages));
/* display the image when click on it */
// we made a class for this method "the class called PicassoDisplayImageAdapter"
gridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the image
String image = RamadanImages[position];
Intent intent = new Intent(ImagesRamadanActivity.this, PicassoDisplayImageAdapter.class);
intent.putExtra("imageUrl", image);
ImagesRamadanActivity.this.startActivity(intent);
}
});
activity_image_display.xml activity to display the photo and has the button to download the image
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image_display"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageView>
<Button
android:id="#+id/button_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="download the image"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0dp" />
</RelativeLayout>
Inside,
onCreate(){
setContentView(..);
// requestPermission. ask for permission when app starts.
}
#Override
public void onClick(View v) {
if (checkPermission()) {
String URL = intent.getStringExtra("imageUrl");
SaveImage (URL);
}
}
// kind of this, add this block to your existing code.
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to save files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
// make sure Manifest has all the permission defined
By using the retrofit as REST Client,
private void doGetRestBagLotNumber(int bagNumber, String lotNumber, final BagLotNumberRestService callback) {
Call<BagLotNumberModel> call = bagLotNumberRestService.getAntamBagLotNumber(bagNumber, lotNumber);
call.enqueue(new Callback<BagLotNumberModel>() {
#Override
public void onResponse(Call<BagLotNumberModel> call, Response<BagLotNumberModel> response) {
if (response.code() == 404 || response.code() == 422) {
Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_SHORT).show();
} else {
int id = response.body().getId();
int bagNumber = response.body().getBagNumber();
String lotNumber = response.body().getLotNumber();
// Adding the response to recylerview
preparedObjectDataBagLotNumber(id, bagNumber, lotNumber);
callback.onSuccess(response.body() != null);
}
}
#Override
public void onFailure(Call<BagLotNumberModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have a method to display a dialog that contains several edit text
to input data from the user.
Here's the code.
private void addItemTextMethod() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts_antam_incoming, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertDialog builder
alertDialogBuilder.setView(promptsView);
final EditText bagNumber = (EditText) promptsView.findViewById(R.id.editTextDialogAntamBagNumber);
final EditText lotNumber = (EditText) promptsView.findViewById(R.id.editTextDialogLotNumber);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Search", null)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) alertDialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(view -> {
doGetRestBagLotNumber(
Integer.parseInt(bagNumber.getText().toString()), lotNumber.getText().toString(),
new BagLotNumberRestService() {
#Override
public void onSuccess(boolean value) {
if($value){
// The question is here
// Show Big Thick in center of dialog
// Show bottom option, Close or Adding More
// If user choose Adding More , display this dialog again
}
}
#Override
public Call<BagLotNumberModel> getAntamBagLotNumber(int bagNumber, String lotNumber) {
return null;
}
}
);
});
}
});
alertDialog.show();
}
How when the result of the doGetRestBagLotNumber callback is true,
the app show option like this:
Show Big Thick in center of dialog as Success message
Show bottom option, Close or Adding More.
If user choose Adding More , display this dialog again
Any help it so appreciated
Use the instance of your inflated view to change the child views inside it. For example use this inside your onSuccess method:
((ImageView)promptsView.findViewById(R.id.tickIndicationView)).setImageResource(R.drawable.ic_tick);
iam fairly new to android development, so what iam trying to make is app that can show pdf from url,
I want to show progress bar while pdf file is loading from web(some pdf files are big over 15mb) How can i do that?
iam using com.github.barteksc.pdfviewer.PDFView to show pdf from web
here is my pdf show activity
private PDFView mPDFview;
private String mStoreId;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flyer);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mReference = mFirebaseDatabase.getReference("Store");
if (getIntent()!=null)
{
mStoreId = getIntent().getStringExtra("StoreId");
}
if (!mStoreId.isEmpty())
{
getUrlStoreFlyer(mStoreId);
}
}
private void getUrlStoreFlyer(String storeId) {
mReference.child(storeId).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Store storeChain = dataSnapshot.getValue(Store.class);
String pdfUrl = storeChain.getFlyerPDF().toString();
mPDFview = findViewById(R.id.flyer_pdfView);
new RetrievePDFStream().execute(pdfUrl);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
class RetrievePDFStream extends AsyncTask<String, Void, InputStream>
{
#Override
protected InputStream doInBackground(String... strings)
{
InputStream inputStream = null;
try{
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
if (urlConnection.getResponseCode()==200)
{
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
}
catch (IOException e)
{
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
mPDFview.fromStream(inputStream).load();
}
}
#Override
public void onBackPressed() {
finish();
overridePendingTransition(0, 0);
}
}
Here is my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.test.FlyerActivity">
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="150dp"
android:id="#+id/progressBar2" />
<com.github.barteksc.pdfviewer.PDFView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/flyer_pdfView"/>
enter code here
</RelativeLayout>
Here is what i used and worked perfect:
#Override
protected void onPostExecute(InputStream inputStream) {
mPDFview.fromStream(inputStream).onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar2);
progressBar.setVisibility(View.GONE);
}
}).load();
}
private PDFView mPDFview;
private String mStoreId;
//add progressbar
private ProgressBar progressBar;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flyer);
//initialize
progressBar = (ProgressBar) findViewById(R.id.progressBar);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mReference = mFirebaseDatabase.getReference("Store");
if (getIntent()!=null)
{
mStoreId = getIntent().getStringExtra("StoreId");
}
if (!mStoreId.isEmpty())
{
getUrlStoreFlyer(mStoreId);
}
}
private void getUrlStoreFlyer(String storeId) {
mReference.child(storeId).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Store storeChain = dataSnapshot.getValue(Store.class);
String pdfUrl = storeChain.getFlyerPDF().toString();
mPDFview = findViewById(R.id.flyer_pdfView);
new RetrievePDFStream().execute(pdfUrl);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
class RetrievePDFStream extends AsyncTask<String, Void, InputStream>
{
#Override
protected void onPExecute(InputStream inputStream) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected InputStream doInBackground(String... strings)
{
InputStream inputStream = null;
try{
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
if (urlConnection.getResponseCode()==200)
{
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
}
catch (IOException e)
{
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
mPDFview.fromStream(inputStream).load();
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onBackPressed() {
finish();
overridePendingTransition(0, 0);
progressBar.setVisibility(View.GONE);
}
}
Since you are using a library to load PDF from input stream, here is how it can be done.
Just before you execute the Async Task make the progress bar visible and PDFView invisible.
progressBar = findViewById(R.id.progressBar2);
mPDFview = findViewById(R.id.flyer_pdfView);
progressBar.setVisibility(View.VISIBLE);
mPDFview.setVisibility(View.INVISIBLE);
new RetrievePDFStream().execute(pdfUrl);
In onPostExecute() of the AsyncTask is where you do the UI operation after the Network call is complete. So here, you ll have to make the PDFView visible and progressBar invisible, but also since you are making a network operation and then streaming that to PDFView, PDFView will also take time to stream the content. I looked up the library that you are using and I believe it has a function called onLoad(onLoadCompleteListener), you can use this function along with the fromStream() to make the progress bar invisible and pdfView visible.
#Override
protected void onPostExecute(InputStream inputStream) {
mPDFview.fromStream(inputStream).onLoad(this).load();
}
#Override
public void loadComplete(int nbPages) {
progressBar.setVisibilitiy(INVISIBLE);
mPDFView.setVisibility(VISIBLE);
}
Alternatively, Since you are using a library that can actually load PDF from an URI,you need not use Async Task at all.
Just call PDFView.fromUri(uri).onLoad(this).load();
I Want To Add A Switch Camera Button To My Code.
Here is The Code.
I am not getting how do i do it.
Please Suggest Some Methods.
Thank you in Advance.
CameraDemo.java
public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick,switchCam;
int which=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
switchCam=(Button)findViewById(R.id.switchcam);
preview = new Preview(this);
((RelativeLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CameraDemo.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm");
// Setting Dialog Message
alertDialog.setMessage("Are You Done ?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.doneimg);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CameraDemo.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Student");
// Setting Dialog Message
alertDialog.setMessage("Are you a Student?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.student);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Intent i = new Intent(getApplicationContext(),
ScanId.class);
startActivity(i);
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "Sorry, Only Students Allowed", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "Sorry, Only Students Allowed", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
long time = 0;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
time = System.currentTimeMillis();
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",time));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
NExxt Java File >> Preview.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";
SurfaceHolder mHolder;
public Camera camera;
int which=0;
Preview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
camera.stopPreview();
camera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
// parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p= new Paint(Color.RED);
Log.d(TAG,"draw");
canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2, p );
}
}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/layout">
<RelativeLayout android:id="#+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/switchcam"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp" />
</RelativeLayout>
<Button android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/buttonClick"
android:text=""
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/circlebutton"
/>
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/gallery"
android:background="#drawable/grid"
android:layout_marginBottom="50dp"
android:layout_marginLeft="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Just reopen camera with open(int cameraId) method.
//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);