Here, I have to select an image from gallery or camera. When user selects image from gallery, that selected image should be displayed to next activity. But here these both activities are under the same tab, say tab A. Means in tab A there are two activities. In first activity, user has two options to select image either from gallery or from camera. And in second activity under same tab A, user gets that selected image. But here I'm not getting the expected output. Below is my code...
MainActivity.java
public class MainActivity extends TabActivity {
TabHost tabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources ressources = getResources();
tabHost = getTabHost();
Intent intentProfile = new Intent().setClass(this, Tab1.class);
TabSpec tabProfile = tabHost
.newTabSpec("Profile")
.setIndicator("Profile", ressources.getDrawable(R.drawable.ic_launcher))
.setContent(intentProfile);
Intent intentFriends = new Intent().setClass(this, Tab2.class);
TabSpec tabFriends = tabHost
.newTabSpec("Friends")
.setIndicator("Friends", ressources.getDrawable(R.drawable.ic_launcher))
.setContent(intentFriends);
tabHost.addTab(tabProfile);
tabHost.addTab(tabFriends);
tabHost.setCurrentTab(0);
}
public void switchTabBar(int tab) {
tabHost.setCurrentTab(tab);
}
#Override
public void onBackPressed() {
// Called by children
MainActivity.this.finish();
}
}
ABCGroup.java
public class ABCGroup extends ActivityGroup{
public static ABCGroup group;
private ArrayList<View> history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.history = new ArrayList<View>();
group = this;
View view = getLocalActivityManager().startActivity
("ParentActivity",
new Intent(ABCGroup.this, Tab1.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
}
public void replaceView(View v) {
// Adds the old one to history
history.add(v);
// Changes this Groups View to the new View.
setContentView(v);
}
public void back() {
if(history.size() > 0) {
history.remove(history.size()-1);
if(history.size()<=0){
finish();
}else{
setContentView(history.get(history.size()-1));
}
}else {
finish();
}
}
#Override
public void onBackPressed() {
ABCGroup.group.back();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK){
ABCGroup.group.back();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Tab1.java
public class Tab1 extends ActivityGroup {
Button gallery, camera;
private ArrayList<View> myActivityHistory;
private static final int REQUEST_ID = 1;
private static final int HALF = 2;
private static final int TAKE_PICTURE = 3;
private Uri mUri;
private Bitmap mPhoto;
int i = 0;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
myActivityHistory = new ArrayList<View>();
gallery = (Button)findViewById(R.id.gallery);
camera = (Button)findViewById(R.id.camera);
gallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_ID);
}
});
camera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
startActivityForResult(i, TAKE_PICTURE);
}
});
}
public void replaceContentView(String id, Intent newIntent, int flag)
{
View mview = getLocalActivityManager().startActivity(id,newIntent.addFlags(flag)).getDecorView();
ABCGroup.group.replaceView(mview);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK)
{
getContentResolver().notifyChange(mUri, null);
ContentResolver cr = getContentResolver();
try
{
mPhoto = null;
mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, mUri);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
break;
case REQUEST_ID :
InputStream stream = null;
if (resultCode == Activity.RESULT_OK) {
try
{
stream = getContentResolver().openInputStream(data.getData());
Bitmap original;
original = null;
original= BitmapFactory.decodeStream(stream);
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
Intent in = new Intent(Tab1.this, Second.class);
replaceContentView("activity3", in, Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
catch (Exception e)
{
e.printStackTrace();
}
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Toast.makeText(getBaseContext(), "" + cursor.getString(column_index) , 5000).show();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("data", cursor.getString(column_index) );
editor.commit();
return cursor.getString(column_index);
}
}
Second.java
public class Second extends ActivityGroup {
public static Bitmap bmp;
String path;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button btn = (Button)findViewById(R.id.button1);
iv = (ImageView)findViewById(R.id.imageView1);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
path = preferences.getString("data", "");
File imgFile = new File(path);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ABCGroup.group.back();
}
});
}
#Override
public void onBackPressed() {
// this.getParent().onBackPressed();
Intent intent = new Intent(Second.this, Tab1.class);
Tab1 parentActivity = (Tab1)getParent();
parentActivity.replaceContentView("Profile", new Intent(Second.this, Tab1.class), Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
}
Related
public class addBoard extends AppCompatActivity {
private final int GET_GALLERY_IMAGE = 200;
Uri image;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addboard);
final EditText EDTITLE = findViewById(R.id.editTitle);
final EditText EDTEXT = findViewById(R.id.editText);
ImageView imgView = (ImageView)findViewById(R.id.imageView);
Button addPhoto = findViewById(R.id.photo);
addPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, GET_GALLERY_IMAGE);
}
});
try {
Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), image);
imgView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Button backButton = findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Input_Title", EDTITLE.getText().toString());
intent.putExtra("Input_Text", EDTEXT.getText().toString());
intent.putExtra("Input_Image", image);
setResult(RESULT_OK, intent);
finish();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_GALLERY_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectImage = data.getData();
image = selectImage;
}
}
}
If you run this code in another project, there is no error, but if you use it in this project, you will get an error. Why is that?
Error :Caused by: java.lang.NullPointerException: uri
at com.example.toolbar.addBoard.onCreate**(addBoard.java:45)** // blue line
An error occurs during the operation to place Uri as bitmap in imageView.
I am making a birthday wisher app, everthing works fine but I want that user can select image from gallary and it passes to 2nd activity, when timer is finised, I used ticker coundown in this.
My MainActivity
public class MainActivity extends AppCompatActivity {
CircularView circularViewWithTimer;
EditText entertime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
entertime = (EditText) findViewById(R.id.Txt_time);
circularViewWithTimer = findViewById(R.id.circular_view);
CircularView.OptionsBuilder builderWithTimer =
new CircularView.OptionsBuilder()
.shouldDisplayText(true)
.setCounterInSeconds(15)
.setCircularViewCallback(new CircularViewCallback() {
#Override
public void onTimerFinish() {
String name = entertime.getText().toString();
Intent i = new Intent(MainActivity.this, Bday_page.class);
i.putExtra("text", name);
startActivity(i);
finish();
}
#Override
public void onTimerCancelled() {
// Will be called if stopTimer is called
Toast.makeText(MainActivity.this, "CircularCallback: Timer Cancelled ", Toast.LENGTH_SHORT).show();
}
});
circularViewWithTimer.setOptions(builderWithTimer);
}
public void btn_pause(View view) {
circularViewWithTimer.pauseTimer();
}
public void btn_start(View view) {
MediaPlayer mMediaPlayer;
if(entertime.getText().toString().isEmpty()){
Toast.makeText(this, "Enter name of bday boy", Toast.LENGTH_SHORT).show();
}
else {
circularViewWithTimer.startTimer();
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this,R.raw.count);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
}
public void btn_resume(View view) {
circularViewWithTimer.resumeTimer();
}
}
My 2nd Activity
public class Bday_page extends AppCompatActivity {
TextView nameuser;
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bday_page);
nameuser = (TextView)findViewById(R.id.txt_imagename);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.happybady);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
Intent i = getIntent();
nameuser.setText(i.getStringExtra("text"));
}
}
first of all you have to request the storage permission in the manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
after that in your MainActivity make your onTimerFinish methods like these
#Override
public void onTimerFinish() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent,1777);
}
now you requsted the image from Galary then add onActivityResult method to your main activity to receive the image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
Uri uri = data.getData();
Cursor cursor;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
String name = entertime.getText().toString();
Intent i = new Intent(MainActivity.this, Bday_page.class);
i.putExtra("text", name);
i.putExtra("imagePath",picturePath )
startActivity(i);
finish();
}}}
now you get the path of selected image and send it to the next activity
and in your 2nd Activity receive the image like these
Intent i = getIntent();
nameuser.setText(i.getStringExtra("text"));
String imagePath = i.getStringExtra("imagePath") //add these
now you have the image Path in the new activity you can do what you want to do with it
My Main2Activity class
public class Main2Activity extends AppCompatActivity {
private static int PICK_IMAGE_REQUEST = 1;
ImageView imgView;
static final String TAG = "Main2Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void loadImagefromGallery(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) {
final Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
imgView = (ImageView) findViewById(imageView);
imgView.setImageBitmap(scaled);
Button button3 = (Button) findViewById(bt_tab3);
button3.setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.setData(uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
});
} else {
Toast.makeText(this, "No.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Oops! Sorry", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
And the Main3Activity
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri imageUri = getIntent().getData();
imageView.setImageURI(imageUri);
}
}
How can I show same gallery image in MainActivity and another Activity?
Move your Button related codes into onCreate() and send Uri as String using intent extras.
Update Main2Activity as below:
public class Main2Activity extends AppCompatActivity {
static final String TAG = "Main2Activity";
private static int PICK_IMAGE_REQUEST = 1;
ImageView imgView;
Button button3;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imgView = (ImageView) findViewById(R.id.imageView);
button3 = (Button) findViewById(R.id.bt_tab3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
}
});
}
public void loadImagefromGallery(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) {
// Get uri
imageUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
// Set image
imgView.setImageBitmap(scaled);
} else {
Toast.makeText(this, "No.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Oops! Sorry", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
Get Uri as string from intent and construct Uri from string using Uri.parse() method.
Update Main3Activity as below:
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
if (getIntent().getExtras() != null) {
imageUri = Uri.parse(getIntent().getStringExtra("imageUri"));
imageView.setImageURI(imageUri);
}
}
}
Pass the file path from the uri as String like this to Main3Activity.
button3.setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.putExtra("filePath", uri.getPath());
startActivity(intent);
}
});
And in Main3Activity get the data passed from the calling Activity like this.
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
File file = new File(getIntent().getStringExtra("filePath"));
setImageFromFileIntoImageView(file);
}
private void setImageFromFileIntoImageView (File imgFile)
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}
}
}
You need to add the following permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
based on you not accepting previous answers here is a different approach :
first convert your image to byte array like :
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is bitmap object
byte[] b = baos.toByteArray();
then convert that into string like :
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
then from your first activity make an intent and put that string as an extra like:
Intent imageIntent = new Intent(context,Main3Activity.class);
imageIntent.putExtra("image",encodedImage);
startActivity(imageIntent);
and after that it is so easy to get this string in the next activity using getIntent and then getExtra
hope this helps.
The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && 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]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.
How to
Select an image from gallery.
Get Uri of this image.
Pass Uri to another Activity.[shared preffrence's ??]
Load image using uri.
Set it as backgound of Inbox Activity:
#SuppressLint("NewApi")
public class Inbox extends ListActivity
{
ArrayList<String> ListItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri urisms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(urisms, null, null ,null,null);
if(c.moveToFirst())
{
for(int i=0; i < c.getCount(); i++)
{ String body = c.getString(c.getColumnIndexOrThrow("body")).toString();
ListItems.add(body);
c.moveToNext();
}
if(ListItems.isEmpty())
ListItems.add("no messages found !!");
}
c.close();
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ListItems);
setListAdapter(adapter);
}
}
Launch a "get image" intent:
public static final int REQUEST_CODE = 0;
Intent target = new Intent(Intent.ACTION_GET_CONTENT);
target.setType("image/*");
target.addCategory(Intent.CATEGORY_OPENABLE);
Intent intent = Intent.createChooser(target, "Choose Image");
try {
startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// ...
}
Get Uri and pass to new Activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
// The Uri of the Image selected
Uri uri = data.getData();
Intent i = new Intent(this, NewActivity.class);
i.setData(uri);
startActivity(i);
}
}
Set as the background in your new ListActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = getIntent().getData();
Drawable drawable = getDrawable(uri);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
getListView().setBackgroundDrawable(drawable);
} else {
getListView().setBackground(drawable);
}
}
private Drawable getDrawable(Uri uri) {
Drawable drawable = null;
InputStream is = null;
try {
is = getContentResolver().openInputStream(uri);
drawable = Drawable.createFromStream(is, null);
} catch (Exception e) {
// ...
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e2) {
}
}
}
return drawable;
}
Final Working code :
ChangeBackground.java
Choose Image from gallery here .
Inbox.java
Show's Messages from inbox with choosen Image as Background.
public class ChangeBackground extends Activity{
private static final int REQUEST_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent target = new Intent(Intent.ACTION_GET_CONTENT);
target.setType("image/*");
target.addCategory(Intent.CATEGORY_OPENABLE);
Intent intent = Intent.createChooser(target, "Choose Image");
try {
startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// ...
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Uri uri = data.getData();
Intent i = new Intent(this,Inbox.class);
i.setData(uri);
startActivity(i);
}
}
}//end of ChangeBackground
public class Inbox extends ListActivity
{
ArrayList<String> ListItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri uri = getIntent().getData();
Drawable drawable = getDrawable(this, uri);
getListView().setBackgroundDrawable(drawable);
Uri urisms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(urisms, null, null ,null,null);
if(c.moveToFirst())
{
for(int i=0; i < c.getCount(); i++)
{ String body = c.getString(c.getColumnIndexOrThrow("body")).toString();
ListItems.add(body);
c.moveToNext();
}
if(ListItems.isEmpty())
ListItems.add("no messages found !!");
}
c.close();
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ListItems);
setListAdapter(adapter);
}
private Drawable getDrawable(Context context, Uri uri) {
Drawable drawable = null;
InputStream is = null;
try {
is = context.getContentResolver().openInputStream(uri);
drawable = Drawable.createFromStream(is, null);
} catch (Exception e) {
// ...
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e2) {
}
}
}
return drawable;
}
}