I'm trying to take a photo from gallery on a Dialog but I couldn't. I cannot call startActivityResult() method to override on Dialog. Does anybody know a way to do it on Dialog?
Here is my code. (I need to do it in buttonG.setOnClickListener())
public class AddBirthdayDialog extends Dialog {
private Context context;
String name;
String sname;
private int day;
private int month;
private int year;
private byte[] imageByte;
private Bitmap imageBitmap;
private int RESULT_LOAD_IMAGE = 1;
final EditText textName;
final EditText textSname;
final DatePicker birthDate;
private DB myDB;
private SQLiteDatabase database;
private Person person = new Person();
public AddBirthdayDialog(final Context context) {
super(context);
this.context = context;
setCanceledOnTouchOutside(false);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.addbirthday_layout);
myDB = new DB(context);
textName = (EditText) findViewById(R.id.editTextname);
textSname = (EditText) findViewById(R.id.editTextsname);
birthDate = (DatePicker) findViewById(R.id.datePicker);
Button buttonG = (Button) findViewById(R.id.buttonUploadG);
buttonG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**//Need to call gallery and take a photo's bitmap or byte[] here.**
}
});
Button buttonC = (Button) findViewById(R.id.buttonUploadC);
buttonC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Button cancelButton = (Button) findViewById(R.id.cancelbutton);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
Button save = (Button) findViewById(R.id.buttonadd);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = textName.getText().toString();
sname = textSname.getText().toString();
day = birthDate.getDayOfMonth();
month = birthDate.getMonth()+1;
year = birthDate.getYear();
final String dayStr = String.valueOf(day);
final String monthStr = String.valueOf(month+1);
final String yearStr = String.valueOf(year);
person.setName(name);
person.setSname(sname);
person.setDay(day);
person.setMonth(month);
person.setYear(year);
person.setDateStr(dayStr + "/" + monthStr + "/" + yearStr);
myDB.addBirthday(person);
if(context instanceof MainActivity)
((MainActivity)context).onResume();
dismiss();
}
});
}
}
Thanks in advance :)
inside your class:
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECTED_PICTURE:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection,
null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
selectedImage = BitmapFactory.decodeFile(filePath);
d = new BitmapDrawable(selectedImage);
iv.setBackground(d);
update.setVisibility(View.VISIBLE);
}
break;
}
}
inside onClick:
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_PICTURE);
Global variables:
private static final int SELECTED_PICTURE = 1;
Bitmap selectedImage;
What is context? If it is an activity, you can to start activity from your context-activity and handle onActivityResult in context-activity
Related
I am creating my first project using Android Studio, I am aiming to create an app where you can load photos in from the phones memory and display them so people can see.
I've managed to get it working sort of how I want it to, the pictures in the gallery stay where they should do when I close out of the app and then reopen it - however if I close the app restart it and then try and add a new photo it overwrites the gallery and deletes the pictures I orginally put in. Does anyone have any ideas on how I can fix this? I tried playing with when I create the images ArrayList but that didn't help.
Code:
Main Activity
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST = 0;
private static final int RESULT_LOAD_IMAAGE = 1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
ImageView imageView;
Button uploadButton;
Button savedPhotos;
List<String> images;
String imageCreated;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
imageView = (ImageView) findViewById(R.id.imageView);
uploadButton = (Button) findViewById(R.id.button);
savedPhotos = (Button) findViewById(R.id.button2);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
images = new ArrayList<>();
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAAGE);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(imageCreated, "Complete");
}
});
savedPhotos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openPage2();
}
});
}
public void openPage2()
{
Intent intent = new Intent(this, SavedPhotos.class);
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode)
{
case PERMISSION_REQUEST:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Permission Not Granted", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch(requestCode)
{
case RESULT_LOAD_IMAAGE:
if(resultCode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
images.add(picturePath);
StringBuilder stringBuilder = new StringBuilder();
for(String i : images)
{
stringBuilder.append(i);
stringBuilder.append(",");
}
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("images", stringBuilder.toString() );
editor.commit();
}
}
}}
And SavedPhotos
public class SavedPhotos extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_photos);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
String wordsString = sharedpreferences.getString("images", "");
String[] itemWords = wordsString.split(",");
List<String> items = new ArrayList<String>();
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for(int i = 0; i < itemWords.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);
items.add(itemWords[i]);
imageView.setImageBitmap(BitmapFactory.decodeFile(items.get(i)));
}
}}
Thank you for your help :)
I actually run to same issues before until i met a well made library and requires nothing and made my code much good looking, FastSave: https://github.com/yehiahd/FastSave-Android.
I have two activity:
First activity: MyCollectionActivity
In this activity I have a TextView for title, a ListView - to show my list of stamps and a FloatingButtonAction.
When I click on the FloatingButtonAction I want to start my second activity that I'm talking about: InsertStampActivity.
Second activity: InsertStampActivity
InsertStampActivity where I have 3 EditText (inserting country, value, year), an ImageButton and an empty ImageView(for the inserted image). When I click on the ImageButton it will pop up an AlertDialogBox with 3 buttons: Button - FROM GALLERY, Button - TAKE PHOTO or Button - EXIT.
When I click on FROM GALLERY I want to select a picture from my phone's gallery, when I click on TAKE PHOTO to open phone's camera to take photo and when I click on EXIT, to return to MyCollectionActivity.
For this to happend I want to use an CustomAdapter.
---My problem is how to manage the inserted image.---
My CLASS Timbru (meaning stamp):
public class Timbru implements Parcelable {
private Integer year;
private String country;
private Float value;
private String imagePath;
public Timbru(int year, String country, float value, String imagePath) {
this.year = year;
this.country = country;
this.value = value;
this.imagePath = imagePath;
}
public Timbru() {
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Float getValue() {
return value;
}
public void setValue(Float value) {
this.value = value;
}
#Override
public String toString() {
return "Timbru{" +
"year=" + year +
", country='" + country + '\'' +
", value=" + value +
", imagePath='" + imagePath + '\'' +
'}';
}
public Timbru(Parcel in) {
this.year = in.readInt();
this.country = in.readString();
this.value = in.readFloat();
}
public static Parcelable.Creator<Timbru> CREATOR = new Creator<Timbru>() {
#Override
public Timbru createFromParcel(Parcel parcel) {
return new Timbru(parcel);
}
#Override
public Timbru[] newArray(int i) {
return new Timbru[i];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(year);
parcel.writeString(country);
parcel.writeFloat(value);
}
}
This is a class for keeping the List:
public class ListaTimbru {
private static ArrayList<Timbru> timbre = new ArrayList<>();
public static ArrayList<Timbru> getTimbre() {
return timbre;
}
public ListaTimbru() {
}
}
This is TimbruAdapter class:
public class TimbruAdapter extends ArrayAdapter {
private int resource;
private List<Timbru> objects;
private LayoutInflater inflater;
public TimbruAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List objects, LayoutInflater inflater) {
super(context, resource, objects);
this.inflater = inflater;
this.resource = resource;
this.objects = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row = inflater.inflate(this.resource, parent, false);
TextView tvYear = (TextView) row.findViewById(R.id.tv_year_rowLayout2);
TextView tvCountry = (TextView) row.findViewById(R.id.tv_country_rowLayout2);
TextView tvValue = (TextView) row.findViewById(R.id.tv_value_rowLayout2);
Timbru timbru = objects.get(position);
tvCountry.setText(timbru != null && timbru.getCountry() != null ? timbru.getCountry() : "");
tvYear.setText(timbru != null && timbru.getYear() != null ? timbru.getYear().toString() : "");
tvValue.setText(timbru != null && timbru.getValue() != null ? timbru.getValue().toString() : "");
return row;
}
}
This is MyCollectionActivity:
public class MyColectionActivity extends AppCompatActivity {
FloatingActionButton fltBtn_insert;
ListView listViewStamps;
List<String> listStamps = new ArrayList<>();
List<Timbru> listStamps2 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_colection);
fltBtn_insert = (FloatingActionButton)
findViewById(R.id.flBtn_insertNewStamp_myCollection);
listViewStamps = (ListView)
findViewById(R.id.lv_stampList_myCollection);
TimbruAdapter adapter = new TimbruAdapter(getApplicationContext(), R.layout.row_layout2, ListaTimbru.getTimbre(), getLayoutInflater());
listViewStamps.setAdapter(adapter);
fltBtn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), InsertStampActivity.class);
startActivityForResult(intent, Constants.ADD_STAMP_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.ADD_STAMP_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Timbru result = data.getParcelableExtra(Constants.ADD_STAMP_KEY);
if (result != null) {
ListaTimbru.getTimbre().add(result);
TimbruAdapter currentAdapter = (TimbruAdapter) listViewStamps.getAdapter();
currentAdapter.notifyDataSetChanged();
}
}
}
This is InsertStampActivity:
public class InsertStampActivity extends AppCompatActivity {
EditText et_year;
EditText et_country;
EditText et_value;
Intent intent;
Button insertStamp;
ImageView poza_timbru;
Uri imageUri;
static final int PICK_IMAGE_REQUEST=1;
static final int REQUEST_IMAGE_TAKEN=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_stamp);
initializareComponente();
intent = getIntent();
}
private void initializareComponente() {
et_year = (EditText) findViewById(R.id.et_year_insertStamp);
et_country = (EditText) findViewById(R.id.et_country_insertStamp);
et_value = (EditText) findViewById(R.id.et_value_insertStamp);
poza_timbru = (ImageView) findViewById(R.id.imgView_stampAdded_insertStamp);
insertStamp = (Button) findViewById(R.id.btn_insertStamp);
insertStamp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validation()) {
Timbru timbru = createTimbruFromComponents();
if (timbru != null) {
intent.putExtra(ADD_STAMP_KEY, timbru);
setResult(RESULT_OK, intent);
finish();
}
}
}
});
}
private Timbru createTimbruFromComponents() {
Integer year = Integer.parseInt(et_year.getText().toString());
String country = et_country.getText().toString();
Float value = Float.parseFloat(et_value.getText().toString());
Uri selectedImage=intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = 0;
String picturePath = null;
if (cursor != null) {
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
return new Timbru(year, country, value,picturePath);
}
private boolean validation() {
//only for EditTexts
if (et_year.getText() == null || et_year.getText().toString().trim().isEmpty() || et_year.getText().toString().length() < 4) {
Toast.makeText(getApplicationContext(), "Year is not valid", Toast.LENGTH_SHORT).show();
}
if (et_country.getText() == null || et_country.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Country is not valid", Toast.LENGTH_SHORT).show();
}
if (et_value.getText() == null || et_value.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Value is not valid", Toast.LENGTH_SHORT).show();
}
return true;
}
public void imgBtn_insertImagine(View view) {
//DIALOG BOX
final Dialog dialog = new Dialog(getApplicationContext());
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("PICK ONE");
Button exit = (Button) findViewById(R.id.btnExit_dialogBox);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnForGallery_dialogBox).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto_dialogBox).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openCamera();
}
});
dialog.show();
}
public void openCamera() {
Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intentCamera.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE_TAKEN);
}
}
public void openGallery() {
Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*"); //arata doar imagini, nu si video sau altceva
startActivityForResult(intentGallery, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_IMAGE_REQUEST:
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = 0;
String picturePath = null;
if (cursor != null) {
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
Timbru timbru = new Timbru();
timbru.setCountry("Madagascar");
timbru.setValue(20.4f);
timbru.setImagePath(picturePath);
timbru.setYear(1200);
ListaTimbru.getTimbre().add(timbru);
}
break;
case REQUEST_IMAGE_TAKEN:
if (requestCode == REQUEST_IMAGE_TAKEN && resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(imageUri, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
Timbru timbru = new Timbru();
timbru.setCountry("Australia");
timbru.setValue(55.5f);
timbru.setImagePath(picturePath);
timbru.setYear(1800);
ListaTimbru.getTimbre().add(timbru);
}
break;
}
}
}
In the same Activity(InsertStampActivity) you can use this code to display image from camera & gallery to imageview
case REQUEST_IMAGE_TAKEN:
if (requestCode == REQUEST_IMAGE_TAKEN && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
poza_timbru.setImageBitmap(photo); //poza_timbru is your imageview.
}
case PICK_IMAGE_REQUEST:
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
poza_timbru.setImageBitmap(thumbnail); //poza_timbru is your imageview.
}
Then in adapter class view add one imageview in R.Layout.row_layout2 pass your data to adapter class then display it in listview.
Hope it helps..!
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.
I try set image into ImageView from gallery.
public class CollageCreateActivity extends AppCompatActivity {
private static final String TAG ="MyLogs" ;
Draw2d draw2d;
static final int GALLERY_REQUEST = 1;
private final int TAKE_PICTURE_CAMERA = 2;
private Uri mOutputFileUri;
ArrayList<CollageView> collageViewList1;
ArrayList<CollageView> collageViewList2;
float width;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage_creator);
collageViewList1 = new ArrayList<>();
collageViewList2 = new ArrayList<>();
Data data = new Data();
draw2d = new Draw2d(this);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_1);
if (frameLayout != null) {
frameLayout.addView(draw2d);
}
createCollage(data, layout);
if (layout != null) {
layout.bringToFront();
}
click();
}
public void createCollage(Data data, LinearLayout layout) {
ArrayList<Integer> list = new ArrayList<>();
list.add((int) data.getMap().get("mainLayout"));
list.add((int) data.getMap().get("firstLayout"));
list.add((int) data.getMap().get("secondLayout"));
final LinearLayout layout1 = new LinearLayout(this);
final LinearLayout layout2 = new LinearLayout(this);
LinearLayout[] massLay = {layout, layout1, layout2};
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1;
layout1.setLayoutParams(params);
layout2.setLayoutParams(params);
for (int i = 0; i < (int) data.getMap().get("layButt1"); i++) {
final Button button = new Button(this);
button.setLayoutParams(params);
button.setTextSize(50);
button.setId(i);
button.setPadding(16, 16, 16, 16);
button.setText(R.string.plus);
layout1.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout1.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
saveFromGallery();
layout1.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
collageViewList1.add(collageView);
}
});
}
for (int j = 0; j < (int) data.getMap().get("layButt2"); j++) {
Button button2 = new Button(this);
button2.setLayoutParams(params);
button2.setTextSize(50);
button2.setId(j);
button2.setPadding(16, 16, 16, 16);
button2.setText(R.string.plus);
layout2.addView(button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout2.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
layout2.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
width = layout2.getWidth();
collageViewList2.add(collageView);
}
});
}
for (int x = 0; x < list.size(); x++) {
if (list.get(x) == 0) {
massLay[x].setOrientation(LinearLayout.HORIZONTAL);
} else {
massLay[x].setOrientation(LinearLayout.VERTICAL);
}
}
layout.addView(layout1);
layout.addView(layout2);
}
public void click() {
Button button = (Button) findViewById(R.id.butt);
if (button != null) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < collageViewList1.size(); i++) {
collageViewList1.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap1 = Bitmap.createBitmap(collageViewList1.get(i).getDrawingCache());
collageViewList1.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap1);
draw2d.listX.add(collageViewList1.get(i).getX());
draw2d.listY.add(collageViewList1.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
for (int i = 0; i < collageViewList2.size(); i++) {
collageViewList2.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap2 = Bitmap.createBitmap(collageViewList2.get(i).getDrawingCache());
collageViewList2.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap2);
draw2d.listX.add(collageViewList2.get(i).getX() + width);
draw2d.listY.add(collageViewList2.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
draw2d.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(draw2d.getDrawingCache());
draw2d.setDrawingCacheEnabled(false);
draw2d.invalidate();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
InputStream imageStream = null;
CollageView collageView = new CollageView(CollageCreateActivity.this);
switch(requestCode) {
case GALLERY_REQUEST:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
try {
imageStream=getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap= BitmapFactory.decodeStream(imageStream);
Log.d(TAG, "сетим з галереї1");
collageView.setImageBitmap(bitmap);
Log.d(TAG, "сетим з галереї");
}
break;
case TAKE_PICTURE_CAMERA:
if (data != null) {
if (data.hasExtra("data")) {
Bitmap thumbnailBitmap = data.getParcelableExtra("data");
collageView.setImageBitmap(thumbnailBitmap);
}
} else {
collageView.setImageURI(mOutputFileUri);
}
}
}
private void saveFromGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
}
When i try set image from folder "drawrable" it's work, but if i try load image and set from gallery it's don't work, all i have "W/EGL_genymotion: eglSurfaceAttrib not implemented" in logs
In this case you will have to create a content provider which will use to share your local (Application's internal) file to the camera activity.when you try to take picture from camera
try this code:
Content provider class
public class MyFileContentProvider extends ContentProvider {
public static final Uri CONTENT_URI =
Uri.parse("content://com.example.camerademo/");
private static final HashMap<String, String> MIME_TYPES = new
HashMap<String, String>();
static {
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
}
#Override
public boolean onCreate() {
try {
File mFile = new File(getContext().getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
mFile.createNewFile();
}
getContext().getContentResolver().notifyChange(CONTENT_URI, null);
return (true);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public String getType(Uri uri) {
String path = uri.toString();
for (String extension : MIME_TYPES.keySet()) {
if (path.endsWith(extension)) {
return (MIME_TYPES.get(extension));
}
}
return (null);
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
File f = new File(getContext().getFilesDir(), "newImage.jpg");
if (f.exists()) {
return (ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_WRITE));
}
throw new FileNotFoundException(uri.getPath());
}
#Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
throw new RuntimeException("Operation not supported");
}
#Override
public Uri insert(Uri uri, ContentValues initialValues) {
throw new RuntimeException("Operation not supported");
}
#Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
#Override
public int delete(Uri uri, String where, String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
}
Home.java:
public class Home extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
Button button1;
ImageView imageView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
imageView1 = (ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(this);
}
public void onClick(View v) {
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available",
Toast.LENGTH_LONG).show();
} }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(Tag, "Receive the camera result");
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
File out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
imageView1.setImageBitmap(mBitmap);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
imageView1 = null;
}
}
hope it will help you,otherwise u will contact me my email
id:daminimehra28#gmail.com
i use this (link or code) to store id and password of user
http://techblogon.com/android-login-registration-screen-with-sqlite-database-example/
problem is i want to store list view item permanently in my listview when user login against their account
private static int RESULT_LOAD_IMAGE = 1;
private String currentImageName = "ic_launcher";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_ad_layout);
Button saveButton = (Button) findViewById(R.id.buttonSaveAdd);
saveButton.setOnClickListener(this);
Button buttonaddimage = (Button) findViewById(R.id.buttonAddImage);
buttonaddimage.setOnClickListener(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want Create a new Add?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(Create_adds_Activity.this, Button_mak.class);
startActivity(intent);
}
});
builder.show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonAddImage:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
case R.id.buttonSaveAdd:
EditText editTextTitle = (EditText) findViewById(R.id.editTextTitle);
EditText editTextDes = (EditText) findViewById(R.id.editTextDescription);
EditText editTextOwner = (EditText) findViewById(R.id.editTextOwnerName);
EditText editTextOwnerEmail = (EditText) findViewById(R.id.editTextOwnerEmail);
EditText editTextPrice = (EditText) findViewById(R.id.editTextPrice);
//populating data object from the values received
//from view
String title = editTextTitle.getText().toString();
String description = editTextDes.getText().toString();
String ownerName = editTextOwner.getText().toString();
String ownerEmail = editTextOwnerEmail.getText().toString();
String pricce = editTextPrice.getText().toString();
Advertisement object = new Advertisement(title, description,
ownerName, ownerEmail, currentImageName, Integer.parseInt(pricce), 100);
Button_mak.ads.add(object);
this.finish();
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView10 = (ImageView) findViewById(R.id.creatae);
imageView10.setImageBitmap(BitmapFactory.decodeFile(picturePath));
currentImageName = ">>>"+picturePath;
}
i use array adapter
final Context context = this;
public static ArrayList<Advertisement> ads = new ArrayList<Advertisement>();
I would deffenitely recommend using SQLite to save your data.
In the beginning it might seem a bit complex, but when ur used to it, its an ease.
Here's a handy little tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/