How to use onActivityResult in base adapter class? - android

I have a listview which contains two buttons, when the button is clicked it should open a gallery. I tried to implement it and followed some post on stackoverflow but still I'm not able to get exact result. How to open the gallery using buttons in listViewlistview?
I have tried the following and used the adapter class as inner class
MyAdapter adapter=new MyAdapter(getApplicationContext(),videoFileList);
im my adapter class
private class MyAdapter extends BaseAdapter
{
ImageView picture;
Button imgbtn,videobtn;
ImageButton play;
Context context;
private LayoutInflater inflater;
private ArrayList<String> videolisty;
public MyAdapter(Context context,ArrayList<String> videolistx)
{
this.context=context;
inflater = LayoutInflater.from(context);
videolisty = videolistx;
Field[] arrayOfField = R.raw.class.getFields();
for (int i = 0; ; i++)
{
if (i >= arrayOfField.length)
{
System.out.println("-----------videolist------" +videoFileList);
return;
}
System.out.println("audio files-----" + arrayOfField[i].getName());
videoFilename.add(arrayOfField[i].getName());
Uri localUri = Uri.parse("android.resource://" + Listmodels.this.getPackageName() + "/" + "R.raw." + arrayOfField[i].getName());
System.out.println("--------uri path------" + localUri);
}
}
#Override
public int getCount() {
return videolisty.size();
}
#Override
public Object getItem(int i)
{
return videolisty.get(i);
}
#Override
public long getItemId(int i)
{
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup)
{
View v = view;
final int xx = i;
if(v == null)
{
v = inflater.inflate(R.layout.clistview, viewGroup, false);
v.setTag(R.id.categoryimageView1, v.findViewById(R.id.categoryimageView1));
v.setTag(R.id.uploadimg, v.findViewById(R.id.uploadimg));
v.setTag(R.id.uploadvideo, v.findViewById(R.id.uploadvideo));
v.setTag(R.id.play, v.findViewById(R.id.play));
}
picture = (ImageView)v.getTag(R.id.categoryimageView1);
imgbtn = (Button)v.getTag(R.id.uploadimg);
videobtn = (Button)v.getTag(R.id.uploadvideo);
play=(ImageButton)v.getTag(R.id.play);
imgbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Activity aa = (Activity)context;
aa.startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
System.out.println("YEST"+xx);
Intent localIntent = new Intent(Listmodels.this, Videoplay.class);
localIntent.putExtra("videopath", videoFileList.get(xx));
startActivity(localIntent);
}
});
/*picture.setImageResource(item.drawableId);
name.setText(item.name);*/
return v;
}
protected void onActivityResult(int requestCode, int resultCode) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
System.out.println("------data path-------"+picturePath);
//filechoose.setText(picturePath);
}
}

Related

Can't load images from phone gallery via intent and set it on gridview

i am new to android and want to load images from phone gallery via intent and want to display the list item on gridView.
But when i load the gallery after selection the image is not displaying.
Activity
private static final int CODE = 0;
public GridView gridView;
public Uri selectedImageUri;
ImageAdapter imageAdapter;
...
gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
imageAdapter = new ImageAdapter(this);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
Toast.makeText(MainActivity.this, "" + position + "",
Toast.LENGTH_LONG).show();
}
});
Button loadImageButton = (Button) findViewById(R.id.load_image_button);
loadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
Picture"), CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == CODE && resultCode == RESULT_OK && intent != null) {
selectedImageUri = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
objImageAdapter.addToList(picturePath);
cursor.close();
imageView = (ImageView)findViewById(R.id.image_view);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Adapter class
public class ImageAdapter extends BaseAdapter {
public ImageView imageView;
private Context vContext;
ArrayList<String> arrayList = new ArrayList<String>();
public ImageAdapter(Context context) {
this.vContext = context;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
public void addToList(String stringPath) {
this.arrayList.add(stringPath);
this.notifyDataSetChanged();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imageView = new ImageView(vContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(2, 2, 2, 2);
} else {
imageView = (ImageView) convertView;
}
String path = arrayList.get(position);
Bitmap bitmap = BitmapFactory.decodeFile(path);
imageView.setImageBitmap(bitmap);
return imageView;

How to bring file image from onActivityResult to Adapter Android?

I have a recycle View android and there's an image in each item. In that image i want to make a upload function. And I use MVP in this app. SO, There's a fragment, presenter and adapter.
My Fragment
public void loadList() {
rv.setAdapter(new PendingOrderAdapter(transactionHistories, getContext(), presenter));
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
file = new File(picturePath);
}
}
}
My Adapter
public class PendingOrderAdapter extends RecyclerView.Adapter<PendingOrderAdapter.PendingOrderHolder> {
ArrayList<TransactionHistory> list;
Context context;
File file;
PendingOrderPresenter presenter;
public PendingOrderAdapter(ArrayList<TransactionHistory> list, Context context, PendingOrderPresenter presenter) {
this.list = list;
this.context = context;
this.presenter = presenter;
}
#Override
public PendingOrderAdapter.PendingOrderHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_pending_order, parent, false);
return new PendingOrderAdapter.PendingOrderHolder(itemView);
}
#Override
public void onBindViewHolder(PendingOrderAdapter.PendingOrderHolder holder, int position) {
final TransactionHistory item = list.get(position);
holder.txvPackageName.setText(item.getPackageName());
holder.txvTransactionType.setText(item.getTransactionType());
holder.txvOrderNumber.setText(item.getOrderNumber());
holder.txvInvestmentNumber.setText(item.getInvestmentNumber());
holder.txvTotal.setText(AmountFormatter.format(item.getAmount()));
holder.txvTransactionStatus.setText(item.getTransactionStatus());
SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.INVISEE_RETURN_FORMAT2, Locale.getDefault());
Date dateParse = null;
try {
dateParse = sdf.parse(item.getTransactionDate());
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm" , Locale.getDefault());
String convertedDate= formatter.format(dateParse);
holder.txvDate.setText(convertedDate);
holder.imgOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Activity origin = (Activity) context;
origin.startActivityForResult(i, 0);
}
});
presenter.uploadTransaction(item.getOrderNumber(), file);
}
#Override
public int getItemCount() {
return list != null ? list.size() : 0;
}
public static class PendingOrderHolder extends RecyclerView.ViewHolder {
#Bind(R.id.txvDate)
TextView txvDate;
#Bind(R.id.txvTransactionType)
TextView txvTransactionType;
#Bind(R.id.txvPackageName)
TextView txvPackageName;
#Bind(R.id.txvOrderNumber)
TextView txvOrderNumber;
#Bind(R.id.txvInvestmentNumber)
TextView txvInvestmentNumber;
#Bind(R.id.txvTotal)
TextView txvTotal;
#Bind(R.id.txvTransactionStatus)
TextView txvTransactionStatus;
#Bind(R.id.imgOrder)
ImageView imgOrder;
public PendingOrderHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
The question is how to bring image file to my adapter?

Android Gallery Display two item

Hello I made android gallery . I added capture image camera or gallery but I show only one image in display How can show two gallery item in gallery For example that is
here is my gallery code xml
<Gallery
android:id="#+id/main_list_view"
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_alignLeft="#+id/btnAdd"
android:layout_below="#+id/btnAdd"
android:layout_marginTop="28dp"
android:cacheColorHint="#color/deepPurple1"/>
And My MainActivity
#SuppressLint("NewApi")
public class MainActivity extends Activity {
private ArrayList<MyImage> images;
private ImageAdapter imageAdapter;
private Gallery listView;
private Uri mCapturedImageURI;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
private Handler handler;
Dialog dialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Alert Dialog View");
// Construct the data source
images = new ArrayList<MyImage>();
// Create the adapter to convert the array to views
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setAdapter(imageAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Button btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnChoosePath)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeTakePhoto();
}
});
// show dialog on screen
dialog.show();
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
imageAdapter.remove(images.remove(position));
return false;
}
});
}
public void btnAddOnClick(View view) {
dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("Alert Dialog View");
Button btnExit = (Button) dialog.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnChoosePath)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto)
.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
activeTakePhoto();
}
});
// show dialog on screen
dialog.show();
}
/**
* take a photo
*/
private void activeTakePhoto() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
/**
* to gallery
*/
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE &&
resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
MyImage image = new MyImage();
image.setTitle("Test");
image.setDescription(" add list view");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
images.add(image);
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setSpacing(-20);
listView.setAdapter(imageAdapter);
// listView.setSelection(imageAdapter.getCount()-1);
imageAdapter.notifyDataSetChanged();
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor =
managedQuery(mCapturedImageURI, projection, null,
null, null);
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
MyImage image = new MyImage();
image.setTitle("Test");
image.setDescription("list view");
image.setDatetime(System.currentTimeMillis());
image.setPath(picturePath);
images.add(image);
imageAdapter = new ImageAdapter(this, images);
// Attach the adapter to a ListView
listView = (Gallery) findViewById(R.id.main_list_view);
listView.setSpacing(-20);
listView.setAdapter(imageAdapter);
// listView.setSelection(imageAdapter.getCount()-1);
imageAdapter.notifyDataSetChanged();
}
}
}
And My Adapter
public class ImageAdapter extends ArrayAdapter<MyImage>{
/**
* applying ViewHolder pattern to speed up ListView, smoother and faster
* item loading by caching view in A ViewHolder object
*/
private static class ViewHolder {
ImageView imgIcon;
TextView description;
}
public ImageAdapter(Context context, ArrayList<MyImage> images) {
super(context, 0, images);
}
#Override public View getView(int position, View convertView,
ViewGroup parent) {
// view lookup cache stored in tag
ViewHolder viewHolder;
// Check if an existing view is being reused, otherwise inflate the
// item view
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_image, parent, false);
/*
viewHolder.description =
(TextView) convertView.findViewById(R.id.item_img_infor);
*/
viewHolder.imgIcon =
(ImageView) convertView.findViewById(R.id.item_img_icon);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Get the data item for this position
MyImage image = getItem(position);
// set description text
// viewHolder.description.setText(image.toString());
// set image icon
final int THUMBSIZE = 100;
// viewHolder.imgIcon.setImageURI(Uri.fromFile(new File(image
// .getPath())));
viewHolder.imgIcon.setImageBitmap(ThumbnailUtils
.extractThumbnail(BitmapFactory.decodeFile(image.getPath()),
THUMBSIZE, THUMBSIZE));
viewHolder.imgIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
viewHolder.imgIcon.setBackgroundResource(R.drawable.ios_retina_toggle_frame);
// Return the completed view to render on screen
return convertView;
}
}
And My image Class
public class MyImage {
private String title, description, path;
private Calendar datetime;
private long datetimeLong;
protected SimpleDateFormat df = new SimpleDateFormat("MMMM d, yy h:mm");
public String getTitle() { return title; }
public Calendar getDatetime() { return datetime; }
public void setDatetime(long datetimeLong) {
this.datetimeLong = datetimeLong;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(datetimeLong);
this.datetime = cal;
}
public void setDatetime(Calendar datetime) { this.datetime = datetime; }
public String getDescription() { return description; }
public void setTitle(String title) { this.title = title; }
public long getDatetimeLong() { return datetimeLong; }
public void setDescription(String description) {
this.description = description;
}
public void setPath(String path) { this.path = path; }
public String getPath() { return path; }
#Override public String toString() {
return "Title:" + title + " " + df.format(datetime.getTime()) +
"\nDescription:" + description + "\nPath:" + path;
}
}

Load image From basic gallery To imageview in Custom Listview/

First, I'm sorry for my bad English. please excuse me. :)..
I tried to make a custom listView which has ImageView, TextViews, and Button.
So, I want to change image after I click ImageView in listview and select image from gallery. But.. It's really hard to me.
In my code(customAdapter)Adapter class is not Activity, So it cannot call startActivityForResult directly. So I make new Activity(It is GalleryImage.java). and call startActivity using that class. But it is not working. What should I do...
(Error occur in ImageView.setOnClickListner, getView of PhoneBookAdapter)
CustomAdapter Source Code
//..skip import
public class PhoneBookAdapter extends BaseAdapter implements Filterable {
ArrayList<Contact> m_people = new ArrayList<Contact>();
ArrayList<Contact> m_filteredPeople = new ArrayList<Contact>();
private ItemFilter mFilter = new ItemFilter();
private class CustomHolder {
ImageView m_photo;
TextView m_name, m_phone;
Button m_call, m_reserve;
}
public PhoneBookAdapter(ArrayList<Contact> people) {
m_people = people;
m_filteredPeople = people;
}
#Override
public int getCount() {
return m_filteredPeople.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// final int pos = position;
final Context context = parent.getContext();
final TextView phone;
final ImageView photo;
TextView name;
Button call, reserve;
final int pos = position;
CustomHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.phonebook_list_item, parent,
false);
photo = (ImageView) convertView.findViewById(R.id.iv_photo);
name = (TextView) convertView.findViewById(R.id.tv_name);
phone = (TextView) convertView.findViewById(R.id.tv_phonenumber);
call = (Button) convertView.findViewById(R.id.btn_call);
reserve = (Button) convertView.findViewById(R.id.btn_reserve);
holder = new CustomHolder();
holder.m_photo = photo;
holder.m_name = name;
holder.m_phone = phone;
holder.m_call = call;
holder.m_reserve = reserve;
convertView.setTag(holder);
} else {
holder = (CustomHolder) convertView.getTag();
photo = holder.m_photo;
name = holder.m_name;
phone = holder.m_phone;
call = holder.m_call;
reserve = holder.m_reserve;
}
//photo.setImageResource(m_filteredPeople.get(position).getImage());
name.setText(m_filteredPeople.get(position).getName());
phone.setText(m_filteredPeople.get(position).getNumber());
photo.setOnClickListener(new OnClickListener() {
Activity activity;
int SELECT_IMAGE=90;
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryImage gallery = new GalleryImage(SELECT_IMAGE, photo);
gallery.startActivityForResult(intent, SELECT_IMAGE);
}
});
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO make real phone call
Toast.makeText(context, "call " + phone.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse("tel:" + m_filteredPeople.get(pos).getNumber()));
context.startActivity(intent);
}
});
reserve.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "reserve " + phone.getText(),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString();
FilterResults results = new FilterResults();
final ArrayList<Contact> m_IFpeople = m_people;
int count = m_IFpeople.size();
final ArrayList<Contact> n_people = new ArrayList<Contact>();
String filterableString;
if (filterString != null
&& filterString.trim().equalsIgnoreCase("") != true) {
// Whitespace와 null 제거
// for (int i = 0; i < count; i++) {
// filterableString = m_IFpeople.get(i).getName();
// if (filterableString.indexOf(filterString) >= 0) {
// n_people.add(m_IFpeople.get(i));
// }
// }
for (int i = 0; i < count; i++) {
filterableString = HangulUtils.getHangulInitialSound(
m_IFpeople.get(i).getName(), filterString);
if (filterableString.indexOf(filterString) >= 0) {
n_people.add(m_IFpeople.get(i));
}
}
results.values = n_people;
results.count = n_people.size();
} else {
results.values = m_IFpeople;
results.count = m_IFpeople.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
m_filteredPeople = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
}
GalleryImage.java(new Activity)
//..skip import
public class GalleryImage extends Activity {
final int REQ_CODE_SELECT_IMAGE;
ImageView photo;
public GalleryImage(int codeImage, ImageView m_photo) {
REQ_CODE_SELECT_IMAGE = codeImage;
photo = m_photo;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Intent intent = new Intent(Intent.ACTION_PICK);
// intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
// intent.setData(
// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// startActivityForResult(intent, REQ_CODE_SELECT_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SELECT_IMAGE && resultCode == Activity.RESULT_OK
&& data != null) {
final Uri selectImageUri = data.getData();
final String[] filePathColumn = { MediaStore.Images.Media.DATA };
final Cursor imageCursor = this.getContentResolver()
.query(selectImageUri, filePathColumn, null, null, null);
final int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
final String imagePath = imageCursor.getString(columnIndex);
imageCursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
}
}
}
Thanks for your help. :D.
Solution here is not creating a new instance of Activity but being able to access already existing instance created by Android Framework. Instance of an Activity should never be created by an application programmer.
Best approach would be to add a parameter of type Activity to the constructor of PhoneBookAdapter. Such as:
private Activity activity;
public PhoneBookAdapter(Activity activity, ArrayList<Contact> people) {
this.activity = activity;
m_people = people;
m_filteredPeople = people;
}
You can than then call activity.startActivityForResult on this instance of Activity.
You then pass in the instance of Activity when you create the adapter. In Activity you would simply pass this and in Fragment you can obtain the instance by calling getActivity() method of Fragment class.
As to processing the result of the started Activity you would need to implement this in the Activity or Fragment in which you display the list.

android onActivityResult not calling

I'm beginner in Android. I have two screens. I am switching between the screens, but onActivityResult() is not called in my application. I'm getting my main screen back. I want result of my second screen.
This is my code:
mainActivity.java
loadPicture.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Intent i = new Intent(context, ImageThumbnailsActivity.class);
startActivityForResult(i, 0);
return true;
}
});
ImageThumbnailActivity.java
public class ImageThumbnailsActivity extends Activity {
private Cursor imagecursor, actualimagecursor;
private int image_column_index, actual_image_column_index;
GridView imagegrid;
private int count;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.image_gallery);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Thumbnails._ID };
imagecursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,
null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
image_column_index = imagecursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
count = imagecursor.getCount();
imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
imagegrid.setAdapter(new ImageAdapterClass(getApplicationContext()));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
//System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,
null, null, null);
actual_image_column_index = actualimagecursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
//System.gc();
Intent intent = new Intent();
intent.putExtra("filename", i);
//startActivity(intent);
setResult(RESULT_OK,intent);
finish();
}
});
}
public class ImageAdapterClass extends BaseAdapter {
private Context mContext;
public ImageAdapterClass(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
//System.gc();
ImageView i = new ImageView(mContext.getApplicationContext());
if (convertView == null) {
imagecursor.moveToPosition(position);
int id = imagecursor.getInt(image_column_index);
i.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""+ id));
i.setScaleType(ImageView.ScaleType.CENTER_CROP);
i.setLayoutParams(new GridView.LayoutParams(92, 92));
} else {
i = (ImageView) convertView;
}
return i;
}
}
}
Add this to you main activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String filename = data.getStringExtra("filename");
}
}
}
It is not obvious that you have overloaded the activity's onActivityResult method.

Categories

Resources