I have been writing a gallery app for Android as I am just beginning with it. I have managed to get it working previously with photos in the drawable folder but now I have implemented getting the images from the storage, I can't seem to figure out how to get the ID to pass to the ShowPic Method.
Here is the code I have for my Main Activity:
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
public class MainActivity extends AppCompatActivity
{
private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
private Cursor cursor;
private int columnIndex;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
String[] projection = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Images.Thumbnails._ID + "");
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
GridView imgGridView = findViewById(R.id.imgGridView);
PicAdapter picAdapter = new PicAdapter(MainActivity.this, cursor, columnIndex);
imgGridView.setAdapter(picAdapter);
imgGridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
}
});
}
public void ShowPic(final int imgID)
{
Intent intent = new Intent(MainActivity.this, OpenPicFull.class);
intent.putExtra("picId", imgID);
startActivity(intent);
}
}
Here is my Adapter:
public class PicAdapter extends BaseAdapter
{
Context mCont;
Cursor mCur;
ImageView mImageView;
int mColumnIndex;
public PicAdapter(Context cont, Cursor cur, int index)
{
mCont = cont;
mCur = cur;
mColumnIndex = index;
}
#Override
public int getCount()
{
return mCur.getCount();
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
mImageView = new ImageView(mCont);
mCur.moveToPosition(position);
int imageID = mCur.getInt(mColumnIndex);
mImageView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID));
mImageView.setLayoutParams(new GridView.LayoutParams(330, 330));
mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
mImageView.setPadding(4, 4, 4, 4);
return mImageView;
}
}
Here is my OpenFullPic class:
public class OpenPicFull extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_pic_full);
ImageView fullImgView = findViewById(R.id.pic_full);
int picID = getIntent().getExtras().getInt("picId");
fullImgView.setImageResource(picID);
}
}
Any help would be greatly appreciated
Thanks
So do the same thing as you did in adapter:
imgGridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
cursor.moveToPosition(position);
ShowPic(cursor.getInt(columnIndex));
}
});
}
And change your Openfullpic with this:
fullImgView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + picID));
Also a suggestion try to optimize your image because your code will show memory error if there are lots of image
Related
I have developed a Contacts application. It does everything that a normal contacts application should does. There is always a chance of improvement. I had noticed in Android Emulator that loading for contact images starts when user has settled, he has scrolled the contact list to the area where there are chances are good that he would get contact he is searching for. So, I tried to implement the same thing on my app copy. I have implemented it. Its running very very slow. As I presume, I believe that application is running the thread multiple time even if it has retrieved the image which leads to big lagging. I am aware of the ASync task but just out of curiosity and to check whether it can be done, I don't wish to implement it here. Here is the source code for MainActivity.
package com.example.contact;
import java.io.InputStream;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
public class MainActivity extends ListActivity {
ListView listview;
private boolean mPaused;
private MyAdapter mAdapter;
private View view;
private boolean running = false;
final private ArrayList<String> con_ids = new ArrayList<String>();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = getListView();
context = this;
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME+" ASC");
if(c!=null)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
con_ids.add(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
mAdapter = new MyAdapter(this, android.R.layout.simple_list_item_1, con_ids);
listview.setAdapter(mAdapter);
listview.setOnScrollListener(makeScrollListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
running = false;
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
String log = "";
Log.d(log, "Scroll First Item" + i);
Log.d(log, ""+ listview.getChildCount());
final int want = i;
running = true;
runOnUiThread(new Thread(new Runnable() {
int totalChild = listview.getChildCount();
int first = listview.getFirstVisiblePosition() - listview.getHeaderViewsCount();
int toRetrieve = want-first;
int id;
long con_id;
Bitmap thumbnail;
final ListView list = listview;
#Override
public void run() {
// TODO Auto-generated method stub
while(running)
{
if(!(toRetrieve<0||toRetrieve>=totalChild))
{
id = want+toRetrieve;
con_id = Long.valueOf(con_ids.get(id));
Uri ContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, con_id);
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), ContactUri);
thumbnail = BitmapFactory.decodeStream(stream);
if(thumbnail == null)
{
toRetrieve++;
continue;
}
else
{
View view = list.getChildAt(toRetrieve);
if(view == null)
{
toRetrieve++;
continue;
}
else
{
ImageView iamge = (ImageView) view.findViewById(R.id.contact_iamge);
iamge.setImageBitmap(thumbnail);
}
toRetrieve++;
}
}
else
{
running = false;
}
}
}
}));
}
};
}
}
Code for MyAdapter,
package com.example.contact;
import java.util.ArrayList;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<String> {
private Context context;
private ListView listview;
private ArrayList<String> ids;
private LayoutInflater infl;
private String displayname;
private String maindetail;
private SimplifiedContact contact;
private Drawable drawable;
public MyAdapter(Context context, int ResourceId, ArrayList<String> list)
{
super(context, ResourceId, list);
this.context = context;
ids = list;
infl = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
drawable = context.getResources().getDrawable(R.drawable.person);
}
static class ViewHolder
{
public ImageView image;
public TextView display_name;
public TextView main_detail;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
contact = new SimplifiedContact(context, Long.valueOf(ids.get(position)));
if(row == null)
{
row = infl.inflate(R.layout.single_cell, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.display_name =(TextView) row.findViewById(R.id.disp_name);
viewHolder.main_detail = (TextView) row.findViewById(R.id.main_detail);
viewHolder.image = (ImageView)row.findViewById(R.id.contact_iamge);
row.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) row.getTag();
holder.display_name.setText(contact.getDisplayName());
holder.main_detail.setText(contact.getMainDetail());
holder.image.setBackgroundDrawable(drawable);
return row;
}
}
I wish to know, how this lag can be reduced. Thanks in advance.
Why don't you try to take that Thread instance that you are making in runOnUiThread and put It in a field, initializing It in the onCreate. I think that you are creating several thread instaces with no use.
public class MainActivity extends ListActivity {
ListView listview;
private boolean mPaused;
private MyAdapter mAdapter;
private View view;
private boolean running = false;
final private ArrayList<String> con_ids = new ArrayList<String>();
private Context context;
Thread uiThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = getListView();
context = this;
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME+" ASC");
if(c!=null)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
con_ids.add(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
uiThread = new Thread(new Runnable() {
int totalChild = listview.getChildCount();
int first = listview.getFirstVisiblePosition() - listview.getHeaderViewsCount();
int toRetrieve = want-first;
int id;
long con_id;
Bitmap thumbnail;
final ListView list = listview;
#Override
public void run() {
// TODO Auto-generated method stub
while(running)
{
if(!(toRetrieve<0||toRetrieve>=totalChild))
{
id = want+toRetrieve;
con_id = Long.valueOf(con_ids.get(id));
Uri ContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, con_id);
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), ContactUri);
thumbnail = BitmapFactory.decodeStream(stream);
if(thumbnail == null)
{
toRetrieve++;
continue;
}
else
{
View view = list.getChildAt(toRetrieve);
if(view == null)
{
toRetrieve++;
continue;
}
else
{
ImageView iamge = (ImageView) view.findViewById(R.id.contact_iamge);
iamge.setImageBitmap(thumbnail);
}
toRetrieve++;
}
}
else
{
running = false;
}
}
}
});
mAdapter = new MyAdapter(this, android.R.layout.simple_list_item_1, con_ids);
listview.setAdapter(mAdapter);
listview.setOnScrollListener(makeScrollListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
running = false;
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
String log = "";
Log.d(log, "Scroll First Item" + i);
Log.d(log, ""+ listview.getChildCount());
final int want = i;
running = true;
runOnUiThread(uiThread);
}
};
}
}
I came across a nice filterable listview tutorial and I was wondering how to determine what listview item is selected and display a toast. Here is the code:
package com.example.listview;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class TestFilterListView extends Activity {
FrameLayout historyContainer;
ViewStub viewStub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history_container);
historyContainer = (FrameLayout) findViewById(R.id.historyContainerLayout);
EditText filterEditText = (EditText) findViewById(R.id.filter_text);
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
historyContainer.removeAllViews();
final List<String> tempHistoryList = new ArrayList<String>();
tempHistoryList.addAll(historyList);
for(String data : historyList) {
if(data.indexOf((s.toString())) == -1) {
tempHistoryList.remove(data);
}
}
viewStub = new ViewStub(TestFilterListView.this, R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener()
{
public void onInflate(ViewStub stub, View inflated)
{
setUIElements(inflated, tempHistoryList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
setViewStub();
}
/********************************************************************************************************/
private void setViewStub()
{
historyList.add("first");
historyList.add("second");
historyList.add("third");
historyList.add("fourth");
historyList.add("fifth");
historyList.add("sixth");
historyList.add("seventh");
viewStub = new ViewStub(TestFilterListView.this, R.layout.history_schedule);
viewStub.setOnInflateListener(new ViewStub.OnInflateListener()
{
public void onInflate(ViewStub stub, View inflated)
{
setUIElements(inflated, historyList);
}
});
historyContainer.addView(viewStub);
viewStub.inflate();
}
/********************************************************************************************************/
final List<String> historyList = new ArrayList<String>();
String displayName = "";
ListView historyListView;
private void setUIElements(View v, List<String> historyLists)
{
if (v != null)
{
historyScheduleData.clear();
//historyList.clear();
historyScheduleData.addAll(historyLists);
historyListView = (ListView) findViewById(R.id.historylist);
historyListView.setAdapter(new BeatListAdapter(this));
registerForContextMenu(historyListView);
}
}
private static class BeatListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public BeatListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return historyScheduleData.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.history_list_view, null);
holder = new ViewHolder();
holder.historyData = (TextView) convertView
.findViewById(R.id.historytext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.historyData.setText(historyScheduleData.get(position));
return convertView;
}
static class ViewHolder {
TextView historyData;
}
}
private static final List<String> historyScheduleData = new ArrayList<String>();
}
I thought about using
protected void onListItemClick(ListView l, View v, int position, long id) {
if(position == 0) {
Intent intent = new Intent(getApplicationContext(), GODoc1Activity.class);
startActivity(intent);
But when I try to implement it, it does not work. Am I missing something here? How do I go about doing this?
you tried this?: (in the onCreate)
historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//your code
}
});
If you are trying to find the selected item in your ListView:
listView.getAdapter().getItem(listView.getCheckedItemPosition());
Take a look at the documentation here for more information http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemPosition%28%29
Hi I have images in grid view. when i click my grid view images, it's display in full screen. if i want view another image go back in grid view then select another image view in full screen. i feel it's hard one.. so i am trying to view images full screen view using to swipe....no idea how to create this method please guide me and give some nice codes also...
This is my working app screen shot:
source code: 1. ImageViewExample.java
public class ImageViewExample extends Activity {
/** Called when the activity is first created. */
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);
setContentView(R.layout.main);
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 ImageAdapter(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(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(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;
}
}
}
ViewImage.java
public class ViewImage extends Activity {
private String filename;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 2;
filename = extras.getString("filename");
ImageView iv = new ImageView(getApplicationContext());
Bitmap bm = BitmapFactory.decodeFile(filename, bfo);
iv.setImageBitmap(bm);
setContentView(iv);
}
}
After getting id of selected image, implement this..
// this Class For Grid view images
package com.thumbnailview;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class Activity_ThumbView extends Activity
{
GridView gridview;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(Activity_ThumbView.this, "" + position, 2).show();
id=parent.getPositionForView(v);
Intent i=new Intent(Activity_ThumbView.this,Activity_ImageView.class);
i.putExtra("position", position);
startActivity(i);
finish();
}
});
}
public class ImageAdapter extends BaseAdapter
{
Context context;
public ImageAdapter(Context c )
{
context = c ;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return mThumbIds[position];
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null)
{
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(75, 75));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else
{
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
}
public static Integer[] mThumbIds = {
R.drawable.a,R.drawable.icon,
R.drawable.b, R.drawable.s,
R.drawable.c, R.drawable.r,
R.drawable.d, R.drawable.q,
R.drawable.e, R.drawable.p,
R.drawable.f, R.drawable.o,
R.drawable.g, R.drawable.n,
R.drawable.h, R.drawable.m,
R.drawable.i, R.drawable.l,
R.drawable.j, R.drawable.k,
R.drawable.t,R.drawable.y,
R.drawable.u,R.drawable.x,
R.drawable.v,R.drawable.s,
R.drawable.cd,R.drawable.z,
R.drawable.bc,R.drawable.ab
};
}
// This Flip image Class
package com.thumbnailview;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class Activity_ImageView extends Activity
{
ImageView thumb_imgview;
ViewFlipper viewFlipper;
Button b_wall;
Button b_home;
// Animation a,b;
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
int j;
WallpaperManager myWall;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
j=getIntent().getExtras().getInt("position");
myWall = WallpaperManager.getInstance(getApplicationContext());
b_wall=(Button) findViewById(R.id.button3);
b_home=(Button) findViewById(R.id.button1);
thumb_imgview=(ImageView) findViewById(R.id.thumb_txt_image);
thumb_imgview.setImageResource(Activity_ThumbView.mThumbIds[j]);
gestureDetector = new GestureDetector(new MyGestureDetector());
b_wall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
myWall.setResource(Activity_ThumbView.mThumbIds[j]);
} catch (IOException e) {
e.printStackTrace();
}
}
});
b_home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(Activity_ImageView.this,Activity_ThumbView.class);
startActivity(i);
finish();
}
});
}
public class MyGestureDetector extends SimpleOnGestureListener implements OnGestureListener
{
public boolean onFling(MotionEvent m1, MotionEvent m2, float velocityX, float velocityY)
{
try
{
if (Math.abs(m1.getY() - m2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
if(m1.getX() - m2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
if(Activity_ThumbView.mThumbIds.length>j)
{
j++;
thumb_imgview.setImageResource(Activity_ThumbView.mThumbIds[j]);
}
}
else if (m2.getX() - m1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
if(j>0)
{
j--;
thumb_imgview.setImageResource(Activity_ThumbView.mThumbIds[j]);
}
}
}
catch (Exception e)
{
}
return false;
}
}
public boolean onTouchEvent(MotionEvent event)
{
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}
}
Implement OnGestureListener in ViewImage activity and capture swipe from user.
For displaying previous or next image, use cursor.
Store all image filenames in array when you are populating into Gridview and then pass that array to another view from that array you can get all images instead of go back to gridview for selecting images..
The easiest way to do this is indeed like RajaReddy P said: create an array with the filenames/urls pass it to the ViewImage activity...
For the ViewImage activity I really would use the ViewPager! Really easy to implement and the swiping is handled for you!
More about viewpager:
http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html
im easily able to use for textviews but textview with imageview like contacts name,number and image display sort of listing i m suffering with i have searched many blogs but without success please help....
public class Listmain extends ListActivity
{
#Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
Data_baseActivity db=new Data_baseActivity(this);
db.open();
InputStream is;
Cursor cursor =db.getAllContacts1();
int len=cursor.getCount();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, cursor, new String[] { "image", "name"}, new int[] { R.id.icon, R.id.label});
adapter.setViewBinder(new ProductViewBinder());
setListAdapter(adapter);
db.close();
}
catch(Exception e)
{
Toast.makeText(this, e.toString()+" error", Toast.LENGTH_LONG).show();
}
}
}
public class ProductViewBinder implements ViewBinder
{
public boolean setViewValue(View view, Cursor cursor, int columnIndex)
{
try
{
if (view instanceof ImageView)
{
byte[] result = cursor.getBlob(3);//my image is stored as blob in db at 3
Bitmap bmp = BitmapFactory.decodeByteArray(result, 0, result.length);
ImageView im=(ImageView)findViewById(R.id.icon);
im.setImageBitmap(bmp);
return true;
}
}
catch(Exception e)
{
Toast.makeText(Listmain.this, e.toString()+" err", Toast.LENGTH_LONG).show();
}
return false;
}
}
Try like this:
cr.getBlob(cr.getColumnIndex("Image")) //where "Image" is column name.
I used this and it worked.
If it doesn't worked. Please post the toast message that u r getting in the exception
package com.service;
import java.io.InputStream;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Listmain extends ListActivity{
Bitmap bmaps;
private FriendAdapter friendAdapter;
String forDeletion[][]=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.viewer);
EditText etxData=(EditText)findViewById(R.id.search);
etxData.setText(null);
listContacts();
}
#Override
protected void onResume() {
super.onResume();
EditText etxData=(EditText)findViewById(R.id.search);
etxData.setText(null);
listContacts();
}
public void listContacts()
{
Data_baseActivity db=new Data_baseActivity(this);
try
{
Resources res=getResources();
Drawable d = res.getDrawable(R.drawable.no_photo);
bmaps = ((BitmapDrawable)d).getBitmap();
final ListView lv = getListView();
final EditText etx=(EditText)findViewById(R.id.search);
final ImageButton imgbtn=(ImageButton)findViewById(R.id.refresh);
db.open();
Cursor cursor =getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor.getCount()<1)
{
etx.setVisibility(View.GONE);
}
startManagingCursor(cursor);
int len=cursor.getCount();
forDeletion=new String[len][4];
String[] from = new String[] {};
int[] to = new int[] {};
this.friendAdapter = new FriendAdapter(this, R.layout.rowlayout, cursor, from, to);
lv.setAdapter(friendAdapter);
etx.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
public void onTextChanged(CharSequence c, int s,
int e, int h) {
try
{
Data_baseActivity db1=new Data_baseActivity(Listmain.this);
db1.open();
Cursor searchCursor =getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,
ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?" , new String[]{c+"%"}, null);
startManagingCursor(searchCursor);
String[] from = new String[] {};
int[] to = new int[] {};
friendAdapter = new FriendAdapter(Listmain.this, R.layout.rowlayout, searchCursor, from, to);
lv.setAdapter(friendAdapter);
db1.close();
}
catch(Exception es)
{
Toast.makeText(Listmain.this, es.toString()+" g", Toast.LENGTH_LONG).show();
}
}
});
}
catch(Exception e)
{
Toast.makeText(this, e.toString()+" error", Toast.LENGTH_LONG).show();
}
db.close();
}
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent=new Intent(Listmain.this,Editing.class);
String send[]=new String[4];
send[0]=forDeletion[position][0];
send[1]=forDeletion[position][1];
send[2]=forDeletion[position][2];
send[3]=forDeletion[position][3];
intent.putExtra("com.service.id", send);
startActivity(intent);
}
public class FriendAdapter extends SimpleCursorAdapter
{
private final Context mContext;
private final int mLayout;
private final Cursor mCursor;
private final int mNameIndex;
private final int mIdIndex;
private final LayoutInflater mLayoutInflater;
private int lookUp;
private final class ViewHolder {
public TextView name;
public ImageView image;
public TextView number;
public ImageView endis;
}
public FriendAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mContext = context;
this.mLayout = layout;
this.mCursor = c;
this.mNameIndex = mCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
this.mIdIndex = mCursor.getColumnIndex(ContactsContract.Contacts._ID);
this.lookUp=mCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
this.mLayoutInflater = LayoutInflater.from(mContext);
}
public View getView(int position, View convertView, ViewGroup parent) {
try
{
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder = null;
String name = mCursor.getString(mNameIndex);
if (convertView == null)
{
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.label);
viewHolder.number = (TextView) convertView.findViewById(R.id.number);
viewHolder.image = (ImageView) convertView.findViewById(R.id.icon);
viewHolder.endis = (ImageView) convertView.findViewById(R.id.endis);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
String number = null;
String image = mCursor.getString(mIdIndex);
String lookup=mCursor.getString(lookUp);
long lid=Long.parseLong(image);
Bitmap bmp = loadContactPhoto(mContext.getContentResolver(),lid,mContext);
if(bmp==null)
{
bmp=bmaps;
}
viewHolder.image.setImageBitmap(bmp);
viewHolder.name.setText(name);
Cursor cur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? " , new String[] {image}, null);
String num=null;
while(cur.moveToNext())
{
num = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
num=num+"\n";
}
number=num;
viewHolder.endis.setVisibility(View.GONE);
viewHolder.number.setText(number);
forDeletion[position][0]=name;
forDeletion[position][1]=number;
forDeletion[position][2]=image;
forDeletion[position][3]=lookup;
}
}
catch(Exception e)
{
Toast.makeText(Listmain.this, e.toString()+" 2", Toast.LENGTH_LONG).show();
}
return convertView;
}
}
public Bitmap loadContactPhoto(ContentResolver cr, long id,Context ctx) {
InputStream input=null;
try
{
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
input= ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
}
catch(Exception e)
{
Toast.makeText(ctx, "Image formation error", Toast.LENGTH_LONG).show();
}
Bitmap bmp=BitmapFactory.decodeStream(input);
return bmp;
}
}
## Heading ##
Write a class and extend simpleCusorAdapter in it.
Create a constructor in the class and take parameters: context, layout, cursor, from, to
In the constructor, intialize the views of your customized layout like this.imageContainer=container.
I have created one gallery application, its working fine. If i run the gallery display all sdcard images.
But how do I get pictures from a specific folder? Do I need to change the query?
Example: wallpapers, images, camera, album, etc.
My source code:
package image.Thumbnails;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class ImageThumbnailsActivity extends Activity {
/** Called when the activity is first created. */
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);
setContentView(R.layout.main);
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 ImageAdapter(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(getApplicationContext(),
ViewImage.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(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;
}
}
}
Here is a link to the source code for the Android Gallery app:
https://android.googlesource.com/platform/packages/apps/Gallery3D
You can use this as an example or a starting point for your app.
try this
How to create a new folder when taking a photo from custom camera application?