I'm trying to insert a barcode scanner in my ListFragment and use this tutorial: BarcodeScanner
But if I click on of the two buttons (QR or barcode-scan), it seems that my app doesn't find the downloaded XZing Barcode Scanner. But it is installed! I don't get an issue :-( ...
I think something is wrong in the try-part
Here is the code of my ListFragment:
private Button b1;
private Button b2;
static final String ACTION_SCAN = "com.google.xzing.client.android.SCAN";
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
b1 = (Button) getView().findViewById(R.id.button_scan_barcode_ean);
b2 = (Button) getView().findViewById(R.id.button_scan_qr_code);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanQR(v);
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBar(v);
}
});
}
public void scanBar(View v){
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe){
showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
public void scanQR(View v){
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe){
showDialog(getActivity(), "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
private static AlertDialog showDialog(final Activity act, CharSequence title,
CharSequence message,
CharSequence buttonYes,
CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if (requestCode == 0){
if (resultCode == Activity.RESULT_OK){
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(getActivity(), "Content:" + contents + "Format" + format, Toast.LENGTH_LONG);
toast.show();
final EditText editTextBarcode = (EditText) getView().findViewById(R.id.editText_barcode);
editTextBarcode.setText(contents);
}
}
}
Any ideas?
There is a typo in your ACTION_SCAN String. You wrote "xzing" instead of "zxing".
The correct String is
"com.google.zxing.client.android.SCAN"
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 getting this error in logcat when i try to upload image grom gallery. when i upload image from camera directly it works fine. Below is my code
public class OfflineMerchantRegisterActivity extends AppCompatActivity {
EditText edtUsername, edtPassword, edtConfirmPassword, edtEmail, edtMobile, edtServiceType, edtName, edtAddress, edtCity;
Button btnRegister, btnSelectImage, btnSelectCity, btnSelectType;
ImageView imgMerchant;
String offline_service_type;
LinearLayout layoutCity, layoutServiceType;
EditText edtService;
String service;
String username, password, confirmPassword, email, mobile, serviceType, name, address, city;
Context context;
private String userChoosenTask;
private static final int CAMERA_REQUEST = 1888;
private static final int GALLERY_REQUEST = 2;
Bitmap imageBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline_merchant_register);
context=OfflineMerchantRegisterActivity.this;
edtUsername = (EditText) findViewById(R.id.edtUsername);
edtPassword = (EditText) findViewById(R.id.edtPassword);
edtConfirmPassword = (EditText) findViewById(R.id.edtConfirmPassword);
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtMobile = (EditText) findViewById(R.id.edtMobile);
edtServiceType = (EditText) findViewById(R.id.edtServiceType);
edtName = (EditText) findViewById(R.id.edtName);
edtAddress = (EditText) findViewById(R.id.edtAddress);
edtCity = (EditText) findViewById(R.id.edtCity);
edtService = (EditText) findViewById(R.id.edtService);
edtService.setText("Offline Merchant");
btnRegister = (Button) findViewById(R.id.btnRegister);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);
btnSelectCity = (Button) findViewById(R.id.btnSelectCity);
btnSelectType = (Button) findViewById(R.id.btnSelectType);
imgMerchant = (ImageView) findViewById(R.id.imgMerchant);
layoutCity = (LinearLayout) findViewById(R.id.layoutCity);
layoutServiceType = (LinearLayout) findViewById(R.id.layoutServiceType);
btnSelectCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(OfflineMerchantRegisterActivity.this, MerchantCityActivity.class);
startActivityForResult(intent, 3);
}
});
btnSelectType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(OfflineMerchantRegisterActivity.this, OfflineServiceTypeListActivity.class);
startActivityForResult(intent, 1);
}
});
layoutServiceType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
layoutCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isValid()){
//registerOfflineMerchant();
Intent intent = new Intent(OfflineMerchantRegisterActivity.this, OfflineMerchantConfirmActivity.class);
intent.putExtra("username", edtUsername.getText().toString());
intent.putExtra("password", edtPassword.getText().toString());
intent.putExtra("email", edtEmail.getText().toString());
intent.putExtra("mobile", edtMobile.getText().toString());
intent.putExtra("serviceType", edtServiceType.getText().toString());
intent.putExtra("name", edtName.getText().toString());
intent.putExtra("address", edtAddress.getText().toString());
intent.putExtra("city", edtCity.getText().toString());
if (imageBitmap!=null){
intent.putExtra("imageString", getStringImage(imageBitmap));
intent.putExtra("fileName", username+".png");
}
else {
//do nothing
}
intent.putExtra("service", edtService.getText().toString());
startActivity(intent);
}
}
});
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);*/
selectImage();
}
});
}
public boolean isValidMail(String email) {
// TODO Auto-generated method stub
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
public boolean isValid(){
username = edtUsername.getText().toString().trim();
name = edtName.getText().toString().trim();
password = edtPassword.getText().toString().trim();
confirmPassword = edtConfirmPassword.getText().toString().trim();
email = edtEmail.getText().toString().trim();
mobile = edtMobile.getText().toString().trim();
serviceType = edtServiceType.getText().toString().trim();
address = edtAddress.getText().toString().trim();
city = edtCity.getText().toString().trim();
service = edtService.getText().toString().trim();
if (username.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Username", Toast.LENGTH_SHORT).show();
return false;
}
if (name.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Name", Toast.LENGTH_SHORT).show();
return false;
}
if (password.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Password", Toast.LENGTH_SHORT).show();
return false;
}
if (confirmPassword.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Password Again", Toast.LENGTH_SHORT).show();
return false;
}
if (!(password.equals(confirmPassword))) {
Toast.makeText(this, "Passwords Mismatch", Toast.LENGTH_SHORT).show();
return false;
}
if (email.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Email", Toast.LENGTH_SHORT).show();
return false;
}
if (!isValidMail(email)) {
Toast toast = Toast.makeText(this, "Please Enter Valid Email", Toast.LENGTH_SHORT);
toast.show();
return false;
}
if (mobile.length() <=9){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Mobile Number", Toast.LENGTH_SHORT).show();
return false;
}
if (serviceType.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Select Service Type", Toast.LENGTH_SHORT).show();
return false;
}
if (address.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Address", Toast.LENGTH_SHORT).show();
return false;
}
if (city.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Select City", Toast.LENGTH_SHORT).show();
return false;
}
if (service.length() <= 0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter As Offline Service", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
offline_service_type = data.getStringExtra("offlineServiceType");
edtServiceType.setText(offline_service_type);
}
if (resultCode == Activity.RESULT_OK){
if (requestCode == 3){
city = data.getStringExtra("city");
edtCity.setText(city);
}
}
if (resultCode == RESULT_OK && null != data) {
if (requestCode == GALLERY_REQUEST) {
Uri URI = data.getData();
String[] FILE = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(URI, FILE, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(FILE[0]);
String imageDecode = cursor.getString(columnIndex);
cursor.close();
imageBitmap = BitmapFactory.decodeFile(imageDecode);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
imgMerchant.setImageBitmap(imageBitmap);
//uploadImageToServer(getStringImage(bmp), username);
} else if (requestCode == CAMERA_REQUEST) {
imageBitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgMerchant.setImageBitmap(imageBitmap);
//uploadImageToServer(getStringImage(thumbnail), username);
}
}
}
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
byte[] imageBytes = outputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("Take Photo"))
cameraIntent();
else if (userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(context);
if (items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if (result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if (result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_REQUEST);
//startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
public void onBackPressed() {
OfflineMerchantRegisterActivity.this.finish();
super.onBackPressed();
}
}
How to solve this error ? after selecting image from gallery, app crash error.
This error mostly occurs when the data you are filling in the intent is more than the system is able to transfer through Intent bundle. Check to see the size of all the things you are putting in the bundle. And also check to see that the image you are selecting from gallery is not very large, as the system may not be able to transfer the image from gallery to you app. The camera code is working because the camera app transfers a low-resolution image through the Intent.
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);
}
}
This is my code for the BASE class, i am inheriting this class to another child class. And from that class i am calling this function ActiveSMSPackage(). My code is perfect which has not kind of any error but yet the method is not called. Can you guys tell me where i am doing wrong?
public class PrepaidSMSBase extends Activity {
private String smsNumber = "";
private String smsPackageName;
private String smsPrice;
private String smsTitle;
private String smsText;
public PrepaidSMSBase(){}
public void setSmsPackageInformation(String smsTitle, String smsPackageName, String smsPrice, String smsNumber, String smsText)
{
this.smsTitle = smsTitle;
this.smsPackageName = smsPackageName;
this.smsPrice = smsPrice;
this.smsNumber = smsNumber;
this.smsText = smsText;
}
public void activeSMSPackage()
{
try
{AlertDialog.Builder builder = new AlertDialog.Builder(PrepaidSMSBase.this);
builder.setTitle(smsTitle);
builder.setMessage("Are you sure you want to active" + PrepaidSMSBase.this.smsPackageName + "in RS: " +
PrepaidSMSBase.this.smsPrice);
builder.setPositiveButton("Activate", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Please click send button to activate desire Package", Toast.LENGTH_LONG).show();
}
});
}catch (ActivityNotFoundException e){
e.printStackTrace();
}
}
Code of Child class is:
public class SMSCheckClass extends PrepaidSMSBase implements View.OnClickListener{
Button checkButton;
public SMSCheckClass(){
setSmsPackageInformation("Test 1","Some Thing","50","660","Sub");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checksms);
checkButton = (Button)findViewById(R.id.chkBtn);
checkButton.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
activeSMSPackage();
}
Use this code
{AlertDialog.Builder builder = new AlertDialog.Builder(PrepaidSMSBase.this);
builder.setTitle(smsTitle);
builder.setMessage("Are you sure you want to active" + PrepaidSMSBase.this.smsPackageName + "in RS: " +
PrepaidSMSBase.this.smsPrice);
builder.setPositiveButton("Activate", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Please click send button to activate " + PrepaidSMSBase.this.smsPackageName, Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
you just need to add builder.show() in the end of AlertDialog because your function is written inside of AlertDialog and that show() method is used to show AlertDialog
At first, you should show you dialog in activeSMSPackage, please add this code in that method:
builder.show()
I have created a "Contact Us" page on my app and the idea is you have the option to send a picture to an already predetermind email address. The problem I have is its taking all the images from the gallery of the phone and sending them all in the email. All I want to do is send one picture. I cant seem to work out what to change to be able to just send one image. Is there anyone who could help?
Here is my code:
public class EmailActivity extends Activity {
Button send;
EditText address, subject, emailtext;
protected static final int CAMERA_PIC_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.email);
send=(Button) findViewById(R.id.emailsendbutton);
address=(EditText) findViewById(R.id.emailaddress);
subject=(EditText) findViewById(R.id.emailsubject);
emailtext=(EditText) findViewById(R.id.emailtext);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if
(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
}
File pngDir = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.random.jbrefurb/quote");
if (!pngDir.exists())
pngDir.mkdirs();
Uri pngUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "random#yahoo.co.uk"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, pngUri);
emailIntent.setType("image/jpeg");
EmailActivity.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
});
Button back = (Button) findViewById(R.id.button1);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// fire intent
finish(); // finish current activity
Intent austinIntent = new Intent(view.getContext(),
ContactActivity.class);
startActivityForResult(austinIntent, 0);
}
});
Button camera = (Button) findViewById(R.id.button2);
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
;
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode== 0 && resultCode == Activity.RESULT_OK){
Bitmap x = (Bitmap) data.getExtras().get("data");
((ImageView)findViewById(R.id.imageView1)).setImageBitmap(x);
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.BUCKET_ID, "test");
values.put(Images.Media.DESCRIPTION, "test Image taken");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
x.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (FileNotFoundException e) {
//
}catch (IOException e){
//
}
} }
}
Many thanks in advance
this is code i used in my application try if you need help..
private OnClickListener shareemail=new OnClickListener(){
#Override
public void onClick(View v) {
String address = "your emailaddress";
File filee;
if(address.length()==0)
{
AlertDialog.Builder ab=new AlertDialog.Builder(null);
ab.setMessage("Email Address must not be empty!");
ab.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.show();
}
else
{
ArrayList<Uri> uris = new ArrayList<Uri>();
Uri u;
Intent emailSession = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailSession.putExtra(Intent.EXTRA_SUBJECT,"your subject");
emailSession.setType("images/*");
emailSession.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {address});
emailSession.putExtra(android.content.Intent.EXTRA_TEXT,"body text");
FileWriter fw;
BufferedWriter bw;
try{
filee = new File(path of image you want to send);
if(filee.exists())
{
Uri u1 = Uri.fromFile(filee);
uris.add(u1);
emailSession.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(emailSession);
}
}
catch (ActivityNotFoundException e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}}
};