PhoneCall - Dials strange long number instead of the one entered - android

I am writing a simple app that asks for permissions for a call and the user can type in an EditText the phone number they want to dial and then press Make Call.
When I dial in a real number, it ends up going to the phone but it
dials some long number such as 2637643787767877. This happens whether
I use the emulator or my own galaxy s6.
I of course have this in my Manifest file:
<uses-permission android:name="android.permission.CALL_PHONE" />
Here is the code I have.
package cornez.com.phonecall;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText phoneNumToCall;
Button makeCallButton;
int permissionCheck;
private static final int PERMISSION_REQUEST_CALL_PHONE = 100;
private static final String LOG_TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumToCall = (EditText) findViewById(R.id.editText);
makeCallButton = (Button) findViewById(R.id.button);
//onclicklistener for BUTTON
permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE);
makeCallButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// your handler code here
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
makeCall();
}
else {
// request the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
PERMISSION_REQUEST_CALL_PHONE);
}
} });
//makeCallButton.setOnClickListener();
phoneNumToCall.requestFocus();
getWindow().setSoftInputMode(WindowManager.LayoutParams.
SOFT_INPUT_STATE_VISIBLE);
}
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults)
{
if (requestCode == PERMISSION_REQUEST_CALL_PHONE)
{
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
makeCall();
}
else
{
// notify user that permission was denied
Toast.makeText(this, "The permission was denied", Toast.LENGTH_SHORT).show();
}
}
}
private void makeCall()
{
try
{
Uri uri = Uri.parse("tel:" + phoneNumToCall);
Intent intent = new Intent(Intent.ACTION_CALL, uri);
startActivity(intent);
}
catch (SecurityException ex)
{
String errorMsg = "No permission to make phone call.";
Log.e(LOG_TAG, errorMsg, ex);
}
}
}
The question is, What is wrong with this?

String uri = "tel:" + callNumber;
String deviceName = android.os.Build.MODEL;
Intent intent;
if ("Nexus 5".equalsIgnoreCase(deviceName) || "XT1092".equalsIgnoreCase(deviceName) || "XT1572".equalsIgnoreCase(deviceName) || "XT1575".equalsIgnoreCase(deviceName) ) {
intent = new Intent(Intent.ACTION_DIAL);
} else {
intent = new Intent(Intent.ACTION_CALL);
}
intent.setData(Uri.parse(uri));
startActivity(intent)
Try this code.

You are not parsing string from EditText
you just Declare EditText and called it.
phoneNumToCall = (EditText) findViewById(R.id.editText);
try this
Replace makeCall() method with this
private void makeCall()
{
try
{
Uri uri = Uri.parse("tel:" + phoneNumToCall.getText().toString());
Intent intent = new Intent(Intent.ACTION_CALL, uri);
startActivity(intent);
}
catch (SecurityException ex)
{
String errorMsg = "No permission to make phone call.";
Log.e(LOG_TAG, errorMsg, ex);
}
}

Related

Intent move from one to other activity and do oncreate in other activity

I have 2 activity, Tambah and Tampil activity.
I use Tambah activity to add new data (form and button submit), and after submit, it will move to Tampil activity. in Tampil activity will show the list view of data (i'm using Volley). all script works, no error. but in Tampil activity only showing old data (like before add), not showing the newest data.
here my Tambah acitivity
package com.example.arif.upload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class Tambah extends AppCompatActivity implements View.OnClickListener{
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Konfigurasi.url_tambah_tentor)
.addFileToUpload(path, "foto") //Adding file
.addParameter("nama", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
Intent move = new Intent(getApplicationContext(),Tampil.class);
startActivity(move);
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}
}
}
and here Tampil activity
package com.example.arif.upload;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Tampil extends AppCompatActivity {
ListView list_tentor;
ArrayList<String>nama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tampil);
list_tentor = (ListView)findViewById(R.id.list_tentor);
nama = new ArrayList<String>();
list_tentor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent pindah = new Intent(Tampil.this,Tambah.class);
pindah.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(pindah);
finish();
}
});
RequestQueue req = Volley.newRequestQueue(getApplicationContext());
StringRequest sr = new StringRequest(Request.Method.GET, Konfigurasi.url_tampil_tentor, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
JSONArray tentor = jo.getJSONArray("tentor");
for (int i = 0; i < tentor.length(); i++){
JSONObject pertentor = tentor.getJSONObject(i);
nama.add(pertentor.getString("nama"));
}
Tampiladapter ta = new Tampiladapter(getApplicationContext(),nama);
list_tentor.setAdapter(ta);
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
req.add(sr);
}
}
how can when Intent from Tambah activity to Tampil activity, the Tampil activity reload all data include newest data)?
It seems that you are not waiting until data is uploaded and redirecting to next screen.
Try this answer
Implementing ProgressDialog in Multipart Upload Request
onCompleted redirect to next screen

e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp in Android Studio

This is the error that I'm getting everytime I press the upload button after selecting an image from the device
I/System.out:e:java.lang.ClassNotFoundException:com.mediatek.cta.CtaHttp
W/System: ClassLoader referenced unknown path:system/framework/mediatek-cta.jar
While trying to upload an image with a text parameter from the app to SQL database.
MainAtivity.java
package com.example.veekalp.imageupload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Declaring views
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}
}
}

calling another class functions from one class on button click in android

I am making an app with various activities and each activity uses the camera function which is defined in another class. I want that in each activity when the camera button is clicked the camera class is called.
This is my main class:-
package com.example.ishan.complainbox;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.String;
public class Crime extends MainActivity implements View.OnClickListener
{
camera cam=new camera();
EditText str,city,pn,det;
Button save,pic;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
// Get References of Views
str = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pn = (EditText) findViewById(R.id.pin);
det = (EditText) findViewById(R.id.detail);
save = (Button) findViewById(R.id.save);
pic=(Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
}
public void onClick(View view) {
String street = str.getText().toString();
String cty = city.getText().toString();
String pin = pn.getText().toString();
String detail = det.getText().toString();
// check if any of the fields are vaccant
if(str.equals("")||city.equals("")||pn.equals("")||det.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vacant",
Toast.LENGTH_LONG).show();
return;
}
// check if both passwords match
else
{
// Save the Data in Database
dbHandler.insertEntry(street,cty,pin,detail);
Toast.makeText(getApplicationContext(), "Complaint Successfully
Filed ", Toast.LENGTH_LONG).show();
}
}
};
.....and this is the camera class..:-
package com.example.ishan.complainbox;
/**
* Created by ishan on 13/04/2017.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class camera extends MainActivity{
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
btnSelect = (Button) findViewById(R.id.uploadpic);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ivImage = (ImageView) findViewById(R.id.imgView);
}
#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(userChosenTask.equals("Take Photo"))
cameraIntent();
else if(userChosenTask.equals("Choose from Library"))
galleryIntent();
} else {
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(camera.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(camera.this);
if (items[item].equals("Take Photo")) {
userChosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, 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();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap(getApplicationContext().
getContentResolver(),
data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
}
This can be achieved through regular inter-activity communication mechanisms like passing intents or using broadcast receivers. I would suggest using intents - Refer this basic example from Android doc: https://developer.android.com/training/basics/firstapp/starting-activity.html
EDIT
Response to OP's question in comment-
You have to save the image file to FS in your Camera Class and pass the file name as an Extra with the intent to your Crime class. Since you are dealing with storage your Apps's manifest now would need additional permissions. I would recommend you go through this thread: Camera is not saving after taking picture

Starting camera activity, app crashes

I have problem, that I have been searching for whole week. I'm creating app that sends photo and some data to server. The problem is that when I start activity, camera has to start but, for some devices app crashes. I cant describe the error because devices are in other cities. I have LG G3 and HUAWEI P7 on both of them works fine. I think this might be something wrong with permissions but I'm not sure.
package com.fishingtournaments.ZvejysZvejui;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.support.v4.os.EnvironmentCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.Semaphore;
public class SendImageActivity extends AppCompatActivity implements View.OnClickListener {
public static final int CAMERA_PERMISSION_REQUEST_CODE = 8675809;
TextView fish_n, fish_s, points;
public static final int REQUEST_CAPTURE = 1;
public static String path;
public String fish_name, fish_length, fish_points, colleague_id, fish_size, fish_photo, fish_id,
user_id, user_name = "";
//Declaring views
private Button buttonUpload;
private ImageView imageView;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
//Uri to store the image uri
private Uri imageUri; /*, uriSavedImage*/
private File imagesFolder, image;
private String fixedURI;
//----------------------------------//
// Storage for camera image URI components
private final static String CAPTURED_PHOTO_PATH_KEY = "mCurrentPhotoPath";
private final static String CAPTURED_PHOTO_URI_KEY = "uriSavedImage";
// Required for camera operations in order to save the image file on resume.
private String mCurrentPhotoPath = null;
private Uri uriSavedImage = null;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (mCurrentPhotoPath != null) {
savedInstanceState.putString(CAPTURED_PHOTO_PATH_KEY, mCurrentPhotoPath);
}
if (uriSavedImage != null) {
savedInstanceState.putString(CAPTURED_PHOTO_URI_KEY, uriSavedImage.toString());
}
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(CAPTURED_PHOTO_PATH_KEY)) {
mCurrentPhotoPath = savedInstanceState.getString(CAPTURED_PHOTO_PATH_KEY);
}
if (savedInstanceState.containsKey(CAPTURED_PHOTO_URI_KEY)) {
uriSavedImage = Uri.parse(savedInstanceState.getString(CAPTURED_PHOTO_URI_KEY));
}
super.onRestoreInstanceState(savedInstanceState);
}
//-++-+-+-+-+-+-+-+-+-+-+-+-+---//
#Override
protected void onCreate(Bundle savedInstanceState) {
//Requesting storage permission
//TODO INTERFACE,
//TODO CHECK PERMISSIONS
//TODO TEST ON OTHER PHONES
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
setContentView(R.layout.activity_send_image);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload.setOnClickListener(this);
} else {
setContentView(R.layout.activity_send_image);
if (ContextCompat.checkSelfPermission(SendImageActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imagesFolder = new File(Environment.getExternalStorageDirectory(), "FishingTournament");
image = new File(imagesFolder, "QR_" + timeStamp + ".png");
uriSavedImage = Uri.fromFile(image);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(i, REQUEST_CAPTURE);
} else {
String[] permissionRequest = {Manifest.permission.CAMERA};
ActivityCompat.requestPermissions(SendImageActivity.this, permissionRequest, CAMERA_PERMISSION_REQUEST_CODE);
}
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload.setOnClickListener(this);
}
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", "asd") //Adding text parameter to the request
.addParameter("colleague_id", colleague_id)
.addParameter("fish_length", fish_size)
.addParameter("fish_points", fish_points)
.addParameter("fish_photo", fish_photo)
.addParameter("fish_id", fish_id)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CAPTURE) {
if (data != null) {
fixedURI = String.valueOf(uriSavedImage);
fixedURI = fixedURI.replace("file://", "");
path = fixedURI;
// Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(path);
// imageView.setImageBitmap(bitmap);
} else {
fixedURI = String.valueOf(uriSavedImage);
fixedURI = fixedURI.replace("file://", "");
path = fixedURI;
// Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(path);
// imageView.setImageBitmap(bitmap);
}
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
//Requesting permission
private void requestStorageReadPermission() {
if (ContextCompat.checkSelfPermission(SendImageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(SendImageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
Toast.makeText(SendImageActivity.this, "Norint siųsti nuotrauką reikalingas leidimas prie failų saugyklos", Toast.LENGTH_SHORT).show();
}
//And finally ask for the permission
ActivityCompat.requestPermissions(SendImageActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonUpload) {
uploadMultipart();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
onBackPressed();
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
final String user_name = getIntent().getStringExtra("user_name");
final String colleague_id = getIntent().getStringExtra("colleague_id");
final String user_id = getIntent().getStringExtra("user_id");
Intent intent = new Intent(SendImageActivity.this, ChooseFishActivity.class);
intent.putExtra("colleague_id", colleague_id);
intent.putExtra("user_name", user_name);
intent.putExtra("user_id", user_id);
startActivity(intent);
finish();
}
}
It might look dumb why I have if in onCreate() method, it's because in my LG G3 camera is restarting on taking photo. And thats why my onActivityResult() method looks strange.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fishingtournaments.ZvejysZvejui">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/descicon"
android:label="Žvejys žvejui"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ChooseFishActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ResultActivity"
android:configChanges="orientation"
android:parentActivityName=".ChooseFishActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ShowResultsActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
<activity android:name=".SendImageActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
</application>
</manifest>
P.S. My code might look unclean, sorry for that, I have been doing everything and testing everything to solve that problem.
BTW I'm requesting permission for storage in my LoginActivity and there I'm creating folder for photos.
LoginActivity
package com.fishingtournaments.ZvejysZvejui;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class LoginActivity extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE = 123;
EditText qrCode_edit;
Button check_button;
// Button result_button;
public String colleague_id;
public String colleague_name;
public String user_id, user_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if(ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Užklausa permissionų", Toast.LENGTH_SHORT).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(LoginActivity.this, "Norint siųsti nuotrauką reikalingas leidimas prie failų saugyklos", Toast.LENGTH_SHORT).show();
}
//And finally ask for the permission
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}else{
Toast.makeText(LoginActivity.this, "Teisės suteiktos", Toast.LENGTH_SHORT).show();
}
File direct = new File(Environment.getExternalStorageDirectory()+"/FishingTournament");
if(!direct.exists()) {
if (direct.mkdir())
Toast.makeText(LoginActivity.this, "Direktorija sukurta", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(LoginActivity.this, "Nesukurta direktorija, nes ji jau egzistuoja", Toast.LENGTH_SHORT).show();
}
// it will create two folder in your internal storage first is specifyfoldername and another one inside the mentioned folder which is nestedfoldername
qrCode_edit = (EditText) findViewById(R.id.qrCode_editText);
check_button = (Button) findViewById(R.id.check_button);
// result_button = (Button) findViewById(R.id.results);
//QR Code
final Activity activity = this;
/**
* Button for scanning QR code
*
*/
check_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check_button.setEnabled(false);
String qrCode = qrCode_edit.getText().toString();
//QR Code
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Užveskite kamerą ant QR kodo");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
check_button.setEnabled(true);
//---
/*Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(LoginActivity.this, ChooseFishActivity.class);
colleague_id = jsonResponse.getString("colleague_id");
colleague_name = jsonResponse.getString("colleague_name");
user_id = jsonResponse.getString("user_id");
intent.putExtra("colleague_id",colleague_id);
intent.putExtra("user_name",colleague_name);
intent.putExtra("user_id",user_id);
startActivity(intent);
// finish();
//startActivity(new Intent(LoginActivity.this, ChooseFishActivity.class));
}else{
String message = jsonResponse.getString("message");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
*//*ats.setText(message);*//*
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(qrCode, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);*/
}
});
/**
* Button for launching ShowResultsActivity
*/
/*result_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, ShowResultsActivity.class);
startActivity(intent);
finish();
}
});*/
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents()==null){
Toast.makeText(this, "Atšaukėte skanavimą", Toast.LENGTH_LONG).show();
}else{
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
/*If correct QR-code*/
if (success){
Intent intent = new Intent(LoginActivity.this, ChooseFishActivity.class);
colleague_id = jsonResponse.getString("colleague_id");
colleague_name = jsonResponse.getString("colleague_name");
user_id = jsonResponse.getString("user_id");
user_name = jsonResponse.getString("user_name");
intent.putExtra("colleague_id",colleague_id);
intent.putExtra("user_name",colleague_name);
intent.putExtra("user_id",user_id);
Toast.makeText(getApplicationContext(),"Sveiki, " + user_name,Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}else{
String message = jsonResponse.getString("message");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(result.getContents(), responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
So I figured out where the problem was.
The error was exposed beyond app through ClipData.Item.getUri() . Basicly the problem was in this line i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);. After searching for this error I found solution in this post

Back to the previous activity on back pressed

I have a function which display FileDialog and Intent to use Bluetooth.
But when I press back button, it comes to previous activity, it is visible but not clickable (like screenshot) and I have to press the back button once again.
I tried function onBackPressed() { finish(); }, but nothing worked properly.
MainActivity:
...
if(item == shareMenu) {
startActivity(new Intent(getBaseContext(), ShareViaBluetoothActivity.class));
}
...
ShareViaBluetoothActivity:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.util.List;
public class ShareViaBluetoothActivity extends Activity {
private static final int DISCOVER_DURATION = 300;
private static final int REQUEST_BLU = 1;
private FileDialog fileDialog;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
private File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File mPath = new File(Environment.getExternalStorageDirectory(), "//DIR//");
fileDialog = new FileDialog(this, mPath);
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file) {
Log.d(getClass().getName(), "selected file " + file.toString());
setFile(file);
sendViaBluetooth();
}
});
fileDialog.showDialog();
}
public void sendViaBluetooth() {
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if(btAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device!", Toast.LENGTH_LONG).show();
} else {
enableBluetooth();
}
}
public void enableBluetooth() {
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(file.toString())));
intent.setPackage("com.android.bluetooth");
PackageManager pm = getPackageManager();
List<ResolveInfo> appsList = pm.queryIntentActivities(intent, 0);
if(appsList.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for(ResolveInfo info : appsList) {
packageName = info.activityInfo.packageName;
if(packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
if (!found) {
Toast.makeText(this, "Bluetooth havn't been found",
Toast.LENGTH_LONG).show();
} else {
intent.setClassName(packageName, className);
startActivity(intent);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG)
.show();
}
}
}
What you described was not so complete. But I this there are some reasons may result to this, then you can check it.
1. use super.onBackPressed() or give onBackPressed() return can make different
2. please check activity launch mode work.
but you'd better give a more detailed code,then I can help you

Categories

Resources