Hi can somebody help me with my code?? I have a class which should show me folders on my SD card+ folders name, but all folders have same name, but each should have different. How can i implement it??
public class ThumbnailAdapter extends BaseAdapter {
// Context required for performing queries
private final Context mContext;
// Cursor for thumbnails
private final Cursor cursor;
private final int count;
String bucket;
String id;
public ThumbnailAdapter(Context c) {
this.mContext = c;
// Get list of all images, sorted by last taken first
final String[] projection = {
MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME
};
String BUCKET_GROUP_BY =
"1) GROUP BY 1,(2";
String BUCKET_ORDER_BY = "MAX(datetaken) DESC";
cursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
BUCKET_GROUP_BY,
null,
BUCKET_ORDER_BY
);
if (cursor.moveToFirst()) {
int bucketColumn = cursor.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int idColumn = cursor.getColumnIndex(
MediaStore.Images.Media.BUCKET_ID);
do {
// Get the field values
bucket = cursor.getString(bucketColumn);
id = cursor.getString(idColumn);
} while (cursor.moveToNext());
}
count = cursor.getCount();
Log.d("ThumbnailAdapter", count + " images found");
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout ll = new LinearLayout(mContext);
ImageView imageView = new ImageView(mContext);
TextView mytext = new TextView(mContext);
mytext.setText(bucket);
imageView.setImageResource(R.drawable.your_folder_icon);
ll.addView(imageView);
ll.addView(mytext);
return ll;
}
You are probably not setting your TextView mytext to change the text it displays - try the line:
mytext.setText(projection[position]);
I'm not quite sure how you are indexing your projection String array, but by just providing the right index (using the position variable in the getView() method, you should be able to change the TextView name correctly.
Related
I know that here are many answers how to delete items, but I can't make it work. It show errors. Can you look? I added in adapter remove(position), but I think it works wrongly.
So I want after using onItemLongClickListener to delete file and its thumbnail too.
Main:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView grid = (GridView) findViewById(R.id.gridview);
final ThumbnailAdapter thumbnails = new ThumbnailAdapter(this);
grid.setAdapter(thumbnails);
grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int position,
long id) {
final String imgPath = thumbnails.getImagePath(position);
File file = new File(imgPath);
file.delete();
thumbnails.remove(position);
thumbnails.notifyDataSetChanged();
grid.invalidateViews();
grid.setAdapter(thumbnails);
return true;
}
});
Adapter:
public class ThumbnailAdapter extends BaseAdapter {
// Context required for performing queries
private final Context mContext;
// Cursor for thumbnails
private final Cursor cursor;
private final int imgId;
private final int imgData;
private final int count;
public ThumbnailAdapter(Context c) {
this.mContext = c;
// Get list of all images, sorted by last taken first
final String[] projection = {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA
};
cursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
MediaStore.Images.Media.DATE_TAKEN + " DESC"
);
imgId = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
imgData = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
count = cursor.getCount();
Log.d("ThumbnailAdapter", count + " images found");
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
cursor.moveToPosition(position);
final Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(
mContext.getContentResolver(),
cursor.getInt(imgId),
MediaStore.Images.Thumbnails.MICRO_KIND,
null
);
imageView.setImageBitmap(thumbnail);
Log.d("ThumbnailAdapter", "render: " + cursor.getString(imgData));
return imageView;
}
public String getImagePath(int position) {
cursor.moveToPosition(position);
return cursor.getString(imgData);
}
public void remove(int position) {
remove(position);
notifyDataSetChanged();
}
}
I guess its stack overflow. your remove method in the adapter is recursive forever.
Instead of deleting file youself ask content resolver to remove it. and the reload data.
you dont have to call grid.setAdapter(thumbnails) again in the click listner
Check this line please though :
file.delete();
thumbnails.remove(position);
You are deleting your file first and then removing it from adapter. It should be other way around. You reset your adapter then delete the actual file. Your thumbnail is deleted while still being attached to the adapter.
I have sqlite column is defined like this:
public final static String S_ID = "_ID";
public final static String S_PHOTOPATH = "Photopath";
public final static String S_NAME = "Name";
public final static String S_POS = "Pos";
public final static String S_SCORE = "Score";
public final static String S_FIXED = "Fixed";
I'd like to getItemID from a sqlite helper class with a adapter class extends BaseAdapter. Here is my code:
public class Page1ListAdapter extends BaseAdapter {
private LayoutInflater adapterInflater;
public Cursor mCursor;
TagView tag;
public Page1ListAdapter(Context context, Cursor cursor) {
super();
mCursor = cursor;
adapterInflater=LayoutInflater.from(context);
}
#Override
public int getCount() {
return mCursor.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
tag = new TagView();
convertView = adapterInflater.inflate(R.layout.page1listview_item, null);
tag.imgV = (ImageView) convertView.findViewById(R.id.ItemImage);
tag.titleV = (TextView) convertView.findViewById(R.id.ItemTitle);
tag.descriptionV = (TextView) convertView.findViewById(R.id.ItemText);
convertView.setTag(tag);
} else {
tag = (TagView) convertView.getTag();
}
mCursor.moveToPosition(position);
Bitmap bmp = BitmapFactory.decodeFile(mCursor.getString(mCursor.getColumnIndex(DBHelper.S_PHOTOPATH)));
BitmapDrawable bmpDrawable = new BitmapDrawable(getActivity().getResources(), bmp);
tag.imgV.setBackground(bmpDrawable);
tag.titleV.setText(mCursor.getString(mCursor.getColumnIndex(DBHelper.S_NAME)));
tag.descriptionV.setText(mCursor.getString(mCursor.getColumnIndex(DBHelper.S_POS)));
return convertView;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
Log.i("mCursor.getCount() --->", String.valueOf(mCursor.getCount()));
mCursor.move(position);
long id = mCursor.getLong(0); // <--- error here
return id;
}
public void setTag (Drawable dwb, String title, String description) {
tag.imgV.setBackground(dwb);
tag.titleV.setText(title);
tag.descriptionV.setText(description);
}
}
However, the getItemID() always get error or wrong ID.
How could I get the _ID column value with cursor?
Thanks in advance!
Cursor.move() moves the cursor by relative amount. You want an absolute position, use moveToPosition() instead.
First initialize database obj like below
SQLiteDatabase db = myDb.getReadableDatabase();
Put your parameter names into query.But I inserted it.
try{
Cursor cursor=db.query(DB_helper.YourTableName, new String[] {"_ID","Photopath","Name","Pos","Score","Fixed"}, null,null, null, null, null);
if(cursor.getCount()>0){
cursor.moveToFirst();
do{
//cursor.getString(0); Means get String from first column(_ID)
USER_ID =cursor.getString(0);
USERNAME=cursor.getString(3);
USERTYPE=cursor.getString(5);
PLANTID =cursor.getString(4);
}while (cursor.moveToNext());
cursor.close();
db.close();
}
}catch(Exception e){
e.printStackTrace();
}
You can store it values into String on into array list and use it anywhere.
Thanks
Ok so im making a media player app for android. everything was ok until now. so far i have a list view that shows all .mp3 files on ur sdcard(internal and external) and when playing show a music visualizer. but i cant for the life of me alphabetize the list. everything is dynamic so xml doesnt work here.
public class MusicPlayerActivity extends Activity {
ListView musiclist;
Cursor musiccursor;
int music_column_index;
int count;
private Intent aIntent;
public static String filename;
private RelativeLayout mRelativeLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init_phone_music_grid();
mRelativeLayout = new RelativeLayout(this);
setContentView(mRelativeLayout);
mRelativeLayout.addView(musiclist);
}
public void init_phone_music_grid() {
System.gc();
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ALBUM
};
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
musiccursor = managedQuery(allsongsuri, projection , selection, null, null);
count = musiccursor.getCount();
musiclist = (ListView) findViewById(R.id.PhoneMusicList);
musiclist.setAdapter(new EfficientAdapter(getApplicationContext()));
musiclist.setOnItemClickListener(musicgridlistener);
}
private OnItemClickListener musicgridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id) {
System.gc();
music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
musiccursor.moveToPosition(position);
filename = musiccursor.getString(music_column_index);
aIntent = new Intent(v.getContext(), AudioFX.class);
aIntent.getStringExtra(filename);
startActivity(aIntent);
}
};
class EfficientAdapter extends BaseAdapter {
private Context mContext;
public EfficientAdapter(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();
String id = null;
TextView tv;
if (convertView == null) {
tv = new TextView(mContext.getApplicationContext());
} else{
tv = (TextView) convertView;
}
musiccursor.moveToPosition(position);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
id = musiccursor.getString(music_column_index);
tv.setText(id);
tv.setTextSize(20);
return tv;
}}}
You just need to use DEFAULT_SORT_ORDER, like this:
String sortOrder = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
musiccursor = managedQuery(allsongsuri, projection , selection, null, sortOrder);
Showing the title inside the getView method won't get a alphabetized list.
Inorder to alphabetize the list get all the music titles into a String array or an ArrayList
Alphabetize them manually and pass that String array to EfficientAdapters Constructor and store it locally and use them according to the lists position.
like
class EfficientAdapter extends BaseAdapter {
private Context mContext;
private String values[];
public EfficientAdapter(Context c, String[] a) {
mContext = c;
values = a;
}
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();
String id = null;
TextView tv;
if (convertView == null) {
tv = new TextView(mContext.getApplicationContext());
} else{
tv = (TextView) convertView;
}
id = values[position];
tv.setText(id);
tv.setTextSize(20);
return tv;
}}}
Hope this helps.....
(Sorry I'm not good at English)
I haved created a custom BaseAdapter to show my data from sqlite to a ListView.
Now I can see list but when i scroll listview quickly, rows are view oddly. I can't understand this. And one more strange point is that, if i have 5 data row, getView run 5 time but only first 4 row can be show. I use log and i see 5 time "return view;" clearly.
Here are my adapter code:
public class LocalRankAdapter extends BaseAdapter {
private static final String FIELD1 = "time";
private static final String FIELD2 = "name";
private static final String TABLE_NAME = "rank";
private static final String FIELD_ORDER = "time";
private DataBaseHelper dbHelper;
private Cursor mCursor;
private Context mContext;
private int timeColIndex;
private int nameColIndex;
private int index;
private int length;
public static float recent_time=0;
public static String recent_playerName="";
public LocalRankAdapter(Context context, DataBaseHelper mdbHelper) {
mContext=context;
dbHelper=mdbHelper;
// get data from database
mCursor = dbHelper.getData(TABLE_NAME, new String[] { FIELD1, FIELD2 }, FIELD1 + " !=0 ", FIELD_ORDER + " ASC");
mCursor.moveToFirst();
length=mCursor.getCount();
timeColIndex=mCursor.getColumnIndex(FIELD1);
nameColIndex=mCursor.getColumnIndex(FIELD2);
index=1;
}
public static void insertData(DataBaseHelper dbHelper, float currentTime, String name) {
ContentValues cv=new ContentValues();
cv.put(FIELD1, currentTime);
cv.put(FIELD2, name);
dbHelper.insertData(TABLE_NAME, new String[] {FIELD1, FIELD2}, cv);
}
#Override
public int getCount() {
return length-1;
}
#Override
public View getView(int id, View convertView, ViewGroup parent) {
View v=convertView;
if (convertView == null) {
v=convertView;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, parent, false);
TextView rankNumber=(TextView) v.findViewById(R.id.txtRank);
TextView time=(TextView) v.findViewById(R.id.txtTime);
TextView playerName=(TextView) v.findViewById(R.id.txtPlayerName);
String timeStr=mCursor.getString(timeColIndex);
String playerNameStr=mCursor.getString(nameColIndex);
if(Float.parseFloat(timeStr)==(recent_time/1000f) && playerNameStr.equals(recent_playerName)) {
v.setBackgroundColor(mContext.getResources().getColor(R.color.item_bg_recent));
rankNumber.setText(String.valueOf(index++)+" (Your)");
} else rankNumber.setText(String.valueOf(index++));
time.setText(timeStr);
playerName.setText(playerNameStr);
mCursor.moveToNext();
return v;
}
return v;
}
#Override
public Object getItem(int id) {
return id;
}
#Override
public long getItemId(int arg0) {
return 0;
}
public static void setModeView(int mtime, String mplayerName) {
recent_time=mtime;
recent_playerName=mplayerName;
}
}
you change your query
String getData = "SELECT " + FIELD1 + "," + FIELD2 + " FROM " + TABLE_NAME;
Cursor cursor;
cursor = myDataBase.rawQuery(getData, null);
while (cursor.moveToNext()) {
//String cursor.getColumnIndex(FIELD1);
int id = cursor.getInt(1);
String name = cursor.getString(0);
}
I see one possible problem here:
#Override
public int getCount() {
return length-1;
}
You should write return length; because length=mCursor.getCount()
Another issue that you use cursor inside getView and just do moveNext on it.
I think it is not good idea because fetching data isn't quick process. So it cause lags on scrolling. Try to read complete dataset to internal list of structures and use it in getView.
public class VideoDemo extends Activity {
private VideoView video;
private MediaController ctlr;
File clip=new File(Environment.getExternalStorageDirectory();
{
if (clip.exists()) {
video=(VideoView)findViewById(R.id.videoGrdView);
video.setVideoPath(clip.getAbsolutePath());
ctlr=new MediaController(this);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
}
}};
}
}
So i've got a VideoGrdView of all videos on my sd card to display in a separate activity, now i need to know how to click a video from the grid and have it play through this media player. Any help is appreciated.
public class Menus extends Activity {
//set constants for MediaStore to query, and show videos
private final static Uri MEDIA_EXTERNAL_CONTENT_URI =
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private GridView _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
protected Context _context;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_context = getApplicationContext();
_gallery = (GridView) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
//initialize the videos uri
//showToast(_contentUri.getPath());
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(_itemClickLis);
}
private AdapterView.OnItemClickListener _itemClickLis = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
// We want to get the column index for the data uri
int count = _cursor.getCount();
//
_cursor.moveToFirst();
//
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
startActivity(new Intent("com.ave"));
}
};
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
}
}
//
private class VideoGalleryAdapter extends BaseAdapter
{
public VideoGalleryAdapter(Context c)
{
_context = c;
}
public int getCount()
{
return _videosId.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(_context);;
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setLayoutParams(new GridView.LayoutParams(96, 96));
imgVw.setPadding(8, 8, 8, 8);
}
catch(Exception ex)
{
System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +", "+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(
getContentResolver(),
id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
return thumb;
}
}
}
Gallery, pretty much works the same way as a ListView. Inside the onItemClick method, you should be able to know which specific item was clicked. Get the Uri/absolute path for that item, and pass on that information to the next activity.
In the VideoDemo class, extract this Uri/path and set it to the VideoView.