I Have code which is defined for image (drawable )
Means Image is are already defined but I want user to select Image from Gallery .
SO first I want to get all Images from gallery and then it is show in view and from their user can select Image .
So it means all Images must be saved in array like below .
Any Help for this.
public class StickerSelectActivity extends AppCompatActivity {
public static final String EXTRA_STICKER_ID = "extra_sticker_id";
private final int[] stickerIds = {
R.drawable.abra,
R.drawable.bellsprout,
R.drawable.bracelet,
R.drawable.bullbasaur,
R.drawable.camera,
R.drawable.candy,
R.drawable.caterpie,
R.drawable.charmander,
R.drawable.mankey,
R.drawable.map,
R.drawable.mega_ball,
R.drawable.meowth,
R.drawable.pawprints,
R.drawable.pidgey,
R.drawable.pikachu,
R.drawable.pikachu_1,
R.drawable.pikachu_2,
R.drawable.player,
R.drawable.pointer,
R.drawable.pokebag,
R.drawable.pokeball,
R.drawable.pokeballs,
R.drawable.pokecoin,
R.drawable.pokedex,
R.drawable.potion,
R.drawable.psyduck,
R.drawable.rattata,
R.drawable.revive,
R.drawable.squirtle,
R.drawable.star,
R.drawable.star_1,
R.drawable.superball,
R.drawable.tornado,
R.drawable.venonat,
R.drawable.weedle,
R.drawable.zubat
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_sticker_activity);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.stickers_recycler_view);
GridLayoutManager glm = new GridLayoutManager(this, 3);
recyclerView.setLayoutManager(glm);
List<Integer> stickers = new ArrayList<>(stickerIds.length);
for (Integer id : stickerIds) {
stickers.add(id);
}
recyclerView.setAdapter(new StickersAdapter(stickers, this));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onStickerSelected(int stickerId) {
Intent intent = new Intent();
intent.putExtra(EXTRA_STICKER_ID, stickerId);
setResult(RESULT_OK, intent);
finish();
}
class StickersAdapter extends RecyclerView.Adapter<StickersAdapter.StickerViewHolder> {
private final List<Integer> stickerIds;
private final Context context;
private final LayoutInflater layoutInflater;
StickersAdapter(#NonNull List<Integer> stickerIds, #NonNull Context context) {
this.stickerIds = stickerIds;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public StickerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new StickerViewHolder(layoutInflater.inflate(R.layout.sticker_item, parent, false));
}
#Override
public void onBindViewHolder(StickerViewHolder holder, int position) {
holder.image.setImageDrawable(ContextCompat.getDrawable(context, getItem(position)));
}
#Override
public int getItemCount() {
return stickerIds.size();
}
private int getItem(int position) {
return stickerIds.get(position);
}
class StickerViewHolder extends RecyclerView.ViewHolder {
ImageView image;
StickerViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.sticker_image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
if (pos >= 0) { // might be NO_POSITION
onStickerSelected(getItem(pos));
}
}
});
}
}
}
}
Its not required If you want to show all available images in gallery in your application. You can use
private Cursor cc = null;
cc = this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
null)
This will give you a connection with files available in gallery. More detailed answer is here
How to implement Image Gallery in Gridview in android?
If In case in your application you have an image view and you want your user to click on the image and then Android should ask if they want to select an image from gallery/camera you can follow this, You can call selectImage method on setOnClickListener on ImageView.
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Update Profile Photograph");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(getActivity());
if (items[item].equals("Take Photo")) {
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
if(result)
galleryIntent();
}
}
});
builder.show();
}
private void cameraIntent() {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, familyMemberId + ".png");
Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePicture, 0);
}
private void galleryIntent() {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == Activity.RESULT_OK){
File out = Environment.getExternalStorageDirectory();
out = new File(out, familyMemberId + ".png");
Uri photoURI = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".app.provider", out);
Toast.makeText(getContext(), photoURI.toString(), Toast.LENGTH_LONG).show();
imageUri = photoURI.toString();
Glide.with(this).load(imageUri).into(familyMemberProfilePick);
}
break;
case 1:
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageUri = selectedImage.toString();
Glide.with(this).load(imageUri).into(familyMemberProfilePick);
}
break;
}
}
Please don't forget add these in
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application ...
<provider
android:name=".utility.GenericFileProvider"
android:authorities="${applicationId}.app.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
....
</application>
Related
I want to pick multiple or single images from phone gallery. But my code returning null pointer also one major problem I have notice the createChooser runs twice.
After tries two pick image two time it sends me to the parent activity
OnCreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item_business);
ItemName = findViewById(R.id.item_name);
ItemDes = findViewById(R.id.item_des);
pickImage = findViewById(R.id.pickImage);
ChooseImageList = new ArrayList<>();
UrlsList = new ArrayList<>();
pickImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPermission();
PickImageFromGallery();
}
});
}
Checking Permission
private void CheckPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(addItemBusiness.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(addItemBusiness.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
} else {
PickImageFromGallery();
}
}
}
Move to gallery
private void PickImageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select images"), 100);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("result", "inside activity result");
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Log.i("result", "result is ok");
if (data.getClipData() != null) {
Log.i("result", "fine");
int count = data.getClipData().getItemCount();
for (int i = 0; i < count; i++) {
ImageUri = data.getClipData().getItemAt(i).getUri();
ChooseImageList.add(ImageUri);
SetAdapter();
}
} else if (data.getData() != null) {
Log.i("result", "clip data is null");
ImageUri = data.getData();
ChooseImageList.add(ImageUri);
SetAdapter();
}
}
}
Adapter
private void SetAdapter(){
ViewPagerAdapter adapter = new ViewPagerAdapter(this, ChooseImageList);
viewPager.setAdapter(adapter);
}
Adapter Class
private Context context;
ArrayList<Uri> ImageUrls;
LayoutInflater layoutInflater;
public ViewPagerAdapter(Context context, ArrayList<Uri> imageUrls) {
this.context = context;
ImageUrls = imageUrls;
layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return ImageUrls.size();
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
View view=layoutInflater.inflate(R.layout.show_imgaes_layout,container,false);
ImageView imageView=view.findViewById(R.id.UploadImage);
imageView.setImageURI(ImageUrls.get(position));
container.addView(view);
return view ;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view== object;
}
#Override
public void destroyItem(#NonNull View container, int position, #NonNull Object object) {
((RelativeLayout)object).removeView(container);
}
Hope that you can find the issue. Thank you
I want to return the data from second activity to first activity using intent when click the OnAddClicked button in second activity, but what I done was not working. The data that I return to first activity is null and I have no idea about this. Can anyone help me to solve this problem?
First Activity:
public class CartView extends AppCompatActivity {
ActivityCartViewBinding binding;
public CartView.MyClickHandler handler;
GridView view_listView;
String Default_curr;
String itemgroup;
String itemtype;
String uprice;
String quantity;
ACDatabase db;
List<AC_Class.Item> s_item = new ArrayList<>();
AC_Class.InvoiceDetails invoiceDetails;
AC_Class.Item item;
String substring = "";
EditText searchEditText;
Button All;
Button Type;
Button Group;
ArrayAdapter<String> adapter;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_cart_view);
// Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Catalog");
actionBar.setDisplayHomeAsUpEnabled(true);
searchEditText = (EditText) findViewById(R.id.searchField);
UIUtil.hideKeyboard(this);
UIUtil.showKeyboard(this, searchEditText);
db = new ACDatabase(this);
invoiceDetails = new AC_Class.InvoiceDetails();
item = new AC_Class.Item();
handler = new MyClickHandler(this);
binding.setHandler(handler);
All = (Button) findViewById(R.id.button1);
Type = (Button) findViewById(R.id.button2);
Group = (Button) findViewById(R.id.button3);
view_listView = (GridView) findViewById(R.id.GridView);
All.setVisibility(View.GONE);
Type.setVisibility(View.GONE);
Group.setVisibility(View.GONE);
getData("");
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
#Override
public void afterTextChanged(Editable s) {
getData(s.toString().trim());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.ctlg_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
/*if (id == android.R.id.home)
{
onBackPressed();
return true;
}*/
if (id == R.id.cart)
{
Intent new_intent = new Intent(CartView.this, CartList.class);
new_intent.putExtra("invoiceDetail", invoiceDetails);
startActivityForResult(new_intent,3);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
getData("");
}
public void getData(String substring) {
Cursor data = db.getItemLike(substring, 0);
if (data.getCount() > 0){
s_item.clear();
while (data.moveToNext()) {
try {
AC_Class.Item item = new AC_Class.Item(data.getString(0), data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5), data.getString(6), data.getString(7), data.getString(8), data.getFloat(9), data.getFloat(10), data.getFloat(11), data.getFloat(12), data.getFloat(13), data.getFloat(14), data.getString(15), data.getString(16), data.getFloat(17), data.getString(18),data.getFloat(19),data.getFloat(20));
s_item.add(item);
} catch (Exception e) { Log.i("custDebug", "error reading image: "+e.getMessage()); }
}
CartViewListAdapter arrayAdapter = new CartViewListAdapter(this, s_item);
view_listView.setAdapter(arrayAdapter);
Cursor dcurren = db.getReg("6");
if(dcurren.moveToFirst()){
Default_curr = dcurren.getString(0);
}
view_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemcode = ((AC_Class.Item)parent.getItemAtPosition(position)).getItemCode();
String uom = ((AC_Class.Item)parent.getItemAtPosition(position)).getUOM();
AC_Class.Item sa =((AC_Class.Item) parent.getItemAtPosition(position));
//Intent item_intent = new Intent();
Intent item_intent = new Intent(CartView.this, ItemDetail.class);
item_intent.putExtra("ItemKey",itemcode);
item_intent.putExtra("ItemUOMKey",uom);
item_intent.putExtra("Items",sa);
//setResult(4, item_intent);
startActivity(item_intent);
//finish();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == 1) {
itemtype = data.getStringExtra("TypeKey");
if (itemtype != null) {
getTypedata();
}
}
break;
case 2:
if (resultCode == 1) {
itemgroup = data.getStringExtra("GroupKey");
if(itemgroup != null){
getGroupdata();
}
}
break;
case 3:
if (resultCode == 1) {
AC_Class.Item i = data.getParcelableExtra("Item");
uprice = data.getStringExtra("Price");
quantity = data.getStringExtra("Quantity");
if (i != null) {
invoiceDetails.setItemCode(i.getItemCode());
invoiceDetails.setItemDescription(i.getDescription());
invoiceDetails.setUPrice(Double.valueOf(i.getPrice()));
invoiceDetails.setUOM(i.getUOM());
//invoiceDetails.setUPrice(Double.valueOf(uprice));
invoiceDetails.setQuantity(Double.valueOf(quantity));
}
}
break;
}
}
}
SecondActivity:
public class ItemDetail extends AppCompatActivity {
ActivityItemDetailBinding binding;
AC_Class.Item items;
AC_Class.ItemUOM itemuom;
AC_Class.Cart cart;
AC_Class.InvoiceDetails invoiceDetails;
ACDatabase db;
String Item;
String ItemUOM;
String Default_curr;
Intent pintent;
EditText etQty;
String default_loc;
List<AC_Class.Item> c_item = new ArrayList<>();
MyClickHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_item_detail);
itemuom = new AC_Class.ItemUOM();
items = new AC_Class.Item();
invoiceDetails = new AC_Class.InvoiceDetails();
cart = new AC_Class.Cart();
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
db = new ACDatabase(this);
pintent = getIntent();
//substring = pintent.getStringExtra("substring");
Item = pintent.getStringExtra("ItemKey");
ItemUOM = pintent.getStringExtra("ItemUOMKey");
handler = new MyClickHandler(this);
binding.setHandler(handler);
Cursor loc = db.getReg("7");
if(loc.moveToFirst()){
default_loc = loc.getString(0);
}
items = pintent.getParcelableExtra("Items");
binding.setItem(items);
binding.setInvoicedetail(invoiceDetails);
binding.quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
etQty = (EditText)findViewById(R.id.quantity);
String qty = etQty.getText().toString();
if(qty.length() > 0)
{
invoiceDetails.setQuantity(Double.valueOf(qty));
//Calculation();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
onBackPressed();
return true;
}
}
return super.onOptionsItemSelected(item);
}
public class MyClickHandler {
Context context;
public MyClickHandler(Context context) {
this.context = context;
}
public void OnAddClicked(View view) {
//Intent new_intent = new Intent(context, CartList.class);
Intent new_intent = new Intent(context,CartView.class);
new_intent.putExtra("Item", items);
new_intent.putExtra("Quantity",invoiceDetails.getQuantity());
new_intent.putExtra("Price",invoiceDetails.getUPrice());
setResult(1, new_intent);
finish();
}
}
}
OnAddClicked your are finishing the activity when it goes to next activity previous activity goes to end....so remove the finish();
First thing first, to get result from other activity, you need to Use startActivityForResult method instead of startActivity.
Intent item_intent = new Intent(CartView.this, ItemDetail.class);
item_intent.putExtra("ItemKey",itemcode);
item_intent.putExtra("ItemUOMKey",uom);
item_intent.putExtra("Items",sa);
//startActivity(item_intent);
startActivityForResult(item_intent,REQUST_CODE);
and for setting result
Intent new_intent = new Intent();
new_intent.putExtra("Item", items);
new_intent.putExtra("Quantity",invoiceDetails.getQuantity());
new_intent.putExtra("Price",invoiceDetails.getUPrice());
setResult(Activity.RESULT_OK, new_intent);
finish();
and to receive result use below code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(REQUST_CODE==requestCode && resultCode==Activity.RESULT_OK){
// do logical stuff.
}
}
I am really new to AndroidStudio and I'm trying to make a sharing app. My purpose is to have an app that automatically loads up all the images on my phone(or in my phone's gallery, not that important) and display them on screen. Afterwards, I want to click on one of the images over there, and then use a Share button I made to send that photo to another person (it can be an MMS or any other application, the main problem is that this share button transmit the picture I clicked on most recently).
I don't know a lot about the specifics of Android Studio, meaning I know how to code (sort of) but I am unfamiliar with the possibilities of implementing this. My code is below.
GalleryAdapter.java:
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
private Context context;
private List<String> images;
protected PhotoListener photoListener;
public GalleryAdapter(Context context, List<String> images, PhotoListener photoListener) {
this.context = context;
this.images = images;
this.photoListener = photoListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(
LayoutInflater.from(context).inflate(R.layout.gallery_item, parent, false)
);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String image=images.get(position);
Glide.with(context).load(image).into(holder.image);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
photoListener.onPhotoClick(image);
}
});
}
#Override
public int getItemCount() {
return images.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image=itemView.findViewById(R.id.image);
}
}
public interface PhotoListener{
void onPhotoClick(String path);
}
}
ImagesGallery.java:
public class ImagesGallery {
public static ArrayList<String> listofImages(Context context){
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
ArrayList<String> listofAllImages=new ArrayList<>();
String absolutePathOfImage;
uri= MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection={MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
String orderBy= MediaStore.Video.Media.DATE_TAKEN;
cursor=context.getContentResolver().query(uri, projection, null, null, orderBy+" DESC");
column_index_data=cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
while(cursor.moveToNext()){
absolutePathOfImage=cursor.getString(column_index_data);
listofAllImages.add(absolutePathOfImage);
}
return listofAllImages;
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
GalleryAdapter galleryAdapter;
List<String> images;
TextView gallery_number;
private static final int MY_READ_PERMISSION_CODE=101;
#Override
protected void onCreate(Bundle savedInstanceState) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 101);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery_number=findViewById(R.id.gallery_number);
recyclerView=findViewById(R.id.recyclerview_gallery_images);
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_READ_PERMISSION_CODE);
} else {
loadImages();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId()==R.id.share_menu){
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
Uri uriToImage=Uri.parse("android.resource://com.example.tutorialpaper5/"+R.drawable.test);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.app_name)));
} else{
return super.onOptionsItemSelected(item);
}
return true;
}
private void loadImages(){
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
images=ImagesGallery.listofImages(this);
galleryAdapter=new GalleryAdapter(this, images, new GalleryAdapter.PhotoListener() {
#Override
public void onPhotoClick(String path) {
Toast.makeText(MainActivity.this, ""+path, Toast.LENGTH_LONG).show();
}
});
recyclerView.setAdapter(galleryAdapter);
gallery_number.setText("Photos +("+images.size()+")");
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==MY_READ_PERMISSION_CODE){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "read external storage permission granted", Toast.LENGTH_LONG).show();
loadImages();
} else {
Toast.makeText(this, "Read external storage permission denied", Toast.LENGTH_LONG).show();
}
}
}
}
You will notice that in my onOptionsItemSelected class I just threw in a picture I had in the drawable directory to see if the share button actually works. It does, now I just need some way for it memorize my last clicked photo and throw it in that Intent. But again, I am not sure if that is possible.
There are multiple options, here are two simple solutions just to link your code parts.
Suggestion with minimal changes in your logic:
You can just save the onPhotoClick(String path) to a field that will defined in the activity class scope and then use this field in the onOptionsItemSelected adding some code parts:
public class MainActivity extends AppCompatActivity {
String clickedImagePath = null
// ...
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId()==R.id.share_menu){
if (clickedImagePath != null) {
// The code you had for sharing with changing line for uriToImage
Uri uriToImage=Uri.parse(clickedImagePath);
} else {
// maybe show some error than nothing selected
}
}
}
// ...
public void onPhotoClick(String path) {
Toast.makeText(MainActivity.this, ""+path, Toast.LENGTH_LONG).show();
clickedImagePath = path
}
// ...
Maybe a better UX
Remove the onOptionsItemSelected completely and move the intent code to the onPhotoClick listener.
#Override
public void onPhotoClick(String path) {
Toast.makeText(MainActivity.this, ""+path, Toast.LENGTH_LONG).show();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
Uri uriToImage=Uri.parse(path); // <-- Don't forget to fix the path
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
MainActivity.this.startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.app_name)));
}
Situation :
I am working on Client-Server Communication.
When the users save the data (name of product, image, note), it should be transferred to the server side of the database.
But, I don't know how to code http Post request on the client side(Android).
MyWishlistsActivity.java
public class MyWishlistsActivity extends ListActivity {
SQLiteConnector sqlCon;
private CustomWishlistsAdapter custAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] from = new String[] { Wishlists.NAME, Wishlists.NOTE };
int[] to = new int[] { R.id.name };
custAdapter = new CustomWishlistsAdapter(this,R.layout.wishlist_list_item, null, from, to);
this.setListAdapter(custAdapter);
}
#Override
protected void onResume() {
super.onResume();
new GetContacts().execute((Object[]) null);
}
#SuppressWarnings("deprecation")
#Override
protected void onStop() {
Cursor cursor = custAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
custAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor> {
SQLiteConnector dbConnector = new SQLiteConnector(MyWishlistsActivity.this);
#Override
protected Cursor doInBackground(Object... params) {
return dbConnector.getAllWishlists();
}
#Override
protected void onPostExecute(Cursor result) {
custAdapter.changeCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent addWishlists = new Intent(MyWishlistsActivity.this,AddEditWishlists.class);
startActivity(addWishlists);
//Client-Server
Intent addWishlists2 = new Intent(MyWishlistsActivity.this,Server_AddWishlists.class);
startActivity(addWishlists2);
//Client-Server End
return super.onOptionsItemSelected(item);
}
}
AddWishlists.java
public class AddEditWishlists extends Activity {
private EditText inputname;
private EditText inputnote;
private Button upload;
private Bitmap yourSelectedImage;
private ImageView inputphoto;
private Button save;
private int id;
private byte[] blob=null;
byte[] image=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_wishlist);
setUpViews();
}
private void setUpViews() {
inputname = (EditText) findViewById(R.id.inputname);
inputnote = (EditText) findViewById(R.id.inputnote);
inputphoto = (ImageView) findViewById(R.id.inputphoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id=extras.getInt("id");
inputname.setText(extras.getString("name"));
inputnote.setText(extras.getString("note"));
image = extras.getByteArray("blob");
if (image != null) {
if (image.length > 3) {
inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
}
}
}
upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (inputname.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
saveContactTask.execute((Object[]) null);
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(
AddEditWishlists.this);
alert.setTitle("Error In Save Wish List");
alert.setMessage("You need to Enter Name of the Product");
alert.setPositiveButton("OK", null);
alert.show();
}
}
});
}
private void saveContact() {
if(yourSelectedImage!=null){
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
blob = outStr.toByteArray();
}
else{blob=image;}
SQLiteConnector sqlCon = new SQLiteConnector(this);
if (getIntent().getExtras() == null) {
sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
}
else {
sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(),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.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
inputphoto.setImageBitmap(yourSelectedImage);
}
}
}
}
ViewWishlist.java
public class ViewWishlist extends Activity {
private TextView name;
private TextView note;
private ImageView photo;
private Button backBtn;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_wishlist);
setUpViews();
}
private void setUpViews() {
name = (TextView) findViewById(R.id.inputname);
note = (TextView) findViewById(R.id.inputnote);
photo = (ImageView) findViewById(R.id.inputphoto);
Bundle extras = getIntent().getExtras();
if (extras != null) {
name.setText(extras.getString("name"));
note.setText(extras.getString("note"));
image = extras.getByteArray("blob");
if (image != null) {
if (image.length > 3) {
photo.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
}
}
}
backBtn=(Button)findViewById(R.id.back);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
CustomWishlistsAdapter.java
public class CustomWishlistsAdapter extends SimpleCursorAdapter {
private int layout;
private ImageButton editBtn;
private ImageButton delBtn;
LayoutInflater inflator;
public CustomWishlistsAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
super(context, layout, c, from, to,0);
this.layout = layout;
inflator= LayoutInflater.from(context);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = inflator.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, final Context context, Cursor c) {
final int id = c.getInt(c.getColumnIndex(Wishlists.ID));
final String name = c.getString(c.getColumnIndex(Wishlists.NAME));
final String note = c.getString(c.getColumnIndex(Wishlists.NOTE));
final byte[] image = c.getBlob(c.getColumnIndex(Wishlists.IMAGE));
ImageView iv = (ImageView) v.findViewById(R.id.inputphoto);
if (image != null) {
if (image.length > 3) {
iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
}
}
TextView tname = (TextView) v.findViewById(R.id.name);
tname.setText(name);
final SQLiteConnector sqlCon = new SQLiteConnector(context);
editBtn=(ImageButton) v.findViewById(R.id.edit_btn);
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,AddEditWishlists.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("note", note);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
delBtn=(ImageButton) v.findViewById(R.id.del_btn);
delBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sqlCon.deleteWishlist(id);
Intent intent=new Intent(context,MyWishlistsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,ViewWishlist.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("note", note);
intent.putExtra("blob", image);
context.startActivity(intent);
}
});
}
}
This is my code.
Please help me how to add http post request on this code..
And also the php on the Server side .
For the Android HttpPost (to send JSON serialized data to a server)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("url_of_the_server");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("note", note);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
//With response you can check the server return status code(to check if the request has been made correctly like so
StatusLine sLine = response.getStatusLine();
int statusCode = sLine.getStatusCode();
For more information on how to call a php web service there is a pretty nice tutorial that can be found here
I'm working on an android app that produces effects in images. I want the users of my app to have two options.
1) They can choose pictures from Gallery
2) They can capture a new photo from camera
Here is how I'm accomplishing the aforementioned two tasks:
Button takePhotoFromCameraButton;
Button chooseFromGalleryButton;
String imagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + System.currentTimeMillis() + "_image.jpg";
File imageFile = new File(imagePath);
imageUri = Uri.fromFile(imageFile);
In both buttons, I'm passing the same onClickListner.
#Override
public void onClick(View clickedView) {
int clickedViewId = clickedView.getId();
switch(clickedViewId) {
case R.id.takeFromCamera:
Intent imageCaptureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imageCaptureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(imageCaptureIntent,0);
break;
case R.id.chooseFromGallery:
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, 1);
break;
default:
// As we have only two buttons, and nothing else can be clicked except the buttons. So no need to put
// code in the "DEFAULT CASE"
}
}
And I'm capturing the result from both, the following way:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch(requestCode) {
case 0:
Intent cameraIntent = new Intent(MainOptionsActivity.this,ApplyEffectsActivity.class);
cameraIntent.putExtra("imageFileUri", imageUri);
startActivity(cameraIntent);
break;
case 1:
Uri imageUriForGallery = intent.getData();
Intent galleryIntent = new Intent(MainOptionsActivity.this,ApplyEffectsActivity.class);
galleryIntent.putExtra("imageFileUri", imageUriForGallery);
startActivity(galleryIntent);
break;
}
}
}
The button for gallery images works fine. But when I invoke camera by pressing the second button and capture the image, nothing happens. It stays there till I cancel the camera and come back to my app. I don't receive any image back!
Where I'm wrong? Don't mind this silly question, I'm just a beginner in android! :(
When I implemented mine, I made it work this way through a fragment:
public class ConcertFragment extends Fragment implements SurfaceHolder.Callback {
ImageView toto;
ToggleButton btnFlashlight;
RayMenu menu;
View rootView;
private Camera cam;
boolean hasCamera;
Parameters params;
private int REQUEST_IMAGE_CAPTURE;
Bitmap photo;
Uri imageUri;
public ConcertFragment() {
}
public void startCameraIntent() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
#Override
public void onStart() {
super.onStart();
SurfaceView preview = (SurfaceView)getView().findViewById(R.id.background);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.concert, menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCamera();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_concert, container, false);
toto = (ImageView) rootView.findViewById(R.id.toto);
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode != 0)
{
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
toto.setImageBitmap(photo);
View content = rootView.findViewById(R.id.toto);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try {
cachePath.createNewFile();
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share,"Share via"));
}
else {
cam.release();
}
}
}
// Get the camera
private void getCamera() {
if (cam != null) {
try {
cam = Camera.open();
params = cam.getParameters();
cam.startPreview();
hasCamera = true;
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
cam.release();
}
}
}
Hope this helps :) Just ask if you need more information.
How to do it with an activity, instead of fragment
public class MyCameraActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}