I am trying to figure out where I went wrong either coding or logical flaw, I created a Recipe App that takes a couple of strings and an image, all data get saved into database and on the main screen I get a list of recipes from database.
Main Screen
Add / Edit Screen
Creating or Adding new Data is working as expected, all data get saved. The problem is everything can be updated except for the Image once it has been saved any second attempt doesn't seem to affect the image, the image remains the same.
The core principle is to set data to the views (When user start the activity onCreate or resume the activity onResume) and get data from the views (When user leaves onPause and onSaveInstanceState just incase an update was made)
Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
enableEdit();
fab.hide();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recipeDAOImp = new RecipeDAOImp(this);
recipeDAOImp.open();
findViews();
rowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(RecipeDAOImp.KEY_ID);
if (rowId == null) {
Bundle extras = getIntent().getExtras();
rowId = extras != null ? extras.getLong(RecipeDAOImp.KEY_ID)
: null;
}
populateData();
disableEdit();
}
private void findViews() {
// Finds Views and Set onClick to imageButton
}
private void disableEdit() {
// Disable Views
}
private void enableEdit() {
// Enables Views
}
private void populateData() {
// If rowId is available then user is trying to Edit Recipe
if (rowId != null) {
setTitle("Edit Recipe");
Recipe recipe = new Recipe(rowId);
Cursor cursor = recipeDAOImp.getRecipe(recipe);
startManagingCursor(cursor);
title.setText(cursor.getString(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_TITLE)));
ingredients.setText(cursor.getString(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_INGREDIENTS)));
steps.setText(cursor.getString(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_STEPS)));
category.setText(cursor.getString(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_CATEGORY)));
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), DbBitmapUtility.getImage(cursor.getBlob(
cursor.getColumnIndexOrThrow(RecipeDAOImp.KEY_IMAGE))));
image.setBackground(bitmapDrawable);
// Else user is Adding a new Recipe
} else {
fab.hide();
setTitle("Add Recipe");
enableEdit();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(RecipeDAOImp.KEY_ID, rowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateData();
}
private void saveState() {
// Get the values from the views
String titleString = title.getText().toString();
String ingredientString = ingredients.getText().toString();
String stepsString = steps.getText().toString();
String categoryString = category.getText().toString();
// Get the image from imageButton
Drawable drawable = image.getBackground();
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
byte[] imageData = DbBitmapUtility.getBytes(bitmap);
// Just to clarify image is never null as the backround is a camre image
if (titleString.equals(null) || "".equals(titleString) || ingredientString.equals(null) || "".equals(ingredientString) || stepsString.equals(null) || "".equals(stepsString) || categoryString.equals(null) || "".equals(categoryString) || imageData.equals(null) || "".equals(imageData)) {
Toast.makeText(this, "No Data Saved", Toast.LENGTH_SHORT).show();
} else {
Recipe recipe = new Recipe(titleString, ingredientString, stepsString, categoryString, imageData);
// If rowId is not Available then user is Creating a new Recipe
if (rowId == null) {
long id = recipeDAOImp.createRecipe(recipe);
if (id > 0) {
rowId = id;
}
} else {
recipe.setId(rowId);
recipeDAOImp.updateRecipe(recipe);
}
}
}
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
// Set the imageButton
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), imageBitmap);
image.setBackground(bitmapDrawable);
}
}
}
DAO
#Override
public boolean updateRecipe(Recipe recipe) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_TITLE, recipe.getTitle());
contentValues.put(KEY_INGREDIENTS, recipe.getIngredients());
contentValues.put(KEY_STEPS, recipe.getSteps());
contentValues.put(KEY_CATEGORY, recipe.getCategory());
contentValues.put(KEY_IMAGE, recipe.getImage());
return sqLiteDatabase.update(DATABASE_TABLE, contentValues, KEY_ID + "=" + recipe.getId(), null) > 0;
}
What could be the problem that I can update string data but I can't really update the image once its saved?
After much research and testing, the problem was simply the image button can not be reset.
image.setBackground(bitmapDrawable);
This method above seems not to work for an update, my quick fix was simply to leave the code as it is and simply add a detection onActivityResult to determine if its actually an update then, add the byte data to database directly, rather than updating the image button and then recreate() the Activity, expensive procedure but not costly for a simple app.
if (rowId != null) {
...
recipe.setImage(DbBitmapUtility.getBytes(imageBitmap));
recipeDAOImp.updateRecipe(recipe);
recreate();
}
All Working as expected.
My guess is that the problem is in your DAO code. I have a similar setup (sqlite table with text and blob columns, both get updated), so I know that what you're trying to do is possible.
Related
Here, I want to make an app which is having profile activity and user can see his/her information in that and the activity has one button for editing the profile. When button is clicked the new activity is opened where user can edit there information & press save button and then return to profile activity.
So my question is how can I reload the profile activity with edited information?
here is my Edit profile activity
public class EditProfileActivity extends AppCompatActivity implements View.OnClickListener {
Button save_profile;
RadioGroup radioGroup;
EditText user_name,user_email,user_phone,user_addhar_number,birthdate;
ImageView user_profile_bg,user_profile,back_arrow;
private static final int RESULT_LOAD_IMAGE=24;
//db_details
String db_email="",db_name="",db_birthday,db_phone=" ";
String db_profile_pic = "",db_profile_pic_bg = "",db_token="";
String email,phone,name,profile_pic_url=" ",gender=" ",birthday;
String token="",addhar_number,new_profile_pic_url;
private double currentLatitude;
private double currentLongitude;
private boolean check_flag = false;
byte[] profile_pic_array;
byte[] profile_pic_bg_array;
Bitmap bitmap_profile= null,bitmap_bg=null;
Calendar mycalender;
ImageView CurrentImageView = null;
int choosebutton;
private long imei_number = 0;
private ProgressDialog pDialog;
Bitmap selectedImage = null;
Bitmap selectedImage2 = null;
SQliteHandler db;
private static final String TAG = EditProfileActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
user_name =(EditText)findViewById(R.id.et_user_name);
user_email =(EditText)findViewById(R.id.et_user_email);
user_phone =(EditText)findViewById(R.id.et_user_phone);
user_addhar_number =(EditText)findViewById(R.id.et_user_aadhar_number);
birthdate = (EditText)findViewById(R.id.et_user_birthday);
user_profile_bg =(ImageView)findViewById(R.id.header_cover_image);
user_profile=(ImageView) findViewById(R.id.user_profile_photo);
back_arrow = (ImageView)findViewById(R.id.iv_back);
mycalender = Calendar.getInstance();
save_profile =(Button)findViewById(R.id.btn_profile_save);
db=new SQliteHandler(getApplicationContext());
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
back_arrow.setOnClickListener(this);
save_profile.setOnClickListener(this);
user_profile_bg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check_flag =true;
CurrentImageView = (ImageView) v;
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery,RESULT_LOAD_IMAGE);
choosebutton=1;
}
});
user_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check_flag =true;
CurrentImageView = (ImageView) v;
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery,RESULT_LOAD_IMAGE);
choosebutton=2;
}
});
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
mycalender.set(Calendar.YEAR, year);
mycalender.set(Calendar.MONTH, monthOfYear);
mycalender.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
if(db_birthday != null && db_birthday != " " ){
birthdate.setText(db_birthday);
birthdate.setClickable(false);
}else {
birthdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(EditProfileActivity.this, date, mycalender.get(Calendar.YEAR),
mycalender.get(Calendar.MONTH), mycalender.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
Intent data = getIntent();
if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")) {
name = data.getStringExtra("name");
email = data.getStringExtra("email");
profile_pic_url = data.getStringExtra("profile_url");
token = data.getStringExtra("token");
currentLatitude = data.getDoubleExtra("latitude",0.0);
currentLongitude = data.getDoubleExtra("longitude",0.0);
}else if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")){
name = data.getStringExtra("name");
phone = data.getStringExtra("phone");
profile_pic_url = data.getStringExtra("profile_url");
token = data.getStringExtra("token");
currentLatitude = data.getDoubleExtra("latitude",0.0);
currentLongitude = data.getDoubleExtra("longitude",0.0);
}
//load user data from sqlite
if(email != null && email !=" ") {
HashMap<String, String> user = db.getuserdetails(email);
db_name = user.get("name");
db_email = user.get("email");
db_phone = user.get("phone");
db_profile_pic = user.get("profile_pic");
db_profile_pic_bg = user.get("profile_pic_bg");
birthday = user.get("birthday");
db_token= user.get("token");
}else if(phone != null && phone !=" "){
HashMap<String, String> user = db.getuserdetails(phone);
db_name = user.get("name");
db_email = user.get("email");
db_phone = user.get("phone");
db_profile_pic = user.get("profile_pic");
db_profile_pic_bg = user.get("profile_pic_bg");
birthday = user.get("birthday");
db_token= user.get("token");
}
user_name.setText(name);
if ((email != " " && email != null)&&(Patterns.EMAIL_ADDRESS.matcher(email).matches())){
user_email.setText(email);
KeyListener keyListener = user_email.getKeyListener();
user_email.setKeyListener(null);
}else if((phone !=" " && phone !=null)&& (Pattern.compile("^[789]\\d{9}$").matcher(phone).matches())) {
user_phone.setText("+91 " + phone);
KeyListener keyListener = user_phone.getKeyListener();
user_phone.setKeyListener(null);
}
Glide.with(this)
.load(profile_pic_url)
.placeholder(R.drawable.default_avtar)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(user_profile);
radioGroup =(RadioGroup)findViewById(R.id.gender_rg);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int i) {
RadioButton rb=(RadioButton)radioGroup.findViewById(i);
switch (i){
case R.id.rb_male:
gender = "male";
break;
case R.id.rb_female:
gender = "female";
break;
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_profile_save:
name = user_name.getText().toString();
email = user_email.getText().toString();
phone = user_phone.getText().toString();
addhar_number = user_addhar_number.getText().toString();
birthday = birthdate.getText().toString();
if(!check_flag) {
if (profile_pic_url != null && !profile_pic_url.equals(" ") && !profile_pic_url.isEmpty()) {
BitMap m = new BitMap();
try {
bitmap_profile = m.execute(profile_pic_url).get();
bitmap_bg = BitmapFactory.decodeResource(getResources(),R.drawable.beach);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
profile_pic_array = bitmapToByte(bitmap_profile);
profile_pic_bg_array = bitmapToByte(bitmap_bg);
} else {
bitmap_profile = BitmapFactory.decodeResource(getResources(),R.drawable.default_avtar);
bitmap_bg = BitmapFactory.decodeResource(getResources(),R.drawable.beach);
profile_pic_array = bitmapToByte(bitmap_profile);
profile_pic_bg_array = bitmapToByte(bitmap_bg);
}
}else{
profile_pic_array = bitmapToByte(selectedImage2);
profile_pic_bg_array = bitmapToByte(selectedImage);
}
String profile_pic= null;
String profile_pic_bg = null;
profile_pic = Base64.encodeToString(profile_pic_array,Base64.DEFAULT);
profile_pic_bg = Base64.encodeToString(profile_pic_bg_array,Base64.DEFAULT);
db.updateUser(name,email,phone,addhar_number,gender,profile_pic,profile_pic_bg,birthday,token);
updateProfile();
break;
case R.id.iv_back:
Intent home = new Intent(getApplicationContext(),ProfileActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home);
break;
}
}
private void updateLabel() {
String myFormat = "dd/mm/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
birthdate.setText(sdf.format(mycalender.getTime()));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selected_image = data.getData();
new_profile_pic_url = selected_image.toString();
Log.d("new profile_pic_url",new_profile_pic_url);
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selected_image,filePath,null,null,null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
if(choosebutton==1) {
selectedImage = BitmapFactory.decodeFile(imagePath, options);
Glide.with(this)
.load(selected_image)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(CurrentImageView);
}else if(choosebutton ==2){
selectedImage2 = BitmapFactory.decodeFile(imagePath, options);
Glide.with(this)
.load(selected_image)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(CurrentImageView);
}
cursor.close();
}
}
public byte[] bitmapToByte(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,0,baos);
return baos.toByteArray();
} private class BitMap extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
bitmap = BitmapFactory.decodeStream(url.openStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
And my profile activity class is here
public class ProfileActivity extends Activity implements View.OnClickListener {
ImageView heder_bg,profile_pic,back;
Button edit_profile;
TextView tv_name,tv_email,tv_phone,tv_birthday;
String email=" ",phone=" ",name,profile_pic_url,token;
//db_details
String db_email="",db_name="",birthday = " ",db_phone=" ";
String db_profile_pic = "",db_profile_pic_bg = "";
private double currentLatitude;
private double currentLongitude;
//datetbase variables
SQliteHandler db;
private static final String TAG = ProfileActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
heder_bg =(ImageView)findViewById(R.id.profile_header_cover_image);
profile_pic = (ImageView)findViewById(R.id.profile_user_profile_photo);
back = (ImageView)findViewById(R.id.iv_profile_back);
edit_profile = (Button)findViewById(R.id.btn_edit_profile);
tv_name = (TextView)findViewById(R.id.profile_name);
tv_email = (TextView)findViewById(R.id.profile_email);
tv_phone = (TextView)findViewById(R.id.profile_phone);
tv_birthday = (TextView)findViewById(R.id.profile_birthday);
Intent data = getIntent();
if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")) {
name = data.getStringExtra("name");
email = data.getStringExtra("email");
profile_pic_url = data.getStringExtra("profile_url");
token = data.getStringExtra("token");
currentLatitude = data.getDoubleExtra("latitude",0.0);
currentLongitude = data.getDoubleExtra("longitude",0.0);
}
else if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")){
name = data.getStringExtra("name");
phone = data.getStringExtra("phone");
profile_pic_url = data.getStringExtra("profile_url");
token = data.getStringExtra("token");
currentLatitude = data.getDoubleExtra("latitude",0.0);
currentLongitude = data.getDoubleExtra("longitude",0.0);
}
db = new SQliteHandler(getApplicationContext());
//load user data from sqlite
if(email != null && email !=" ") {
HashMap<String, String> user = db.getuserdetails(email);
db_name = user.get("name");
db_email = user.get("email");
db_phone = user.get("phone");
db_profile_pic = user.get("profile_pic");
db_profile_pic_bg = user.get("profile_pic_bg");
birthday = user.get("birthday");
}else if(phone != null && phone !=" "){
HashMap<String, String> user = db.getuserdetails(phone);
db_name = user.get("name");
db_email = user.get("email");
db_phone = user.get("phone");
db_profile_pic = user.get("profile_pic");
db_profile_pic_bg = user.get("profile_pic_bg");
birthday = user.get("birthday");
}
edit_profile.setOnClickListener(this);
back.setOnClickListener(this);
load_user_info();
}
public void load_user_info(){
if(name != null && name !=""){
tv_name.setText(name);
}else if(db_name != null && db_name !=""){
tv_name.setText(db_name);
}
if (email != " " && email != null){
tv_email.setText(email);
}else if(db_email != null && db_email != "") {
tv_email.setText(db_email);
}else {
tv_email.setText(" ");
}
if(phone !=" " && phone !=null) {
tv_phone.setText("+91 " + phone);
}else if(db_phone !=null && db_phone !=" ") {
tv_phone.setText(db_phone);
}else {
tv_phone.setText("");
}
if(profile_pic_url!=null && profile_pic_url != "") {
Glide.with(this)
.load(profile_pic_url)
.error(R.drawable.default_avtar)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(profile_pic);
Glide.with(this)
.load(R.drawable.beach)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(heder_bg);
}
else if((db_profile_pic !=null && !db_profile_pic.equals(" "))&&(db_profile_pic_bg !=null && !db_profile_pic_bg.equals(" "))){
byte[] db_profile;
byte[] db_profile_bg;
Bitmap db_profile_bitmap,db_profile_pic_bg_bitmap;
db_profile = Base64.decode(db_profile_pic,Base64.DEFAULT);
db_profile_bitmap = getBitmap(db_profile);
db_profile_bg = Base64.decode(db_profile_pic_bg,Base64.DEFAULT);
db_profile_pic_bg_bitmap = getBitmap(db_profile_bg);
Glide.with(this)
.load(db_profile_bitmap)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(profile_pic);
Glide.with(this)
.load(db_profile_pic_bg_bitmap)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(heder_bg);
}else {
Glide.with(this)
.load(R.drawable.default_avtar)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(profile_pic);
Log.d("Default image set",TAG);
}
if(birthday !=" " && birthday !=null && birthday.equals("test")){
tv_birthday.setText("Born on " + birthday);
} else {
tv_birthday.setText(" ");
}
}
#Override
public void onResume(){
super.onResume();
load_user_info();
Log.d("in resume methode",TAG);
}
public Bitmap getBitmap(byte[] bitmap) {
return BitmapFactory.decodeByteArray(bitmap , 0, bitmap.length);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_edit_profile:
Intent edit_profile = new Intent(getApplicationContext(),EditProfileActivity.class);
edit_profile.putExtra("name",name);
if((email !=null && email !="") && Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
edit_profile.putExtra("email", email);
}else if(phone != null && phone !="") {
edit_profile.putExtra("phone", phone);
}
edit_profile.putExtra("profile_url",profile_pic_url);
edit_profile.putExtra("token",token);
edit_profile.putExtra("latitude",currentLatitude);
edit_profile.putExtra("longitude",currentLongitude);
startActivity(edit_profile);
break;
case R.id.iv_profile_back:
Intent home = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(home);
break;
}
}
}
Before OP posted code
You can define a function that loads your data for ProfileActivity and call it in onResume().
#Override
public void onResume() {
super.onResume();
if (this.reloadNedeed)
this.reloadProfileData();
this.reloadNeeded = false; // do not reload anymore, unless I tell you so...
}
This way, since onResume() is also called after onCreate(),
you'd be using the same code both for when the the activity is first created and for when you re-open it (e.g. when you come back from another activity, or another app).
In order to make it work, reloadNedeed must be set to true by default:
private boolean reloadNeed = true;
In order to start the EditActivity you can do:
startActivityForResult(new Intent(EditActivity.class), EDIT_CODE);
where EDIT_CODE can be any number, e.g:
private static final int EDIT_CODE = 31;
When you want to get back to from EditActivity you just call:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_OK,returnIntent); // or RESULT_CANCELED if user did not make any changes
// it would be better to use some custom defined codes here
finish();
This would trigger the function onActivityResult(int, int Intent) in ProfileActivity, in which you can tell the activity to reload the data.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDIT_CODE) { // Ah! We are back from EditActivity, did we make any changes?
if (resultCode == Activity.RESULT_OK) {
// Yes we did! Let's allow onResume() to reload the data
this.reloadNeeded = true;
}
}
onResume() is called after onActivityResult(), so we can safely decide whether to put reloadNeeded to true, or just leave it to false.
Edit: After OP posted code
I haven't tested your code, but I may have found some oddities just by looking at it.
I believe you may have a problem with some if-else conditions in your load_user_info() function.
When you get back from EditActivity the activity is (most likely) not created again. Only onResume() is called, which calls load_user_info();
But since the Activity isn't recreated, your variables hold the same values from when they were initialized in onCreate().
When he does check the data:
if(name != null && name !=""){
tv_name.setText(name);
}else if(db_name != null && db_name !=""){
tv_name.setText(db_name);
}
your activity says:
Heyy, name is not null and is different than "" (by the way you should use equals(), even for literals)
Therefore, I will execute this piece of code tv_name.setText(name);, and since it's an if else statement, the second block will NOT be executed.
So your activity, never really displays the updated data. The same data as before is displayed.
You should try to apply the same logic as I posted in my original answer.
Hope I understood your question right...
There are multiple ways to accomplish what you are asking. There's the simple(ish) way and the hard(er) and more correct way.
The easiest way is to refresh the data you're expecting in the onResume of the activity you are returning to. If you navigate to a different activity, the previous activity will call onPause, then onResume when you return, and at that time you can check for new data and load it in place. That's the quicker way.
A better, more correct way of doing it would be to implement a ViewModel and use LiveData to allow the Activity to always have the most up to date data. This does require a bit of extra effort on your end to make sure your app has proper architecture, but in the long run pays off way better. Check out Android's architecture components.
To refresh your activity data:
finish();
startActivity(getIntent());
onBackPressed or finish() then its call and refresh
#Override
public void onRestart()
{
super.onRestart();
finish();
startActivity(getIntent());
}
I hope this helpful...
Good day!
i am quite new in programming and i am trying to make a simple android app. i have here 2 edittext and 2 buttons inside my activity and what i want them to do is get the number of prefered contacts to text and the 1st edittext and 1st button succeeded but my problem is the button 2 also put the number on the 1st edittext that is supposed to put in 2nd edittext any idea?
this is my code..
public class SA extends Activity {
EditText con1;
EditText con2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_s);
con1 = (EditText) findViewById(R.id.cnum1);
con2 = (EditText) findViewById(R.id.cnum2);
((Button)findViewById(R.id.btnSelectContact1)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
((Button)findViewById(R.id.btnSelectContact2)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v2) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent2.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent2, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,},
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
showSelectedNumber(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
protected void onActivityResult2(int requestCode2, int resultCode2, Intent data2) {
if (data2 != null) {
Uri uri2 = data2.getData();
if (uri2 != null) {
Cursor c2 = null;
try {
c2 = getContentResolver().query(uri2, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,},
null, null, null);
if (c2 != null && c2.moveToNext()) {
String number2 = c2.getString(0);
showSelectedNumber(number2);
}
} finally {
if (c2 != null) {
c2.close();
}
}
}
}
}
public void showSelectedNumber(String number) {
con1.setText(number);
}
public void showSelectedNumber2(String number2) {
con2.setText(number2);
}
No need of onActivityResult2() because startActivityForResult() gives you result back in onActivityResult() method.
So now your question would be, how you can manage different requests? Well, that you can do by passing different request code while calling startActivityForResult().
For example:
startActivityForResult(intent, 1); // first request
startActivityForResult(intent, 2); // second request
// you can pass any random number as a request code
Now you just need to perform the operations according to the request code received back in onActivityResult() method.
For example:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if(requestCode == 1) {
...
...
} else if (requestCode == 2) {
...
...
}
}
}
I've completely re-wrote the question to single down the scope.
I have Two Fragments that Flip around like a card(Left, Right). When the front fragment disappears flips it shows the back. Once the button is clicked again it flips to the front again but the ImageView on the front fragment is gone.
I have tried different methods of saving the data of the Image picked.
Saving the Fragment onSaveInstanceState
This gives me a Null Pointer, so I figured I needed something more constant once being created.
So now I save the image to SDCard once Picked
This I figured would work and just check the path and grab it if its flipped to the front or the activity is recreated.
Here is some Code
onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_postcard_activity);
//UI call
frontImageView = (ImageView) findViewById(R.id.imageView);
Log.d(tag, "onCreate() Instance:" + savedInstanceState);
//fragment start
if (savedInstanceState == null) {
Log.d(tag,"Instance Null");
getFragmentManager()
.beginTransaction()
.add(R.id.postcardFrame, new CardFrontFragment())
.commit();
if(!mShowingBack){
Log.d(tag,"Not showing back");
if(newPath != null && newPath != ""){
Log.d(tag, "entered new path, not empty");
Drawable drawable = Drawable.createFromPath(newPath);
Log.d(tag, "Should be setting saved image.");
frontImageView.setImageDrawable(drawable);
}
}
}
else
{
mShowingBack = (getFragmentManager().getBackStackEntryCount() > 0);
Log.d(tag, "Instance is not Null");
}
Flip Button Click Listener
//flip card
final Button cardBackButton = (Button) findViewById(R.id.cardBackButton);
cardBackButton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
flipCard();
});
flipCard Method:
private void flipCard()
{
Log.d(tag2, "Log after flipCard:" + mShowingBack);
if(mShowingBack)
{
//Flip to front
flipFront();
return;
}
// Flip to back
flipBack();
}
I set the Image onActivityResult from their PhotoGallery
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
Uri photoUri = intent.getData();
if (photoUri != null) {
try {
ImageView setImage = (ImageView)findViewById(R.id.imageView);
frontImage = MediaStore.Images.Media.getBitmap(this
.getContentResolver(), photoUri);
imageSet = true;
//save image to SD
if(imageSet == true){
Log.d(tag, "Inside Image Set if Statement");
String path = getExternalCacheDir() + "Postcards.png";
if(path != null && path != ""){
Log.d(tag, "Path is:" + path);
File file = new File(path);
newPath = file.getAbsolutePath();
Log.d(tag, "New Path:" + newPath);
if(file.exists()){
Log.d(tag, "File Exists");
Drawable d = Drawable.createFromPath(newPath);
setImage.setImageDrawable(d);
}else{
try{
Log.d(tag,"File didnt exist");
FileOutputStream out = new FileOutputStream(file);
frontImage.compress(Bitmap.CompressFormat.PNG, 90, out);
if(file.exists()){
Log.d(tag, "file exists now");
newPath = file.getAbsolutePath();
Drawable b = Drawable.createFromPath(newPath);
setImage.setImageDrawable(b);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
This is how I am accessing the image and trying to set it to my ImageView on Restart()
if(imageSet == true){
if(newPath != null && newPath != ""){
ImageView view = (ImageView) findViewById(R.id.imageView);
Drawable drawable = Drawable.createFromPath(newPath);
view.setImageDrawable(drawable);
}
}
This seems like the best route in getting the image and setting it but it wont work.
What would be best practice and how can I get it to perform the way I need it to?
Much appreciated with any help!
savedInstanceState serves a different purpose.
onSaveInstanceState (Bundle):
This method is called before an activity may be killed so that when it
comes back some time in the future it can restore its state
And, in your particular case, it may not even be required. On button click, you are changing fragments, not restarting your app.
From what I can see, you are letting the user create a postcard: a picture on one side (say, Side A) and a message on flip-side (say, Side B). When the app starts, Side A is in view. In some manner, you let the user select an image from the gallery. I will assume that onActivityResult(int, int, Intent) works as expected, and sets the image to ImageView - R.id.imageView. When a button is clicked, the view is changed to Side B. And when the button is clicked again, the view changes to Side A, but the image selected by user is not there.
One thing you can do inside onActivityResult(int, int, Intent) is: save the path of the image in SharedPreferences.
SharedPreferences preferences;
final String PREFS = "your.application.name.prefs";
// Keyword to find the path
final String IMAGE_SELECTED_BY_USER = "image_selected_by_user";
// Use a default image when the user starts the app for the first time
// or if the retrieved path points to a deleted image etc.
final String PATH_TO_A_DEFAULT_IMAGE = "path_to_a_default_image"
#Override
protected void onCreate(Bundle savedInstanceState) {
....
....
preferences = getActivity().getSharedPreferences(PREFS, 0);
imagePath = preferences.getString(IMAGE_SELECTED_BY_USER, PATH_TO_A_DEFAULT_IMAGE);
frontImageView = (ImageView) findViewById(R.id.imageView);
Drawable drawable = null;
if (new File(imagePath).exists()) {
drawable = Drawable.createFromPath(imagePath);
} else {
drawable = Drawable.createFromPath(PATH_TO_A_DEFAULT_IMAGE);
}
frontImageView.setImageDrawable(drawable);
getFragmentManager()
.beginTransaction()
.add(R.id.postcardFrame, new CardFrontFragment())
.commit();
....
....
}
In onActivityResult(int, int, Intent), save the image path:
if(file.exists()){
Log.d(tag, "File Exists");
Drawable d = Drawable.createFromPath(newPath);
setImage.setImageDrawable(d);
Editor editor = preferences.edit();
editor.putString(IMAGE_SELECTED_BY_USER, newPath);
editor.commit();
} else{
try{
Log.d(tag,"File didnt exist");
FileOutputStream out = new FileOutputStream(file);
frontImage.compress(Bitmap.CompressFormat.PNG, 90, out);
if (file.exists()) {
Log.d(tag, "file exists now");
newPath = file.getAbsolutePath();
Drawable b = Drawable.createFromPath(newPath);
setImage.setImageDrawable(b);
Editor editor = preferences.edit();
editor.putString(IMAGE_SELECTED_BY_USER, newPath);
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
This way, when the user starts the app, he/she will see either the default image, or an image previously selected.
Where savedInstanceState would be useful: Let's say you give the user an option of writing a short message on Side B. Now, if while writing the message, the user rotates the device from Landscape to Portrait (or vice-versa), the message he/she wrote will be gone because the activity will be destroyed and recreated. To save the message, you would use onSaveInstanceState(Bundle):
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("Text_To_Save", someEditText.getText().toString());
}
On rotation, activity's onCreate(Bundle)' will be called. The bundle passed is the same one fromonSaveInstanceState(Bundle)`. To retrieve the text:
String savedString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.contains("Text_To_Save")) {
savedString = savedInstanceState.getString("Text_To_Save");
}
}
someEditText.setText(savedString);
}
I try to pass a string from one activity to another activity.
This is the coding in Activity A:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("UserName", UserName);
Log.i(Tag, "UserName1: "+ UserName);
super.onSaveInstanceState(savedInstanceState);
}
In Activity B I use this code to get the string:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.i(Tag, "UserName2: "+ UserName);
}
But the logcat shown the first log "UserName1" when I clikc the open to Activity B,
and show the second log "UserName2" as "null".
May I know what wrong with my code?
What I want to do is Activity A pass the String in Activity B when I click the "button" and intent to Activity B. So I can get the String value in Activity B.
Any Idea? Cause I getting error when using intent.putStringExtra() and getintent.getStringExtra(), so I change to use onSaveInstanceState (), but still having problem.
EDIT:
This is my original code, I can get the String in Activity B, but unexpected I can't save my data in Sqlite. If remove the putString Extra then everything go smoothly.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addItem = new Intent(ItemActivity.this, AddEditItem.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
addItem.putStringExtra("UserName", UserName);
Log.e(Tag, "UseName: "+ UserName);
startActivity(addItem);
return super.onOptionsItemSelected(item);
}
Code in Activity B:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
UserName = (String) getIntent().getStringExtra("UserName");
Log.e(Tag, "UserName3: "+ UserName);
}
Full code for Activity B:
public class AddEditItem extends Activity implements OnItemSelectedListener {
private static final String Tag = null;
private EditText inputItemName;
private EditText inputItemCondition;
private EditText inputEmail;
private Button btnGal, btnConfirm;
private Bitmap bmp;
private ImageView ivGalImg;
private Spinner spinner;
String[] category = {"Books", "Clothes & Shoes", "Computer", "Electronics", "Entertainment", "Food & Drinks",
"Furnitures", "Mobile Phone", "Other", "UKM"};
String selection;
String filePath, itemName, itemCondition;
String UserName, user;
private int id;
private byte[] blob=null;
byte[] byteImage2 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
setUpViews();
if (savedInstanceState != null){
UserName = savedInstanceState.getString("UserName");
}
Log.e(Tag, "UserName2: "+ UserName);
//UserName = (String) getIntent().getStringExtra("UserName");
//Log.e(Tag, "UserName3: "+ UserName);
}
private void setUpViews() {
inputItemName = (EditText)findViewById(R.id.etItemName);
inputItemCondition = (EditText)findViewById(R.id.etItemCondition);
inputEmail = (EditText)findViewById(R.id.etEmail);
ivGalImg = (ImageView) findViewById(R.id.ivImage);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddEditItem.this, android.R.layout.simple_spinner_dropdown_item, category);
spinner = (Spinner)findViewById(R.id.spnCategory);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
user=extras.getString("user");
inputItemName.setText(extras.getString("name"));
inputItemCondition.setText(extras.getString("condition"));
inputEmail.setText(extras.getString("email"));
selection = extras.getString("category");
byteImage2 = extras.getByteArray("blob");
if (byteImage2 != null) {
if (byteImage2.length > 3) {
ivGalImg.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2,0,byteImage2.length));
}
}
}
btnGal = (Button) findViewById(R.id.bGallary);
btnGal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
btnConfirm = (Button) findViewById(R.id.bConfirm);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputItemName.getText().length() != 0 && inputItemCondition.getText().length() != 0
&& inputEmail.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveItemTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveItem();
return null;
}
#Override
protected void onPostExecute(Object result) {
Toast.makeText(getApplicationContext(),
"Item saved", Toast.LENGTH_LONG)
.show();
finish();
}
};
saveItemTask.execute((Object[]) null);
Toast.makeText(getApplicationContext(),
"Item saved reconfirm", Toast.LENGTH_LONG)
.show();
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditItem.this);
alert.setTitle("Error In Save Item");
alert.setMessage("You need to fill in all the item details");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveItem() {
if(bmp!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=byteImage2;}
ItemSQLiteConnector sqlCon = new ItemSQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertItem(UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
else {
sqlCon.updateItem(id, UserName, inputItemName.getText().toString(),
inputItemCondition.getText().toString(),
inputEmail.getText().toString(),
selection, blob);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
super.onActivityResult(requestCode, resultCode, resultdata);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = resultdata.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 filePath = cursor.getString(columnIndex);
cursor.close();
// Convert file path into bitmap image using below line.
bmp = BitmapFactory.decodeFile(filePath);
ivGalImg.setImageBitmap(bmp);
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
TextView tv = (TextView)view;
selection = tv.getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
onSaveInstanceState is not used in that purpose, its used to save your activity state on for example orientation change, or when you leave an activity and get back to it.
What you need is to use intents.
Other than starting activity, intents can also carry some information throughout app, like this:
This would be activity 1:
Intent = new Intent (getApplicationContext(), Activity2.class);
intent.putExtra("UserName", UserName);
startActivity(intent);
and to recover it in second activity use:
String username = getIntent().getExtras().getString("UserName");
May I know what wrong with my code?
onSaveInstanceState() has nothing to do with passing data between activities. Instead, you need to put your string in an extra on the Intent used with startActivity().
Cause I getting error when using intent.putExtra() and getintent.getExtra()
Since that is the correct approach (albeit using getStringExtra()), please go back to it and fix whatever error you are encountering.
I had idea to build simple app that can store text and images. I started from Notepad Tutorial (http://developer.android.com/training/notepad/index.html) from first and second exercise.
After I did second I arrange exercise to handle images, it was working very well unless user tapped back button in device. With help came thid exercise where the goal to handling life-cycle events. I managed to did it, it is working very well for old entries in database, but when I try to add new Image, my ImageView is not filled with just taken photo.
Can you spot where is the problem?
public class ParagonArmageddonEdit extends Activity
{
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private ImageView imageContainer;
private byte[] imageInByteArray;
private Button takePhotoButton;
private ParagonDbAdapter mDbHelper;
private static final long serialVersionUID = 1L;
public boolean classEnabled;
private static final int CAMERA_REQUEST = 1888;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mDbHelper = new ParagonDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.paragonarmageddon_edit);
setTitle(R.string.edit_note);
this.imageContainer = (ImageView) this.findViewById(R.id.ImageView);
this.takePhotoButton = (Button) this.findViewById(R.id.photoButton);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
Button confirmButton = (Button) findViewById(R.id.Save);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(ParagonDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(ParagonDbAdapter.KEY_ROWID)
: null;
}
populateFields();
this.takePhotoButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//camera Intent
Intent IntentKamery = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(IntentKamery, CAMERA_REQUEST);
}
});
confirmButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
setResult(RESULT_OK);
finish();
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(ParagonDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(ParagonDbAdapter.KEY_BODY)));
byte[] photo = note.getBlob(note.getColumnIndexOrThrow(ParagonDbAdapter.KEY_ZDJECIE));
Bitmap photoConvertedToBitmap = BitmapFactory.decodeByteArray(zdjecie, 0, photo.length);
this.imageContainer.setImageBitmap(photoConvertedToBitmap);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{
Bitmap photoConvertedToBitmap = (Bitmap) data.getExtras().get("data");
imageContainer.setImageBitmap(photoConvertedToBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photoConvertedToBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
imageInByteArray = stream.toByteArray();
photoTaken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(ParagonDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
imageContainer.buildDrawingCache();
Bitmap photoConvertedToBitmap = imageContainer.getDrawingCache();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photoConvertedToBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
imageInByteArray = stream.toByteArray();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, imageInByteArray);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, imageInByteArray);
}
}
}
The Intent android.provider.MediaStore.ACTION_IMAGE_CAPTURE does not return a byte array in its 'data' Extra. It returns a Uri to the image, which must be opened e.g.
Uri uri = data.getData();
This provides the content path to the image, which can be loaded using a ContentResolver:
InputStream input = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input);
You will need to ensure you check that the Uri exists and handle errors gracefully, you should never assume that another app is going to do something sensible, and should expect malformed/missing data wherever possible.