i read DialogFragment, and make one in one like this.
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class MyDialogFragment extends DialogFragment {
public static MyDialogFragment newInstance(int title) {
MyDialogFragment frag = new MyDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.plus_icon)
.setTitle(title)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AddExerciseFragment.doPositiveClick();
}
}
)
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AddExerciseFragment.doNegativeClick();
}
}
)
.create();
}
}
and in another SherlockFragment i make next:
public void doPositiveClick() {
}
public void doNegativeClick() {
}
void showDialog() {
DialogFragment newFragment = MyDialogFragment.newInstance(
R.string.name);
newFragment.show(getFragmentManager(), "dialog");
}
But methods doPositiveClick(),doNegativeClick() wants to be static - it is bad for me.
public void doPositiveClick() {
DialogFlag = 0;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
// dialog.cancel();
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
String path = null;
if (DialogFlag == 0) {
switch (requestCode) {
case GALLERY_REQUEST:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
path = getRealPathFromURI(selectedImage);
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
}
}
if (DialogFlag == 1) {
Uri uri;
if (requestCode == CAMERA_RESULT) {
Cursor cursor = getActivity().getContentResolver().query(
Media.EXTERNAL_CONTENT_URI,
new String[] { Media.DATA, Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
uri = Uri.parse(cursor.getString(cursor
.getColumnIndex(Media.DATA)));
path = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
}
}
In your Fragment class
Declare the below
public static final int DIALOG_FRAGMENT = 1;
public static final int RESULT_OK = 101;
Then
DialogFragment newFragment = MyDialogFragment.newInstance(
R.string.name);
newFragment.setTargetFragment(SherLockFragmentName.this, DIALOG_FRAGMENT);
newFragment.show(getFragmentManager(), "dialog");
Then in Dialog Fragment
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent i =getActivity().getIntent();
i.putExtra("key", true);
getTargetFragment().onActivityResult(getTargetRequestCode(), 101, i);
}
}
)
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//AddExerciseFragment.doNegativeClick();
Intent i =getActivity().getIntent();
i.putExtra("key", false);
getTargetFragment().onActivityResult(getTargetRequestCode(), 101, i);
}
}
)
Then override onActivityResult in Fragment class
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case DIALOG_FRAGMENT:
if (resultCode == RESULT_OK) {
boolean check = data.getBooleanExtra("key", true);
if(check)
{
dopositiveClick();
}
else
{
donegativeClick();
}
}
break;
}
}
If you don't want want a static access here's another option:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
final AddExerciseFragment aef = new AddExerciseFragment(SomeParameters...);
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.plus_icon)
.setTitle(title)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
aef.doPositiveClick();
}
//and so on
Related
public class DirectionActivity extends AppCompatActivity implements View.OnClickListener{
Button scanBtn;
TextView messageText, messageFormat, messageText2, messageFormat2, HTTPResult;
String Result = null;
QRResultData datum;
String myServer = "https://swulj.000webhostapp.com/bus_fetch.php";
String BUS_NUMBER= "EXTRA_BUS_NUMBER";
String Param = "PARAM";
String Stop = "STOP";
Context cntxt = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_direction);
scanBtn = findViewById(R.id.scanBtn);
messageText = findViewById(R.id.textContent);
messageFormat = findViewById(R.id.textFormat);
messageText2 = findViewById(R.id.textContent2);
messageFormat2 = findViewById(R.id.textFormat2);
HTTPResult = findViewById(R.id.HTTPResult);
// adding listener to the button
scanBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(this);
intentIntegrator.setPrompt("Scan a barcode or QR Code");
intentIntegrator.setOrientationLocked(true);
intentIntegrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
// if the intentResult is null then
// toast a message as "cancelled"
if (intentResult != null) {
if (intentResult.getContents() == null) {
Toast.makeText(getBaseContext(), "Cancelled", Toast.LENGTH_SHORT).show();
} else {
// if the intentResult is not null we'll set
// the content and format of scan message
Result = intentResult.getContents();
datum = parseResult(Result, myServer);
showDialog(cntxt);
//messageText.setText(Result);
//messageFormat.setText(intentResult.getFormatName());
messageText.setText(datum.seatNumber);
messageFormat.setText(datum.busNumber);
messageText2.setText(datum.original);
messageFormat2.setText(Result);
//Toast.makeText(getApplicationContext(),"You download is resumed2",Toast.LENGTH_LONG).show();
HTTPConnection1 conn = new HTTPConnection1();
conn.execute(datum);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
public void showDialog(Context cntxt)
{
final CharSequence[] items = {"On-Direction", "Return-Direction"};
AlertDialog.Builder builder = new AlertDialog.Builder(cntxt);
builder.setTitle("Alert Dialog with ListView and Radio button");
//builder.setIcon(R.drawable.icon);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(cntxt, "Success", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(cntxt, "Fail", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public QRResultData parseResult(String Result, String urlArg)
{
QRResultData data = new QRResultData();
/*StringTokenizer multiTokenizer = new StringTokenizer(Result, ";");
if(multiTokenizer.hasMoreTokens())
{
data.busNumber = multiTokenizer.nextToken();
}
if(multiTokenizer.hasMoreTokens())
{
data.seatNumber = multiTokenizer.nextToken();
}*/
data.url = urlArg;
data.original = Result;
String[] split = Result.split(";");
data.busNumber = split[0];
if (split.length > 1) {
data.seatNumber = split[1];
}
return data;
}
.....
.....
I am trying to create a dialog. After the dialog shows, I should select on-direction or return-direction. If on-direction is selected, it should return true, if return-direction is selected, it should return false. But my dialog does not wait for user-inputs. It disappears after a moment.
I am trying to scan a barcode. after scanning the barcode, I am opening a dialog to get true or false. I will send the scanned result, boolean value to the HTTP SERVER.
I am working on an project where the user can change their profile picture either by taking a picture or selecting an image from Gallery. Despite following multiple tutorials, the code they use does not work for me. Whenever I select Camera on the Dialog Box, it goes to Gallery then Camera. Likewise when I select Gallery on the Dialog Box, it does go to Gallery but it will still go to Camera before displaying the image on the Image View. Is it because I am using Android Lollipop? I am not really sure too.
How can I get this fixed?
package com.example.user.imagestuff;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
String[] Items;
ImageView mImageView;
Button mButton;
final int bmpHeight = 160;
final int bmpWidth = 160;
static final int CAMERA_CODE = 1;
static final int GALLERY_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.mImageView);
mButton = (Button) findViewById(R.id.mButton);
Items = getResources().getStringArray(R.array.DialogItems);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageOnClick(v);
}
});
}
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for(int i=0; i < Items.length; i++){
if (Items[i].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[i].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
switch(requestCode){
case 1:
Log.i("CameraCode",""+CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
mImageView.setImageBitmap(resized);
case 0:
Log.i("GalleryCode",""+requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
}
}
}
}
Because you are using for loop for checking Camera and Gallary Strings. You need to remove for loop and try ike below code
And also you missing break in your swith case
final CharSequence[] items = {"Camera", "Gallery"}
if (items[item].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (items[item].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
Second Option
You can also put break; keyword for breaking your for loop when your condition match
You are opening an intent in for loop and there is another mistake is you are not breaking the case in your switch case. Use break in your switch case
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
switch(requestCode){
case 1:
Log.i("CameraCode",""+CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
mImageView.setImageBitmap(resized);
break;
case 0:
Log.i("GalleryCode",""+requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
break;
}
}
This works fine for me.
public static final int CAMERA_PERMISSION =100;
public static final int REQUEST_IMAGE_CAPTURE =101;
public static final int READ_STORAGE_PERMISSION =102;
public static final int REQUEST_IMAGE_PICK =103 ;
private Dialog mCameraDialog;
private Uri mImageURI;
/**
* Method to show list dialog to choose photo form gallery or camera.
*/
private void showChoosePhotoDialog() {
mCameraDialog.setContentView(R.layout.dialog_choose_photo);
if(mCameraDialog.getWindow()!=null)
mCameraDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mCameraDialog.findViewById(R.id.camera).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCameraDialog.dismiss();
onCameraOptionSelected();
}
});
mCameraDialog.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCameraDialog.dismiss();
onGalleryOptionSelected();
}
});
mCameraDialog.show();
}
/**
* Method to open gallery.
*/
private void onGalleryOptionSelected() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentGallery, REQUEST_IMAGE_PICK);
overridePendingTransition(R.anim.push_left_right, R.anim.push_right_left);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
READ_STORAGE_PERMISSION);
}
}
/**
* Method to open chooser.
*/
private void onCameraOptionSelected() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
CAMERA_PERMISSION);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION);
}
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
CAMERA_PERMISSION);
} else {
mImageURI = Uri.parse(AppUtils.getFilename());
startActivityForResult(AppUtils.getCameraChooserIntent(EditProfileActivity.this, mImageURI + ""),
REQUEST_IMAGE_CAPTURE);
}
} else {
mImageURI = Uri.parse(AppUtils.getFilename());
startActivityForResult(AppUtils.getCameraChooserIntent(this, mImageURI + ""),
REQUEST_IMAGE_CAPTURE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSION:
int j = 0;
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED)
j = 1;
}
if (j == 1) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) || (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA))) {
// Toast.makeText(this, R.string.s_camera_permission, Toast.LENGTH_SHORT).show();
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) || !ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
// Open phone settings page.
// Toast.makeText(this, getString(R.string.s_app_needs_camera_permission), Toast.LENGTH_SHORT).show();
}
} else
onCameraOptionSelected();
break;
case READ_STORAGE_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
onGalleryOptionSelected();
else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Toast.makeText(this, getString(R.string.s_storage_permission), Toast.LENGTH_SHORT).show();
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Open Phone Settings
}
}
}
Please Replace your code
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for(int i=0; i < Items.length; i++){
if (Items[i].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[i].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
}
});
builder.show();
}
To
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Items[which].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[which].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
});
builder.show();
}
you didnt use break statement thats why its moving to next statement.
just use break statement when you are firing an intent
public void ImageOnClick (View v){
Log.i("OnClick", "True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < Items.length; i++) {
if (Items[i].equals("Camera")) {
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (CameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(CameraIntent, CAMERA_CODE);
}
break;
} else if (Items[i].equals("Gallery")) {
Log.i("GalleryCode", "" + GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent, GALLERY_CODE);
}
break;
}
}
});
builder.show();
}
To make it efficient use position value, when you set onclickListener it returns one int variable which is position of list which is clicked. In your case its int which So you can simply use
public void ImageOnClick (View v){
Log.i("OnClick", "True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Items[which].equals("Camera")) {
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (CameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(CameraIntent, CAMERA_CODE);
}
break;
} else if (Items[which].equals("Gallery")) {
Log.i("GalleryCode", "" + GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent, GALLERY_CODE);
}
break;
}
});
builder.show();
}
Also in OnActivityResult method use break statement otherwise it will both cases
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case 1:
Log.i("CameraCode", "" + CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth, bmpHeight, true);
mImageView.setImageBitmap(resized);
break;
case 0:
Log.i("GalleryCode", "" + requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
break;
}
}
}
ItemAdapter.java
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textView;
String item;
private final Context context;
public ViewHolder(final View itemView) {
super(itemView);
context = itemView.getContext();
itemView.setOnClickListener(this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId()==textView.getId()){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
context.startActivity(intent);
}
else
{
Toast.makeText(context,"Hellooo",Toast.LENGTH_LONG).show();
}
}
});
textView = (TextView) itemView.findViewById(R.id.textView);
}
Try this
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
activeTakePhoto();
} else if (items[item].equals("Choose from Library")) {
activeGallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void activeTakePhoto() { //open camera
String filename = "Pic_" + System.currentTimeMillis() + ".jpg";
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(), filename);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
private void activeGallery() { // open gallery
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
break;
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
imageView.setImageURI(null);
imageView.setImageURI(imageUri);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}
}
}
I'm using MvvmCross on Android via Xamarin and i got a problem. I created a core service interface called IFileExplorerService.
This interface goal is to open a open file dialog and select a file whatever the device is (Windows or android).
On android i managed easly to do this without my interface via view by just using the OnActivityResult and Intents.
But i just cannot make it work from my view, as the interface implementation is a singleton registered in the setup, when i call it from my viewmodel there is absolutely no one to handle the OnActivityResult.
I tried to make my FileExplorer implmentation to inherit from Activity or MvxActivity, for this way my FileExplorer could override OnActivityResult, but this fails.
I tried to use StartActivity(typeof(FileExplorer)) but this obviously would fails anyway as it wouldn't be the singleton registered in MvvmCross that would be started.
Does anyone has any idea/comment/question/suggestion to help me on this?
Here is my code so far :
public class FileExplorerService : IFileExplorerServiceMock
{
string _addedFileName;
public static int REQUEST_FILE_CAPTURE = 2;
private bool _hasMediaBeenAdded;
private TaskCompletionSource<String> GetFileTask;
public Activity activity;
public FileExplorerService()
{
GetFileTask = new TaskCompletionSource<string>();
}
private void DispatchSelectFileIntent()
{
Intent Intent = new Intent();
Intent.SetType("*/*");
Intent.SetAction(Intent.ActionGetContent);
activity.StartActivityForResult(Intent.CreateChooser(Intent, "Select File"), REQUEST_FILE_CAPTURE);
}
public void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
//
if (resultCode == Result.Ok)
{
if (data != null)
{
bool isFileCopied = CopySelectedFileToAddedFilesDirectory(data.Data);
if (isFileCopied)
{
//everything went well
ShowSuccesAlertDialog();
GetFileTask.SetResult(_addedFileName);
}
else
{
ShowFailureAlertDialog();
//oops something crashed
//Log
}
}
}
else
{
_addedFileName = String.Empty;
}
}
private void ShowFailureAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Oops... something went wrong");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Something went rong when adding a media");
alertDialog.SetButton("Ok", (s, ev) =>
{
});
alertDialog.Show();
}
private void ShowSuccesAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Media added with succes !");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Your media has been added with succes");
alertDialog.SetButton("Ok", (s, ev) =>
{
_hasMediaBeenAdded = true;
});
alertDialog.Show();
}
private void DeletePreviousAddedFile()
{
//todo delete file only if selected rex type is the same
if (_hasMediaBeenAdded)
{
MsFile.Delete(_addedFileName);
_addedFileName = string.Empty;
_hasMediaBeenAdded = false;
}
}
private static string GetRealPathFromURI(Context _context, Android.Net.Uri contentUri)
{
string[] projection = new string[] { MediaStore.MediaColumns.Data };
ContentResolver cr = _context.ContentResolver;
Android.Database.ICursor cursor = cr.Query(contentUri, projection, null, null, null);
if (cursor != null && cursor.Count > 0)
{
cursor.MoveToFirst();
int index = cursor.GetColumnIndex(Android.Provider.MediaStore.MediaColumns.Data);
return cursor.GetString(index);
}
return "";
}
private bool CopySelectedFileToAddedFilesDirectory(Android.Net.Uri data)
{
var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/");
if (!dir.Exists())
dir.Mkdirs();
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/";
JavaFile file = new Java.IO.File(path);
string realPath = GetRealPathFromURI(activity.ApplicationContext, data);
string FileName = realPath.Split('/').Last();
_addedFileName = Path.Combine(dir + "/" + FileName);
if (!string.IsNullOrEmpty(realPath))
{
//todo manage errors
using (FileStream fs = new FileStream(realPath, FileMode.Open))
{
byte[] datas = new byte[fs.Length];
int numberBytesToRead = (int)fs.Length;
int numBytesRead = 0;
while (numberBytesToRead > 0)
{
int n = fs.Read(datas, numBytesRead, numberBytesToRead);
if (n == 0)
{
break;
}
numBytesRead += n;
numberBytesToRead -= n;
}
using (FileStream fs2 = System.IO.File.OpenWrite(Path.Combine(dir + "/" + FileName)))
{
fs2.Write(datas, 0, datas.Length);
}
}
return true;
}
return false;
}
public List<FileType> FileTypes
{
get
{
return new List<FileType>();
}
}
public async Task<string> Show(string fiel)
{
if (activity != null)
{
DeletePreviousAddedFile();
DispatchSelectFileIntent();
return GetFileTask.Task.Result;
}
else
{
return String.Empty;
}
}
And in my view :
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.RexView);
_addMediaController = new AddMediaController(this, (RexViewModel)base.ViewModel);
_flyoutMenuAnimator = new FlyoutMenuAnimator(this);
var t= Mvx.Resolve<IFileExplorerServiceMock>() as FileExplorerService;
t.activity = this;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
var t = Mvx.Resolve<IFileExplorerServiceMock>() as FileExplorerService;
t.OnActivityResult(requestCode, resultCode, data);
base.OnActivityResult(requestCode, resultCode, data);
}
With this everything work except that OnActivityResult is never called in my view
Okay i solved it ! Thanks to this link https://forums.xamarin.com/discussion/45691/pass-data-from-android-project-to-pcl
I had to rewrite start activity to give it a callback as an argument, the callback being my OnActivityResult in my file Explorer.
Here is my the code for anyone needing it :
in MyView:
private Action<int, Result, Intent> _resultCallback;
public void StartActivity(Intent intent,int resultCode, Action<int, Result, Intent> resultCallback)
{
_resultCallback = resultCallback;
StartActivityForResult(intent, resultCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (_resultCallback != null)
{
_resultCallback(requestCode, resultCode, data);
_resultCallback = null;
}
}
and in my file Explorer :
string _addedFileName;
public static int REQUEST_FILE_CAPTURE = 2;
private bool _hasMediaBeenAdded;
private TaskCompletionSource<String> GetFileTask;
public RexView activity;
public FileExplorerService()
{
}
private void DispatchSelectFileIntent()
{
Intent intent = new Intent();
intent.SetType("*/*");
intent.SetAction(Intent.ActionGetContent);
GetFileTask = new TaskCompletionSource<string>();
activity.StartActivity(Intent.CreateChooser(intent, "Select File"), REQUEST_FILE_CAPTURE, OnActivityResult);
// activity.StartActivityForResult(Intent.CreateChooser(intent, "Select File"), REQUEST_FILE_CAPTURE);
}
public void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
//
if (resultCode == Result.Ok)
{
if (data != null)
{
bool isFileCopied = CopySelectedFileToAddedFilesDirectory(data.Data);
if (isFileCopied)
{
//everything went well
ShowSuccesAlertDialog();
GetFileTask.SetResult(_addedFileName);
}
else
{
ShowFailureAlertDialog();
//oops something crashed
//Log
}
}
}
else
{
_addedFileName = String.Empty;
}
}
private void ShowFailureAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Oops... something went wrong");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Something went rong when adding a media");
alertDialog.SetButton("Ok", (s, ev) =>
{
});
alertDialog.Show();
}
private void ShowSuccesAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Media added with succes !");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Your media has been added with succes");
alertDialog.SetButton("Ok", (s, ev) =>
{
_hasMediaBeenAdded = true;
});
alertDialog.Show();
}
private void DeletePreviousAddedFile()
{
//todo delete file only if selected rex type is the same
if (_hasMediaBeenAdded)
{
MsFile.Delete(_addedFileName);
_addedFileName = string.Empty;
_hasMediaBeenAdded = false;
}
}
private static string GetRealPathFromURI(Context _context, Android.Net.Uri contentUri)
{
string[] projection = new string[] { MediaStore.MediaColumns.Data };
ContentResolver cr = _context.ContentResolver;
Android.Database.ICursor cursor = cr.Query(contentUri, projection, null, null, null);
if (cursor != null && cursor.Count > 0)
{
cursor.MoveToFirst();
int index = cursor.GetColumnIndex(Android.Provider.MediaStore.MediaColumns.Data);
return cursor.GetString(index);
}
return "";
}
private bool CopySelectedFileToAddedFilesDirectory(Android.Net.Uri data)
{
var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/");
if (!dir.Exists())
dir.Mkdirs();
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/";
JavaFile file = new Java.IO.File(path);
string realPath = GetRealPathFromURI(activity.ApplicationContext, data);
string FileName = realPath.Split('/').Last();
_addedFileName = Path.Combine(dir + "/" + FileName);
if (!string.IsNullOrEmpty(realPath))
{
//todo manage errors
using (FileStream fs = new FileStream(realPath, FileMode.Open))
{
byte[] datas = new byte[fs.Length];
int numberBytesToRead = (int)fs.Length;
int numBytesRead = 0;
while (numberBytesToRead > 0)
{
int n = fs.Read(datas, numBytesRead, numberBytesToRead);
if (n == 0)
{
break;
}
numBytesRead += n;
numberBytesToRead -= n;
}
using (FileStream fs2 = System.IO.File.OpenWrite(Path.Combine(dir + "/" + FileName)))
{
fs2.Write(datas, 0, datas.Length);
}
}
return true;
}
return false;
}
public List<FileType> FileTypes
{
get
{
return new List<FileType>();
}
}
public async Task<string> Show(string fiel)
{
if (activity != null)
{
DeletePreviousAddedFile();
DispatchSelectFileIntent();
return await GetFileTask.Task;
}
else
{
return String.Empty;
}
}
}
And in my view model
private async void BrowseMedias()
{
var fileExplorerService = Mvx.Resolve<IFileExplorerServiceMock>();
fileExplorerService.FileTypes.Add(FileType.Picture);
string fileSavedPath = await fileExplorerService.Show(DatabaseContentPath);
/* file managment*/
}
I have created an app in which the user can take pics using their default camera.It works fine in older versions that is till lollipop but when i try to run the app in marshmallow the app gets closed.
So i have added some codes to give permission for the camera app by the user but even it is not working.
public class Cam extends Activity{
String receivingdata;
TextView namecat;
String amount,vat;
private static final String TAG = Cam.class.getSimpleName();
ImageButton imgview,imgchart,imgexit;
Boolean isInternetPresent = false;
ConnectionDetector cd;
AlertDialog alert;
ImageButton btgoback,btcaptureagain,btnpreview;
static TextView tv;
private ImageView imgPreview;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
public static Bitmap bitmap;
final Context context=this;
ConnectionClass connectionClass;
private static final String IMAGE_CAPTURE_FOLDER = "Receipt";
private static final int CAMERA_PIC_REQUEST = 1111;
private static File file;
private Uri ImagefileUri;
private static final String PREF_FIRSTLAUNCH_HELP = "helpcmaera";
private boolean helpDisplayed = false;
private static final String LOGIN_URL = "http://balajee2777-001-site1.1tempurl.com/backup-07032016/Receiptphp/receipts.php";
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Receipt");
alertDialogBuilder
.setMessage("Would you Like to go previous Page!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent i=new Intent(Cam.this,ListAct.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camcod);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
Bundle b = getIntent().getExtras();
receivingdata = b.getString("key");
tv = (TextView)findViewById(R.id.camcodname);
tv.setText(receivingdata);
tv.setVisibility(View.INVISIBLE);
String[] bits=receivingdata.split("_");
String catname = bits[0];
String vatname= bits[1];
connectionClass= new ConnectionClass();
imgPreview = (ImageView) findViewById(R.id.imgpreview);
namecat=(TextView)findViewById(R.id.tvcatnamess);
namecat.setText(catname);
imgview=(ImageButton)findViewById(R.id.camlinearrecep);
imgchart=(ImageButton)findViewById(R.id.camlinearchart);
imgexit=(ImageButton)findViewById(R.id.camlinearexit);
btgoback=(ImageButton)findViewById(R.id.bgoback);
btnpreview=(ImageButton)findViewById(R.id.btnpreview);
btcaptureagain=(ImageButton)findViewById(R.id.bcaptureagain);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
showHelpForFirstLaunch();
btgoback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isInternetPresent) {
showreceipt();
}else{
neti();
}
}
});
btnpreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Cam.this,DeleteMainAct.class);
startActivity(i);
}
});
btcaptureagain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
}
});
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to view receipts!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Viewreceipt.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgchart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to see report!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Chartboy.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode==CAMERA_PIC_REQUEST){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
Toast.makeText(this,"Camera permission not granted",Toast.LENGTH_SHORT).show();
}
}else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}
private void showHelpForFirstLaunch() {
helpDisplayed = getPreferenceValue(PREF_FIRSTLAUNCH_HELP, false);
if (!helpDisplayed) {
showHelp();
savePreference(PREF_FIRSTLAUNCH_HELP, true);
}else if(helpDisplayed){
return;
}
}
private void showHelp() {
final View instructionsContainer = findViewById(R.id.container_help);
instructionsContainer.setVisibility(View.VISIBLE);
instructionsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
instructionsContainer.setVisibility(View.INVISIBLE);
}
});
}
private boolean getPreferenceValue(String key, boolean defaultValue) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
return preferences.getBoolean(key, defaultValue);
}
private void savePreference(String key, boolean value) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private File getFile() {
String filepath = Environment.getExternalStorageDirectory().getPath();
file = new File(filepath, IMAGE_CAPTURE_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
String names=tv.getText().toString();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(file + File.separator + names+"_"+timeStamp
+ ".jpg");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
imgPreview.setVisibility(View.VISIBLE);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int dw = size.x;
int dh = size.y;
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
imgPreview.setImageBitmap(bmp);
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled 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();
}
}
private void neti() {
final LayoutInflater layoutInflater = LayoutInflater.from(Cam.this);
final View promptView = layoutInflater.inflate(R.layout.connectionlost, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false);
final Button retry=(Button)promptView.findViewById(R.id.btnretry);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=getIntent();
finish();
startActivity(intent);
}
});
alert= alertDialogBuilder.create();
alert.show();
}
private void showreceipt() {
LayoutInflater repcard=LayoutInflater.from(Cam.this);
View promptView=repcard.inflate(R.layout.moneyreceipt,null);
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setView(promptView);
final EditText amt=(EditText)promptView.findViewById(R.id.edamt);
final EditText vta=(EditText)promptView.findViewById(R.id.edvat);
final TextView tvs=(TextView)promptView.findViewById(R.id.tvamount);
final TextView tvat=(TextView)promptView.findViewById(R.id.tvvat);
tvs.setVisibility(View.INVISIBLE);
tvat.setVisibility(View.INVISIBLE);
amt.setRawInputType(Configuration.KEYBOARD_12KEY);
vta.setRawInputType(Configuration.KEYBOARD_12KEY);
final Button save=(Button)promptView.findViewById(R.id.btnmoneysave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tvs.setText(amt.getText().toString());
tvat.setText(vta.getText().toString());
amount=tvs.getText().toString();
vat=tvat.getText().toString();
// Toast.makeText(Cam.this, amount, Toast.LENGTH_LONG).show();
//Toast.makeText(Cam.this, vat, Toast.LENGTH_LONG).show();
detailsreceiptupload();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void detailsreceiptupload() {
String[] bits=receivingdata.split("_");
String catname = bits[0];
String cdte=bits[1];
String[] nyte=cdte.split("#");
String email=nyte[0];
String cdate=nyte[1];
String cimagetag=tv.getText().toString();
//String amt=tvs.getText().toString();
userLogin(catname, cdate,email,cimagetag,amount,vat);
}
private void userLogin(String catname, String cdate, String email, String cimagetag, String amount, String vat) {
class UserLoginClass extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Cam.this, "Connecting to Cloud", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")) {
DoLogin dologin=new DoLogin();
dologin.execute("");
}
else
{
Toast.makeText(Cam.this,s,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("catname",params[0]);
data.put("cdate",params[1]);
data.put("email",params[2]);
data.put("cimagetag",params[3]);
data.put("amount",params[4]);
data.put("vat",params[5]);
RegisterUserClass ruc = new RegisterUserClass();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(catname,cdate,email,cimagetag,amount,vat);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DoLogin extends AsyncTask<String,String,String> {
String z="";
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
File destinationdir = new File(Environment.getExternalStorageDirectory() ,"/CompressedImage");
if (!destinationdir.exists()) {
destinationdir.mkdirs();
}
for(File file1:files){
FileOutputStream fos=null;
try{
File file=new File(destinationdir,file1.getName());
fos=new FileOutputStream(file);
Bitmap bm = BitmapFactory.decodeFile(file1.getAbsolutePath());
bm.compress(Bitmap.CompressFormat.JPEG, 25, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), destinationdir.getPath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return z;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
file.delete();
}
Intent i=new Intent(Cam.this,ReceiptGrid.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Cam.this.finish();
dismissDialog(progress_bar_type);
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}}
I have used an condition to check the phones version.If it is marshmallow then i have given a method name showcamera to do the functions for marshmallow
ShowCamera:
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}