I am new to Android and I hope I can find a solution here.
On my activity I can take a picture and select it from the gallery. After I press the save button the app should save the image in the database. But all i get is the following error:
08-17 22:52:41.326 2683-2697/android.process.media E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/35 from pid=4424, uid=10060 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480)
at android.content.ContentProvider$Transport.enforceFilePermission(ContentProvider.java:471)
at android.content.ContentProvider$Transport.openTypedAssetFile(ContentProvider.java:416)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:313)
at android.os.Binder.execTransact(Binder.java:453)
08-17 22:42:31.929 4290-4290/com.group6.travlhoe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.group6.travlhoe, PID: 4290
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
at com.group6.TakeOff.activity_unterkunft.imageViewToByte(activity_unterkunft.java:187)
at com.group6.TakeOff.activity_unterkunft$3.onClick(activity_unterkunft.java:205)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My Java code:
public class activity_unterkunft extends AppCompatActivity {
DatabaseHelper myDb;
Button btn_save;
Spinner ChooseProject;
EditText Entfernung,Price,MWST;
String selectedspinner;
ImageView imageView6;
private static int PICK_IMAGE = 100;
Uri imageUri;
private BottomNavigationViewEx bottomNavigationViewEx;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unterkunft);
myDb = new DatabaseHelper(this);
ChooseProject = (Spinner) findViewById(R.id.ChooseProject);
Entfernung = (EditText) findViewById(R.id.Entfernung);
Price = (EditText) findViewById(R.id.Preis);
MWST = (EditText) findViewById(R.id.MwSt);
btn_save=(Button) findViewById(R.id.btn_save);
ImageButton btnCamera= (ImageButton)findViewById(R.id.btnCamera);
imageView6=(ImageView) findViewById(R.id.imageView6);
loadSpinnerData();
SaveData();
//CameraInitialisierung
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
//++++++++++++BOTTOM NAVIGATION BAR++++++++++++//
bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavigationView);
bottomNavigationViewEx.setOnNavigationItemSelectedListener(new BottomNavigationViewEx.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
if (item.getItemId()==R.id.menu_start){
startActivity(new Intent(activity_unterkunft.this, MainActivity.class));
} else if(item.getItemId()==R.id.menu_allgemein){
startActivity(new Intent(activity_unterkunft.this, activity_allgemein.class));
} else if(item.getItemId()==R.id.menu_transport){
startActivity(new Intent(activity_unterkunft.this, activity_transport.class));
} else if(item.getItemId()==R.id.menu_rechnung){
startActivity(new Intent(activity_unterkunft.this, activity_rechnung.class));
} else if(item.getItemId()==R.id.menu_unterkunft){
startActivity(new Intent(activity_unterkunft.this, activity_unterkunft.class));
}
return true;
}
});
bottomNavigationViewEx.setSelectedItemId(R.id.menu_unterkunft);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
}
public void onButtonClicked(View v){
if(v.getId()==R.id.btnCamera) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName= getPictureName();
File imageFile= new File(pictureDirectory,pictureName);
//URI weil putExtra sonst nicht mit File elementen klar kommt!
Uri pictureUri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
startActivityForResult(intent, 0);
}
if(v.getId()==R.id.goToGPS) {
//Intent intent2 = new Intent(activity_unterkunft.this, function_gps.class );
Intent intent2 = new Intent(activity_unterkunft.this, MapsActivity.class );
startActivity(intent2);
}
if(v.getId()==R.id.btnGallery){
openGallery();
}
}
private void openGallery() {
Intent Gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Gallery, PICK_IMAGE);
}
private String getPictureName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "Rechnung"+ timestamp + ".jpg";
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode==PICK_IMAGE){
imageUri= data.getData();
imageView6.setImageURI(imageUri);
}
// Bitmap bitmap = (Bitmap)data.getExtras().get("data");
//imageView.setImageBitmap(bitmap);
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DatabaseHelper db = new DatabaseHelper (getApplicationContext());
// Spinner Drop down elements
List<String> projects = db.getAllProjects();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, projects);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseProject.setPrompt("Projekt auswählen");
// attaching data adapter to spinner
ChooseProject.setAdapter(dataAdapter);
//Listener für den Spinner damit ich den Wert abspeichern kann
ChooseProject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
//selectedspinner =String.ValueOf(parent.getItemAtPosition(pos));
selectedspinner = (String) ChooseProject.getSelectedItem();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public static byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
//++++++++++++Save Data++++++//
public void SaveData(){
btn_save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.createUnterkunft(
selectedspinner,
Integer.valueOf(Price.getText().toString()),
Integer.valueOf(MWST.getText().toString()),
Integer.valueOf(Entfernung.getText().toString()),
imageViewToByte(imageView6)
);
if(isInserted=true)
Toast.makeText(activity_unterkunft.this, "Daten gespeichert", Toast.LENGTH_LONG).show();
else
Toast.makeText(activity_unterkunft.this, "Daten nicht gespeichert", Toast.LENGTH_LONG).show();
}
}
);
}
}
The corresponding method in my DB-Helper:
//+++++++++++++CREATE A UNTERKUNFT++++++++++++//
public boolean createUnterkunft(String project, int price, int steuer, int entfernung, byte [] image){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_PROJECT, project);
contentValues.put(KEY_PRICE, price);
contentValues.put(KEY_MWST, steuer);
contentValues.put(KEY_ENTFERNUNG, entfernung);
contentValues.put(KEY_RECHNUNG_IMG, image);
long result = db.insert(TABLE_UNTERKUNFT,null,contentValues);
if(result == -1)
return false;
else
return true;
}
I hope that someone can help me with this problem.
Runtime permission has been introduced since Android 6.0. Make sure that you have already requested for READ_EXTERNAL_STORAGE permission otherwise you will not be able to access file in the external storage. More information: https://developer.android.com/training/permissions/requesting.html
Related
I am developing a gallery application, I display all the icons from the external storage into my application. I followed the tutorial from the below link and it is working.
https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/
Now in addition to this, I provide an option for the user to take a picture from the application and save it to the gallery. When the picture is taken using the Camera intent, the image gets actually saved in the gallery. But I have to intent to another fragment and come back to the Gallery to see the picture I have taken.
To see the changes immediately, onActivityResult() of the Camera intent, I am recreating the fragment. But the problem occurs when we click the back button. The recreated fragment stays in the backstack forever. I am brain faded searching for answers. Any help is appreciated.
Please find below what I have tried so far.
public class GalleryFragment extends Fragment {
Toolbar toolbar;
MenuItem search;
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
FloatingActionButton cameraButton;
private static final int REQUEST_PERMISSIONS = 100;
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_IMAGE_CAPTURE = 1;
String projectName = "ProjectGA";
File directory;
String mCurrentPhotoPath;
List<GridViewItem> gridItems;
GridView gridView;
public static GalleryFragment newInstance(){
GalleryFragment galleryFragment = new GalleryFragment();
return galleryFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
directory = new File(Environment.getExternalStorageDirectory() + projectName);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
ImageView icon = (ImageView) getActivity().findViewById(R.id.toolbarIcon);
icon.setImageResource(R.drawable.ic_perm_media_black_24dp);
icon.setColorFilter(getResources().getColor(R.color.Gallery));
TextView title = (TextView) getActivity().findViewById(R.id.toolbarTitle);
title.setText(getString(R.string.galleryLabel));
title.setTextColor(getResources().getColor(R.color.textInputEditTextColor));
toolbar.setBackground(getResources().getDrawable(R.drawable.tile_green));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_green_24dp));
cameraButton = (FloatingActionButton) getActivity().findViewById(R.id.rightActionButton);
cameraButton.setVisibility(View.VISIBLE);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
//gridView = (GridView) view.findViewById(R.id.gridView);
gv_folder = (GridView)view.findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
setHasOptionsMenu(true);
return view;
}
#Override
public void onDestroyView() {
cameraButton.setVisibility(View.INVISIBLE);
super.onDestroyView();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {photoFile = createImageFile();
} catch (IOException ex) {
Context context = getContext();
CharSequence text = "Photo cannot be stored.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Context context = getContext();
Uri photoURI = FileProvider.getUriForFile(context,
"com.example.projectga.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}else{
Context context = getContext();
CharSequence text = "Attention! Required to take picture!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
public void createFolder(){
if (!directory.exists()){
directory.mkdirs();
}
}
private File createImageFile() throws IOException {
createFolder();
// Create an image file name
Context context = getContext();
String timeStamp = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
String imageFileName = projectName + "_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
addImageToGallery(image, context);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getPath();
return image;
}
public static void addImageToGallery(File image, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, image.toString());
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
getFragmentManager().beginTransaction()
.replace(R.id.container_gaFragments, GalleryFragment.newInstance()).commit();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
search = menu.add("search").setIcon(R.drawable.ic_search_green_24dp).setShowAsActionFlags(1);
super.onCreateOptionsMenu(menu, inflater);
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage = null;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(getContext(), "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I also override the onBackPressed() in the Activity. Please help. Also attaching some images to make it clear.
The exact problem of what is happening
Any help is appreciated.
In my app I have a few EditText's that users can fill in and hit save and it will save those details. I also have a button that opens up a blank canvas for the user to sign on (digital signature). Then when the user selects save the image is displayed in an ImageView, and then finally the user can tap on save again to save the form with the image. All of this works, but as soon as the user selects save to save the form the app crashes with the following error:
java.lang.NumberFormatException: Invalid int: "android.widget.ImageView$ImageViewBitmapDrawable#efa14f0"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:410)
at java.lang.Integer.parseInt(Integer.java:367)
at java.lang.Integer.parseInt(Integer.java:334)
at com.pta.sign.form.CreateFormActivity.persistPerson(CreateFormActivity.java:413)
at com.pta.sign.form.CreateFormActivity.onClick(CreateFormActivity.java:245)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10814)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Here is the code I use:
FormDBHelper.class
public static final String USER_SIGNATURE = "signature";
....
USER_SIGNATURE + " BLOB, " +
....
public boolean insertPerson(String customername,
......
byte customersign, int
jobnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME_CUSTOMER, customername);
....
contentValues.put(USER_SIGNATURE, customersign);
contentValues.put(USER_JOB_NUMBER, jobnumber);
db.insert(PERSON_TABLE_NAME, null, contentValues);
return true;
}
public boolean updatePerson(Integer id,
String customername,
....
byte customersign,
int jobnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME_CUSTOMER, customername);
....
contentValues.put(USER_SIGNATURE, customersign);
contentValues.put(PERSON_JOB_NUMBER, jobnumber);
db.update(PERSON_TABLE_NAME, contentValues, PERSON_COLUMN_ID + " = ? ", new String[]{Integer.toString(id)});
return true;
}
Then in my CreateFormActivity.class
private FormDBHelper dbHelper;
EditText nameCustomer;
....
ImageView signatureImage;
Button saveButton;
LinearLayout buttonLayout;
Button editButton, deleteButton;
int personID;
.....
nameCustomer = (EditText) findViewById(R.id.editCustName);
....
signatureImage = (ImageView) findViewById(R.id.custimagesig);
....
dbHelper = new FormDBHelper(this);
if (personID > 0) {
saveButton.setVisibility(View.GONE);
buttonLayout.setVisibility(View.VISIBLE);
rs = dbHelper.getPerson(personID);
rs.moveToFirst();
String customerName = rs.getString(rs.getColumnIndex(FormDBHelper.NAME_CUSTOMER));
....
byte[] custsign = rs.getBlob(rs.getColumnIndex(FormDBHelper.USER_SIGNATURE));
int personAge = rs.getInt(rs.getColumnIndex(FormDBHelper.PERSON_JOB_NUMBER));
if (!rs.isClosed()) {
rs.close();
}
nameCustomer.setText(customerName);
nameCustomer.setFocusable(false);
nameCustomer.setClickable(false);
....
signatureImage.setImageBitmap(bitmap);
signatureImage.setFocusable(false);
signatureImage.setClickable(false);
.....
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.saveButton:
persistPerson(); **This is where is crashes (245)**
return;
case R.id.editButton:
saveButton.setVisibility(View.VISIBLE);
buttonLayout.setVisibility(View.GONE);
nameCustomer.setEnabled(true);
nameCustomer.setFocusableInTouchMode(true);
nameCustomer.setClickable(true);
....
signatureImage.setEnabled(false);
signatureImage.setFocusableInTouchMode(true);
signatureImage.setClickable(false);
......
public void persistPerson() {
if (personID > 0) {
if (dbHelper.updatePerson(
personID,
nameCustomer.getText().toString(),
....
(byte) Integer.parseInt(signImage.getDrawable().toString()),
....
Integer.parseInt(jobEditText.getText().toString()))) {
Toast.makeText(getApplicationContext(), "Form Update Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), FragmentJob.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Form Update Failed", Toast.LENGTH_SHORT).show();
}
} else {
if (dbHelper.insertPerson(
nameCustomer.getText().toString(),
....
(byte) Integer.parseInt(signImage.getDrawable().toString()), **this is where it crashes (413)**
Integer.parseInt(jobEditText.getText().toString()))) {
Toast.makeText(getApplicationContext(), "Form Inserted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Could not Insert Form", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), FragmentFormJob.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
This is my code (in the same class) where the user taps on the button to create their signature:
Button.OnClickListener onButtonClick = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(CreateFormActivity.this, CaptureUserSig.class);
startActivityForResult(i, 0);
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == 1) {
Bitmap b = BitmapFactory.decodeByteArray(
data.getByteArrayExtra("byteArray"), 0,
data.getByteArrayExtra("byteArray").length);
signatureImage.setImageBitmap(Bitmap.createScaledBitmap(b, 512, 512, false));
}
}
}
AFAIK this should work, unless I have made a mistake somewhere along the line. But for the life of me I can't seem to figure it out.
Hello I am getting this strange error in my app. The first time the application starts it runs however when I store a photo from the camera the app crashes and shows this log. The app takes photo from the camera or gallery and saves them in the database and displays the photo in a custom gridview.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.notepad.isidorosioannou.notepad/com.example.notepad.isidorosioannou.notepad.CameraMainActivity}: android.database.sqlite.SQLiteException: unknown error (Sqlite code 0): Native could not create new byte[], (OS error - 0:Success)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2444)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.access$900(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
Caused by: android.database.sqlite.SQLiteException: unknown error (Sqlite code 0): Native could not create new byte[], (OS error - 0:Success)
at android.database.CursorWindow.nativeGetBlob(Native Method)
at android.database.CursorWindow.getBlob(CursorWindow.java:403)
at android.database.AbstractWindowedCursor.getBlob(AbstractWindowedCursor.java:45)
at com.example.notepad.isidorosioannou.notepad.DatabaseAdapt.cursorToImage(DatabaseAdapt.java:179)
at com.example.notepad.isidorosioannou.notepad.DatabaseAdapt.loadAllImages(DatabaseAdapt.java:162)
at com.example.notepad.isidorosioannou.notepad.CameraMainActivity.onCreate(CameraMainActivity.java:48)
Here is part of the code from my db Helper and actually the methods that i get the error in the log.
public static final String CAMERANOTE_CREATE = "create table " + CAMERANOTE_TABLE + " ( "
+ CAMERA_ID + " integer primary key autoincrement, "
+ CAMERA_TITLE + " text not null, "
+ CAMERA_DESC + " text not null, "
+ CAMERA_PATH + " blob);";
public long createCamera(DataImage image){
ContentValues contentValues = new ContentValues();
contentValues.put(CAMERA_TITLE,image.getTitle());
contentValues.put(CAMERA_DESC,image.getDesc());
contentValues.put(CAMERA_PATH,image.getPath());
long insert= sqlDB.insert(CAMERANOTE_TABLE,null,contentValues);
return insert;
public ArrayList<DataImage> loadAllImages(){
ArrayList<DataImage> imageList= new ArrayList<>();
Cursor cursor = sqlDB.query(CAMERANOTE_TABLE,new String[]{CAMERA_ID,CAMERA_TITLE,CAMERA_DESC,CAMERA_PATH},null,null,null,null,null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
DataImage image = cursorToImage(cursor);
imageList.add(image);
}
cursor.close();
return imageList;
}
public Cursor loadAllTasks (){
Cursor cursor = sqlDB.query(TODOLIST_TABLE,new String[]{TODO_ID,TODO_TEXT,TODO_CHECKED},null,null,null,null,null);
return cursor;
}
private DataImage cursorToImage(Cursor cursor){
int id = cursor.getInt(cursor.getColumnIndex(DatabaseAdapt.CAMERA_ID));
String text = cursor.getString(cursor.getColumnIndex(DatabaseAdapt.CAMERA_TITLE));
String desc = cursor.getString(cursor.getColumnIndex(DatabaseAdapt.CAMERA_DESC));
byte [] path = cursor.getBlob(cursor.getColumnIndex(DatabaseAdapt.CAMERA_PATH));
DataImage image= new DataImage(id,text,desc,path);
return image;
}
}
Here is my main activity:
public class CameraMainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView buttonImage;
private GridView gridView;
private ArrayList<DataImage> imageList;
public DatabaseAdapt dbAdapter;
private CameraAdapter cameraAdapter;
private AlertDialog alertBuilder;
private Uri imageUri;
private Bitmap bitMap;
private byte [] byteArray;
private static final int REQUEST_CAMERA_CODE = 1;
private static final int REQUEST_GALLERY_CODE=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar3);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
buttonImage = (ImageView)findViewById(R.id.cameraOptionButton);
buttonImage.setOnClickListener(this);
gridView = (GridView) findViewById(R.id.gridviewPhoto);
dbAdapter = new DatabaseAdapt(getApplicationContext());
dbAdapter.open();
imageList = new ArrayList<>();
imageList = dbAdapter.loadAllImages();
cameraAdapter = new CameraAdapter(this,imageList);
gridView.setAdapter(cameraAdapter);
createAlertWindow();
}
public void onDestroy(){
super.onDestroy();
dbAdapter.close();
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.cameraOptionButton){
alertBuilder.show();
}
}
private void createAlertWindow(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_title)
.setItems(R.array.alert_dialog, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
activateCamera();
}
else{
chooseFromGallery();
}
}
});
alertBuilder = alertDialog.create();
}
private void activateCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,REQUEST_CAMERA_CODE);
}
private void chooseFromGallery(){
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUEST_GALLERY_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK && data !=null){
Bundle extra = data.getExtras();
bitMap = extra.getParcelable("data");
byteArray = convertToByte(bitMap);
}
else if(requestCode==REQUEST_GALLERY_CODE && resultCode == RESULT_OK && data !=null){
imageUri = data.getData();
bitMap = decodeUri(imageUri,400);
byteArray=convertToByte(bitMap);
}
Intent intent = new Intent(this,CameraSaveActivity.class);
intent.putExtra("byteImage",byteArray);
startActivity(intent);
}
private Bitmap decodeUri(Uri image,int size){
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(image),null,options);
int width = options.outWidth;
int height = options.outHeight;
int scale = 1;
while (true){
if(width/2<size || height/2<size){
break;
}
width /=2;
height /=2;
scale *=2;
}
BitmapFactory.Options options2 = new BitmapFactory.Options();
options2.inSampleSize=scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(image),null,options2);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
private byte[] convertToByte(Bitmap bitmap){
ByteArrayOutputStream b = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,b );
return b.toByteArray();
}
}
and here is my second activity where I just preview the image and save it.
public class CameraSaveActivity extends AppCompatActivity implements View.OnClickListener {
private EditText cameraSaveTitle , cameraSaveDesc;
private ImageView cameraPreview;
private Button saveButton;
private byte [] byteArray;
private DatabaseAdapt adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_save);
cameraSaveTitle = (EditText)findViewById(R.id.cameraEditTitle);
cameraSaveDesc = (EditText)findViewById(R.id.cameraEditDesc);
cameraPreview = (ImageView)findViewById(R.id.cameraPreview);
saveButton = (Button)findViewById(R.id.saveCameraButton);
Intent intent = getIntent();
byteArray = intent.getByteArrayExtra("byteImage");
ByteArrayInputStream imageStream = new ByteArrayInputStream(byteArray);
cameraPreview.setImageBitmap(BitmapFactory.decodeStream(imageStream));
adapt = new DatabaseAdapt(this);
adapt.open();
saveButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.saveCameraButton){
String text1 = cameraSaveTitle.getText().toString();
String text2 = cameraSaveDesc.getText().toString();
DataImage image = new DataImage(text1,text2,byteArray);
adapt.createCamera(image);
finish();
}
}
public void onDestroy(){
super.onDestroy();
adapt.close();
}
}
Can someone please help. I searched but I could not find a solution
Your problem is that you are storing path in CAMERA_PATH, which is string and trying to get a Blob. There is a type mismatch and thats why the error is thrown.
You need to insert a blob in the CAMERA_PATH before you try retrieving a blob from there.
package com.example.address_book;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.ContactsContract.CommonDataKinds.Phone;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageButton;import android.widget.Toast;
public class MainActivity extends Activity {
private static final int PICK_CONTACT_REQUEST = 1;
String[] num={" "," "};
String number1;
#Overrideprotected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{ImageButton add_me = (ImageButton) findViewById(R.id.imageButton1);
add_me.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE);startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
});
}catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
int n=0;int n1=0;
if (requestCode == PICK_CONTACT_REQUEST){
if (resultCode == RESULT_OK){
Uri stuff = data.getData();Intent in = new Intent(android.content.Intent.ACTION_VIEW, stuff);
in.setType("text/x-vcard");
startActivity(in);
String[] projection = {Phone.NUMBER};Cursor cursor = getContentResolver().query(stuff, projection, null, null, null);cursor.moveToFirst();
int column = cursor.getColumnIndex(Phone.NUMBER);
number1 = cursor.getString(column);
n++;number1 = number1.replace("-" ,"");
for(int i=0;i<num.length;i++){num[i]=number1;
}
}
}
}
#Overridepublic boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);return true;
}
}
Try with this dude it will open your contact jusr pass contactId in this
Intent intent = new Intent(Intent.ACTION_VIEW);
//pass your contact id
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));
intent.setData(uri);
mcntxt.startActivity(intent);
I have been making ringtone application and I have a problem. I can play sounds in listitem and I can set ringtone but when I check from telephone settings, it doesn't play. Where is the problem, thanks.
public class AndroidListViewActivity extends ListActivity {
int [] sesdosya;
MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sesdosya= new int[] {R.raw.aramabeni,R.raw.azsonra,R.raw.baglama,R.raw.crank,R.raw.haha,R.raw.hippopchicken,R.raw.nokiaturkish,R.raw.nuri,
R.raw.policemix,R.raw.polistelsiz,R.raw.ramiz,R.raw.veryfunnybaby,R.raw.wahwah,R.raw.walawalabingbang,R.raw.windowsmusic};
// storing string resources into Array
String[] sesler = getResources().getStringArray(R.array.sesler);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, sesler));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent intent = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
intent.putExtra("position", position);
startActivity(intent);
}
private String getItemAtPosition(int position) {
// TODO Auto-generated method stub
return null;
}
});
}
}
Other class; (Play and set ringtone)
public class SingleListItem extends Activity{
int [] sesdosya;
String[] sesisim;
MediaPlayer mediaPlayer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sesisim = new String[] {"aramabeni","azsonra","baglama","crank","haha","hippopchicken","nokiaturkish","nuri","policemix",
"polistelsiz","ramiz","veryfunnybaby","wahwah","walawalabingbang","windowsmusic"};
sesdosya= new int[] {R.raw.aramabeni,R.raw.azsonra,R.raw.baglama,R.raw.crank,R.raw.haha,R.raw.hippopchicken,R.raw.nokiaturkish,R.raw.nuri,
R.raw.policemix,R.raw.polistelsiz,R.raw.ramiz,R.raw.veryfunnybaby,R.raw.wahwah,R.raw.walawalabingbang,R.raw.windowsmusic};
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent intent = getIntent();
int position = intent.getExtras().getInt("position");
mediaPlayer = MediaPlayer.create(this, sesdosya[position]);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
mediaPlayer.start();
//start the progress dialog
}
});
Button zil = (Button) findViewById(R.id.btnzilsesi);
zil.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Intent intent = getIntent();
int position = intent.getExtras().getInt("position");
setRingtone(sesdosya[position]);
//start the progress dialog
}
});
}
#SuppressLint("SdCardPath")
public boolean setRingtone(int p){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(p);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path=Environment.getExternalStorageDirectory().getPath()+"/sdcard/media/audio/ringtones/";
String filename=sesisim+".mp3";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE,filename);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "test1");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION,false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(
SingleListItem.this,
RingtoneManager.TYPE_RINGTONE,
newUri
);
return true;
}
}