Android GridView - notifyDataSetChanged not refreshing the GridView - android

I am writing an app that displays a grid of images stored on a local database using GridView. I implemented the deleteSelectedImage method triggered by a button which deletes a given image of the grid in the database. The deletion works, but I cannot get my GridView to refresh by itself... If I close the activity and then open it again, the changes are visible.
Here's my code :
The activity :
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
public class GalleryShowActivity extends AppCompatActivity {
private final String DEBUG_TAG = "GalleryShowActivity";
private DatabaseHandler db;
private Cursor c;
private ImageAdapter mBaseAdapter;
private TextView selectedImageText;
private GridView mGridView;
// currently selected position in the grid
private int mSelectedPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_show);
db = new DatabaseHandler(this);
c = db.getCursorOnAllImages(this);
mBaseAdapter = new ImageAdapter(this, c, db);
mSelectedPos = -1;
selectedImageText = (TextView) findViewById(R.id.selectedImageText);
selectedImageText.setText("Selected image : NONE");
mGridView = (GridView) findViewById(R.id.gridview);
mGridView.setAdapter(mBaseAdapter);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Log.d(DEBUG_TAG, "IMAGE CLICKED");
// click selects an image (can be changed later)
mSelectedPos = position;
selectedImageText.setText("Selected image : " + (position + 1));
}
});
}
public void deleteSelectedImage(View view) {
boolean exists = c.moveToPosition(mSelectedPos);
if (exists) {
boolean success = db.deletePointedPicture(c, this);
if (success) {
Log.d(DEBUG_TAG, "DELETE SUCCESS");
mBaseAdapter.notifyDataSetChanged();
// display a success message...
}
} else {
// display an error...
}
}
}
And here is the code for the ImageAdapter class :
package ch.epfl.sweng.project;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
class ImageAdapter extends BaseAdapter {
private Context mContext;
private Cursor mCursor;
private DatabaseHandler mHandler;
ImageAdapter(Context context, Cursor cursor, DatabaseHandler handler) {
mContext = context;
mCursor = cursor;
mHandler = handler;
}
#Override
public int getCount() {
return mCursor.getCount();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int rowHeight = 200;
int rowWidth = 300;
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(rowWidth, rowHeight));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = mHandler.getImageByIndex(mCursor, position);
imageView.setImageBitmap(bm);
imageView.setVisibility(View.VISIBLE);
return imageView;
}
}
I also tried this :
mBaseAdapter = new ImageAdapter(this, c, db);
mGridView.setAdapter(mBaseAdapter);
Instead of :
mBaseAdapter.notifyDataSetChanged();
But it did not work.

You are implementing it wrong. Even after deletion data in cursor will be same. Data in cursor is only updated when onCreate() is again called. Either update the cursor on deleteSelectedImage method after deleting the data and then call notifyDataSetChanged or try to pass list instead of cursor in constructor and while deleting, delete data from list as well as database and then call notifyDataSetChanged.

Related

Grid view to stay intact once imageview image is changed

I am developing a game in Android where in the alpha value is changed once the image in the imageview and the image in the grid view match. If the number of matches are equal to 4, I need to change the image in the imageview and again compare with the images in the grid view.
I change the image in the imageview using imageView.setImageResource(q);
The image gets changed but the grid view disappears. Could you please tell me what I need to do for the grid view to change intact?
I tried gridView.invalidateViews(); but in vain. I also created a new imageadapter with the same context but it still did not work. Any help would be really great!
package com.example.despicablemehunt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
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.ListAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
final public Integer[] mThumbIds = {
R.drawable.icon1, R.drawable.icon2,
R.drawable.icon3, R.drawable.icon4,
R.drawable.icon1, R.drawable.icon2,
R.drawable.icon3, R.drawable.icon4,
R.drawable.icon1, R.drawable.icon2,
R.drawable.icon3, R.drawable.icon4,
R.drawable.icon1, R.drawable.icon2,
R.drawable.icon3, R.drawable.icon4
};
int i=0;
int p=0;
final Integer q=0;
public Context mContext;
List<Integer> imagesArrayList = new ArrayList<Integer>(Arrays.asList(mThumbIds));
Integer [] tempArrayList;
public static final Random rgenerator = new Random();
public static final Integer[] mImageIds =
{ R.drawable.icon1, R.drawable.icon2, R.drawable.icon3,R.drawable.icon4 };
#Override
protected void onCreate(Bundle savedInstanceState) {
final long time= System.currentTimeMillis();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Collections.shuffle(imagesArrayList);
tempArrayList = (Integer[])(imagesArrayList.toArray(new Integer[imagesArrayList.size()]));
final GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
final Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
final ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageResource(q);
gridView.setOnItemClickListener(new OnItemClickListener() {
#SuppressLint("NewApi")
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(getResources().getDrawable(q).getConstantState().equals(getResources().getDrawable(tempArrayList[arg2]).getConstantState()))
{
if(p==5)
{
/*final long time1= System.currentTimeMillis();
if ((time1-time)> 20)
{
}*/
Toast.makeText(getApplicationContext(), "DONE DONE DONE", Toast.LENGTH_SHORT).show();
}
arg1.setAlpha((float) 0.4);
if((++i)== 4)
{
gridView.setAlpha((float)0.0);
p++;
final Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
ImageView imageView = (ImageView) iv;
imageView.setImageResource(q);
i=0;
gridView.invalidate();
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class ImageAdapter extends BaseAdapter {
// Keep all Images in array
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(tempArrayList[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(50, 50));
return imageView;
}
}
}
To refresh the gridview you have to use gridView.invalidateViews(); So change it
after 4 correct click on gridview image why are you setting alpha 0 in gridview. So just remove the line
gridView.setAlpha((float)0.0);
//setting alpha causing the gridview invisible
so your code should be like this
if ((++i) == 4) {
p++;
final Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
ImageView imageView = (ImageView) iv;
iv.setImageResource(q);
i = 0;
gridView.invalidateViews();
}
hope this will help
Thanks

Slow Application performance

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);
}
};
}
}

CustomAdapter with multiple getView in android

I have an activity, where in i display list of media files i.e Video, Audio, Images and Animations. On clicking the list item, (as of now Images), the activity must display all the images in the local assets folder in grid View. To do so, i use a single adapter and have a switch case in my getView() function. Depending on the options that is set in the constructor, the switch cases would execute. It works fine for the ListView display, but i am unable to display list of images in grid View. Any help would be apprecaited. Thanks in advance. Here is my code:
package com.bookshelf;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MediaGalaryListActivity extends Activity implements
OnItemClickListener {
private ArrayList<String> mGalary = new ArrayList<String>();
private Bitmap mBitArray[];
private Gallery mMediaGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mediagalary);
mGalary.add("Videos");
mGalary.add("Audios");
mGalary.add("Images");
mGalary.add("Animation");
ListView lv = (ListView) findViewById(R.id.mediaGal);
mMediaGallery = (Gallery) findViewById(R.id.mediaGallery);
lv.setAdapter(new MediaGalaryAdapter(this, mGalary, 1));
lv.setOnItemClickListener(this);
}
class MediaGalaryAdapter extends BaseAdapter {
private ArrayList<String> mGal = new ArrayList<String>();
private Bitmap[] mImgArray;
private Context context;
private LayoutInflater mInflate;
private int mAdapterOpt;
public MediaGalaryAdapter(Context ctx, ArrayList<String> gal,
int adapOpt) {
context = ctx;
mGal = gal;
mAdapterOpt = adapOpt;
mInflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public MediaGalaryAdapter(Context ctx, Bitmap[] imgArray, int adapOpt) {
context = ctx;
mImgArray = imgArray;
mInflate = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mAdapterOpt = adapOpt;
}
public int getCount() {
int size = 0;
switch (mAdapterOpt) {
case 1:
size = mGal.size();
break;
case 2:
size = mImgArray.length;
break;
}
return size;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
switch (mAdapterOpt) {
case 1:
convertView = mInflate.inflate(R.layout.medialayout, null);
TextView tv = (TextView) convertView.findViewById(R.id.text);
tv.setText(mGal.get(position));
break;
case 2:
ImageView imgView;
convertView = mInflate.inflate(R.layout.image_gallery, null);
imgView = new ImageView(context);
imgView.setImageBitmap(mImgArray[position]);
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setLayoutParams(new GridView.LayoutParams(100, 100));
imgView.setPadding(8, 8, 8, 8);
break;
}
return convertView;
}
}
// For filtering the filename with extensions
class FileNamFilter implements FilenameFilter {
private String mFileExtn;
public FileNamFilter(String extn) {
mFileExtn = "." + extn;
}
public boolean accept(File dir, String filename) {
return filename.endsWith(mFileExtn);
}
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
String mediaType = mGalary.get(pos);
String list[] = null;
AssetManager assetManager = getAssets();
try {
list = assetManager.list("Immersive");
mBitArray = new Bitmap[list.length];
System.out.println("Length of list ="+list.length);
for (int i = 0, idx = 0; i < list.length; i++)
{
if (list[i].endsWith(".png") || list[i].endsWith(".gif")
|| list[i].endsWith(".jpeg")
|| list[i].endsWith(".jpg"))
{
mBitArray[idx++] = BitmapFactory.decodeStream(assetManager
.open("Immersive/" + list[i]));
System.out.println("Image at position "+i+" is "+list[i]);
}
;
}
mMediaGallery
.setAdapter(new MediaGalaryAdapter(this, mBitArray, 2));
} catch (IOException e) {
e.printStackTrace();
}
AlertDialog.Builder build = new AlertDialog.Builder(this);
build.setTitle("InProgress....");
// build.setIcon(android.R.drawable.)
build.setMessage(mediaType + " is Inprogress...");
build.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// finish();
}
});
AlertDialog alert = build.create();
alert.show();
// Toast.makeText(getApplicationContext(), mediaType, 30).show();
}
class MediaGalary {
private ImageView mImage;
private TextView mName;
public MediaGalary(ImageView img, TextView strName) {
mImage = img;
mName = strName;
}
public ImageView getmImage() {
return mImage;
}
public void setmImage(ImageView mImage) {
this.mImage = mImage;
}
public TextView getmName() {
return mName;
}
public void setmName(TextView mName) {
this.mName = mName;
}
}
}
each application in the device will be allocated some amount of memory by the DVM. you are getting out of memory error becoz your application is exceeding the memory the allocated by dvm to ur application. for example in froyo, memory allocated for an application is 16Mb. if your application exceeding more than 16Mb, you will get out of memory error. The solution for this is you have to compress the images you are using in your application, and you have to clear all the collection you are using. try clearing all collection you are using once there job is done. you can check how much memory has been consumed by your application in ddms using heap tool. hope this will be helpfull for you.

how to view next image in imageview?

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

Android-Listview ClickListener

I have a list in which each object is of type Task. I have created a list that sows all the task details in the row of the list.
My code is given below:
lv=this.getListView();
if(createtaskSubList().size() != 0)
{
//createTaskSubList gives me the List of taskObjects
MyCustomAdapter adapter = new MyCustomAdapter(this,createtaskSubList());
lv.setAdapter(adapter);
lv.setDividerHeight(2);
lv.invalidateViews();
}
}
private ArrayList<Task> createtaskSubList() {
// TODO Auto-generated method stub
ArrayList<Task> taskSubList= new ArrayList<Task>();
String[] values={ Integer.toString(userId),Integer.toString(number),Integer.toString(page)};
String taskList = Helper.getfromUrl(taskDataFetch,values);
if(taskList.length()!=0)
{
String delims = ("[|]");
String[] tasks = taskList.split(delims);
int i=0;
//Splitting Task series into individual items
for (i = 0; i < tasks.length; i++) {
String limit = ("','");
String[] taskItem = tasks[i].split(limit);
taskSubList.add(new Task(taskItem[1],Integer.parseInt(taskItem[2]),Integer.parseInt(removeCharAt(taskItem[0],0)),Integer.parseInt(taskItem[4]),Integer.parseInt(taskItem[5]),taskItem[6],Integer.parseInt(taskItem[3])));
}
}
return taskSubList;
}
Now my arrayadpter class is:
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyCustomAdapter extends ArrayAdapter<Task> {
private final Activity context;
ArrayList<Task> taskSubList =new ArrayList<Task>();
public MyCustomAdapter(Activity context,ArrayList<Task> taskSubList) {
super(context, R.layout.teammember, taskSubList);
this.context = context;
this.taskSubList=taskSubList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.teammember, null, true);
final TextView text = (TextView) rowView.findViewById(R.id.label);
final TextView status = (TextView) rowView.findViewById(R.id.status);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//time.setText(formatTime(taskSubList.get(position).getTimeSpent()));
text.setText(taskSubList.get(position).getName());
if(taskSubList.get(position).isCompleted()==0)
{
status.setText("Not Completed");
status.setTextColor(Color.RED);
}
else
{
status.setText("Completed");
status.setTextColor(Color.parseColor("#468765"));
}
return rowView;
}
I need to change it such a way that list should contain only names and when I click on these names an intent has to be called which gives a layout showing the details of that particular TaskObject.Details here means the properties of that task object which should be shown in the form of text views in new layout.Not a dialog or Toast..
In your getView()
status.setOnClickListener(new MyClickListener(position));
public class MyClickListener implements OnClickListener {
private int posi;
public MyClickListener(int position) {
this.posi = position;
}
public void onClick(View v) {
CustomDialog customDialog = new CustomDialog(ViewDetials.this);
customDialog.show();
// Toast.makeText(getBaseContext(), "text view clicked",Toast.LENGTH_SHORT).show();
}
}
}

Categories

Resources