I am Doing Musicplayer Application. and want to show All the Songs with respect to its Genre. if possible then please give me some hint for that. i able to display all the Song With Respect to Artist and Album but Facing Problem While Going For Genre Wise Song. my out put is displaying all the Songs in Each genre catagory. it is not saprating the Song According to genre. Mycode is Below.
LocalGenre.java
package com.PageViewerTilesDemo.src;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Window;
import android.widget.ExpandableListView;
import android.widget.TextView;
public class LocanGenre extends Activity {
ExpandableListView listLocalArtists;
TextView txttitle;
Cursor musiccursor, musiccursor1;
int music_column_index, music_column_index1;
int count, count1;
ArrayList<String> genresName = new ArrayList<String>();
ArrayList<String> genreID = new ArrayList<String>();
ArrayList<Integer> albumID = new ArrayList<Integer>();
ArrayList<String> numberOFSongs = new ArrayList<String>();
ArrayList<String> artistName = new ArrayList<String>();
ArrayList<String> path = new ArrayList<String>();
ArrayList<String> path12 = new ArrayList<String>();
ArrayList<ArrayList<String>> pathDisplay = new ArrayList<ArrayList<String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.localartists);
txttitle = (TextView) findViewById(R.id.title);
txttitle.setText("Genres");
listLocalArtists = (ExpandableListView) findViewById(R.id.listView1);
init_phone_music_grid();
listLocalArtists.setAdapter(new ExpandableListGenreAdapter(this, path, genresName,
genresName, pathDisplay,albumID));
}
private void init_phone_music_grid() {
// TODO Auto-generated method stub
System.gc();
String[] proj = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ALBUM_ID};
musiccursor1 = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
null);
count1 = musiccursor1.getCount();
if (count1 > 0) {
musiccursor1.moveToFirst();
do {
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
String filename0 = musiccursor1.getString(music_column_index1);
path.add(filename0);
Log.i("LocalGenres ", "Path Main" + path);
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
String filename123 = musiccursor1
.getString(music_column_index1);
path12.add(filename123);
Log.i("LocalGenre", "Media ID " + path12);
music_column_index1 = musiccursor1
.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
int filename1 = musiccursor1.getInt(music_column_index1);
albumID.add(filename1);
Log.i("LOCAL Genres!!!", " ALBUM ID" + albumID);
} while (musiccursor1.moveToNext());
}
String[] projection = { MediaStore.Audio.Genres._ID,
MediaStore.Audio.Genres.NAME};
musiccursor = managedQuery(
MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, projection, null,
null, null);
genresName.clear();
count = musiccursor.getCount();
if (count > 0) {
musiccursor.moveToFirst();
do {
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
String filename = musiccursor.getString(music_column_index);
if(!genreID.contains(filename))
{
genreID.add(filename);
}
Log.i("Local Genres ", "Genre ID" + genreID);
music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
String filename1 = musiccursor.getString(music_column_index);
if(!genresName.contains(filename1))
{
genresName.add(filename1);
}
Log.i("Local Genres ", "Genres Name " + genresName);
/*
* music_column_index = musiccursor
* .getColumnIndexOrThrow(MediaStore.Audio.Genres._COUNT);
*
* String filename3 = musiccursor.getString(music_column_index);
* artistName.add(filename3);
*
* Log.i("Local Albums ", "Album ID for Gen " + artistName);
*/
} while (musiccursor.moveToNext());
}
for (int j = 0; j < genreID.size(); j++) {
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < path12.size(); i++) {
Log.i("EEEEEE", "Inside If path12.get(i) :"+path12.get(i));
Log.i("EEEEEE", "Inside If genreID.get(j) :"+genreID.get(j));
Log.i("EEEEEE", "Inside If Integer.parseInt(path12.get(i)) :"+Integer.parseInt(path12.get(i)));
Log.i("EEEEEE", "Inside If j : "+j);
if (path12.get(i).equalsIgnoreCase(genreID.get(j)) || Integer.parseInt(path12.get(i))>j) {
Log.i("EEEEEE", "Inside If");
arr.add(path.get(i));
}
else
Log.i("xxxxxxx", "Inside else");
arr.add(path.get(i));
}
Log.i("EEEEEE", "Inside outerloop " + arr);
pathDisplay.add(arr);
}
}
}
ExpandableListGenreAdapter.java
package com.PageViewerTilesDemo.src;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ExpandableListGenreAdapter extends BaseExpandableListAdapter{
private Context context;
private ArrayList<String> artist;
private ArrayList<String> genres;
private ArrayList<ArrayList<String>> children;
public ArrayList<String> pathmain ;
public ArrayList<Integer> genresID;
public ArrayList<Integer> albumID;
public ExpandableListGenreAdapter(Context context, ArrayList<String> path, ArrayList<String> groups,ArrayList<String> artist,
ArrayList<ArrayList<String>> children, ArrayList<Integer> albumID) {
this.context = context;
this.genres = groups;
this.artist = artist;
this.pathmain = path;
this.children = children;
this.albumID=albumID;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return children.get(groupPosition).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
/*public Bitmap getAlbumart(int album_id)
{
Bitmap bm = null;
try
{
final Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ParcelFileDescriptor pfd = context.getContentResolver()
.openFileDescriptor(uri, "r");
if (pfd != null)
{
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd);
}
} catch (Exception e) {
}
return bm;
}*/
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final String vehicle = (String) getChild(groupPosition, childPosition);
Log.i("ExpandableListAdapter", "Group Position "+groupPosition);
Log.i("ExpandableListAdapter", "Vehicle "+vehicle);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_layout, null);
}
TextView tv = (TextView) convertView.findViewById(R.id.tvChild);
ImageView imageview1=(ImageView)convertView.findViewById(R.id.ImageView01);
// bm=getAlbumart(albumids.get(1));
// Log.i("LIST ADAPTER","###################ALBUM IDS "+albumids.get(0)+"BITMAPPPPP###"+bm);
// imageview1.setImageBitmap(coverart.get(childPosition));
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.flag = true;
TestFragment3.flag = true;
Firstpage.flag = true;
Log.i("ExpandableListGenreAdapter", "path "+childPosition);
MainActivity.currentPosition = groupPosition;
Log.i("ExpandableListGenreAdapter", "currentPosition "+MainActivity.currentPosition);
MainActivity.genre=true;
MainActivity.currentgenreposition = albumID.get(childPosition);
Log.i("ExpandableListGenreAdapter", "currentGenrePosition "+MainActivity.currentgenreposition);
MainActivity.Media_full_path = "/sdcard/"+vehicle;
Log.i("ExpandableListAdapter", "Onclick "+MainActivity.Media_full_path);
((Activity)context).finish();
}
});
tv.setText(" " + vehicle.toString());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return children.get(groupPosition).size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return genres.get(groupPosition);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return genres.size();
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String group = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_layout, null);
}
TextView txtArtistsName = (TextView) convertView.findViewById(R.id.txtArtistsName);
TextView txtartistssongs = (TextView) convertView.findViewById(R.id.txtartistssongs);
txtArtistsName.setText(group);
txtartistssongs.setText(genres.get(groupPosition)+" Song(s)");
return convertView;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
Please Suggest me Where is i am missing from the Above Code. Thank You.
Hi hope this will help you. It displays the genres and their songs.
int index;
long genreId;
Uri uri;
Cursor genrecursor;
Cursor tempcursor;
String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
String[] proj2 = {MediaStore.Audio.Media.DISPLAY_NAME};
genrecursor = managedQuery(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, proj1, null, null, null);
if (genrecursor.moveToFirst()) {
do {
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
Log.i("Tag-Genre name", genrecursor.getString(index));
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
genreId = Long.parseLong(genrecursor.getString(index));
uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
tempcursor = managedQuery(uri, proj2, null,null,null);
Log.i("Tag-Number of songs for this genre", tempcursor.getCount() + "");
if (tempcursor.moveToFirst()) {
do {
index = tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
Log.i("Tag-Song name", tempcursor.getString(index));
} while(tempcursor.moveToNext());
}
} while(genrecursor.moveToNext());
}
I updated the answer of #Abhijeet for work with old versions
public void getGenres(int total) {
int index;
long genreId;
Uri uri;
Cursor genrecursor;
Cursor tempcursor;
String[] proj1 = {MediaStore.Audio.Genres.NAME, MediaStore.Audio.Genres._ID};
String[] proj2={MediaStore.Audio.Media.DISPLAY_NAME};
String result;
genrecursor = MyApplication.getAppContext().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, proj1, null, null, null);
ArrayList<Genre> genres = new ArrayList<Genre>();
Genre genre = null;
if (genrecursor!=null && genrecursor.moveToFirst()) {
do {
genre = new Genre();
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres.NAME);
if (BuildConfig.DEBUG) Log.i("Tag-Genre name", genrecursor.getString(index));
genre.setName(genrecursor.getString(index));
if(genre.getName().equalsIgnoreCase("")) {
genre.setName("no-genre");
}
index = genrecursor.getColumnIndexOrThrow(MediaStore.Audio.Genres._ID);
genreId = Long.parseLong(genrecursor.getString(index));
uri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
tempcursor = MyApplication.getAppContext().getContentResolver().query(uri, proj2, null, null, null);
if (BuildConfig.DEBUG) Log.i("Tag-Number of songs for this genre", tempcursor.getCount()+"");
genre.setNumberSongs( tempcursor.getCount());
if (!genres.contains(genre)) {
genres.add(genre);
}
if (tempcursor.moveToFirst()) {
do {
index = tempcursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
if (BuildConfig.DEBUG) Log.i("Tag-Song name", tempcursor.getString(index));
for(int i = 0;i<songs.size();i++) {
if (BuildConfig.DEBUG) Log.i("SONG", songs.get(i).getDisplayName()+ " - "+ tempcursor.getString(index));
if (tempcursor!=null && songs!=null && tempcursor.getString(index).equalsIgnoreCase(songs.get(i).getDisplayName()) ) {
songs.get(i).setGenre(genre.getName());
if (genre.isOldVersion()) {
genre.setNumberSongs(genre.getNumberSongs()+1);
}
if (genre.getNumberSongs()==0) { //Is an oldversion of android, less than 3.0
genre.setOldVersion(true);
genre.setNumberSongs(1);
}
}
}
} while(tempcursor.moveToNext());
}
} while(genrecursor.moveToNext());
}
orderList(genres);
result = "";
for(int i = 0; i < 10 && i<genres.size() ;i++) {
result += genres.get(i).toString()+",";
}
result += "Total:"+total;
}
Related
This is one of the class in my app. In this class list of recipes are displaying which were are also stored into the sqlite database. In my db I stored the each recipe name, quantity, image and price. Now i would like to set the edit text value in this class where the edit text value is the quantity value in db. but i don't know how to retreive the quantity value of a particular list items in the db and setting that value in edit text. I am getting all the db count values and stores in arraylist but how to get the particular recipe quantity?
import java.io.ByteArrayInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.restaurantapp.YourOrder.OrdersImageAdapter.ImageHolder;
public class YourOrder extends HelperActivity {
private ListView list;
private DataBaseHandler db;
ArrayList<Contact> imageArry = new ArrayList<Contact>();
OrdersImageAdapter adapter;
public static TextView toatalamount;
EditText qtyView, quantityt;
int total;
int quantity;
double recipeamount = 0;
public static Button payment;
public Integer id = null;
public String name = null;
public Integer price = null;
public int quantiy;
public String quan;
String UpdateVAlue;
double ordercount;
private Double orderTotal = 0.00;
static String ordertotalval;
public String setvaluefinal;
int dbcount = 0;
public double editcount = 0;
int count = NewBreakfastItems.getVariable();
ImageHolder holder;
ArrayList<String> getarray = new ArrayList<String>();
ArrayList<Integer> getid = new ArrayList<Integer>();
ArrayList<Integer> quantityid = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourorders);
list = (ListView) findViewById(R.id.listView1);
toatalamount = (TextView) findViewById(R.id.rupees);
db = new DataBaseHandler(this);
payment = (Button) findViewById(R.id.buy);
// Reading all contacts from database
List<Contact> contacts = db.getAllContacts();
Log.d("", "------DATABASE CONTACTS-------" + db.getAllContacts());
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage() + "Price :" + cn.getprice();
Log.d("Name: ", log);
Log.i("", "-----ID-------" + cn.getID());
Log.i("", "-----ID-------" + cn.getName());
Log.i("----recipe price---", "-----price----" + cn.getprice());
id = cn.getID();
name = cn.getName();
price = cn.getprice();
ordercount = ordercount + price;
getarray.add(cn.getName());
getid.add(cn.getID());
quantityid.add(cn.getQuantity());
Log.e("---ordercount---", "----ordercount----" + ordercount);
toatalamount.setText(String.valueOf(ordercount));
/*
* count=count+price; Log.i("---count----", "-----count----"+count);
*/
// Writing Contacts to log
Log.e("Result:========== ", "=====LOG=====" + log);
imageArry.add(cn);
}
Log.d("", "-----ID-------" + id);
Log.d("", "-----ID-------" + name);
adapter = new OrdersImageAdapter(this, R.layout.orderscart, imageArry);
list.setAdapter(adapter);
dbcount = db.getContactsCount();
Log.e("----dbcount----", "-----dbcount---" + dbcount);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Log.e("","item clicked-----");
//Toast.makeText(getApplicationContext(), "u clicked on"+position, Toast.LENGTH_SHORT).show();
}
});
payment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
Payment.class);
// intent.putExtra("count", count);
intent.putExtra("ordertotalval", ordertotalval);
intent.putExtra("name", name);
startActivity(intent);
}
});
footerBlock();
}
public class OrdersImageAdapter extends ArrayAdapter<Contact> {
// Contact contact;
Context context;
public int dltcount;
int layoutResourceId;
int adaptercount = 0;
public int extPrice;
ArrayList<Contact> data = new ArrayList<Contact>();
public OrdersImageAdapter(Context context, int layoutResourceId,
ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.data = new ArrayList<Contact>();
this.data.addAll(data);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
DecimalFormat df = new DecimalFormat("0.00##");
Contact product = data.get(position);
View row = convertView;
holder = null;
Contact lContact = (Contact) list.getItemAtPosition(position);
Log.e("", "----lcontact values-----"+lContact);
db = new DataBaseHandler(getContext());
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
EditText quantity = (EditText) row.findViewById(R.id.quantity);
// attach the TextWatcher listener to the EditText
// quantity.addTextChangedListener(new MyTextWatcher(row));
int idval=getid.indexOf(lContact);
Log.e("", "----------id value getting-----"+idval);
holder = new ImageHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
holder.dlttxt = (TextView) row.findViewById(R.id.dlt);
holder.quantity = (EditText) row.findViewById(R.id.quantity);
holder.recipeprice = (TextView) row
.findViewById(R.id.recipeprice);
row.setTag(holder);
} else {
holder = (ImageHolder) row.getTag();
}
quantityt = (EditText) row.findViewById(R.id.quantity);
quantityt.setTag(product);
if (product.getQuantity() != 0) {
quantityt.setText(String.valueOf(product.getQuantity()));
} else {
quantityt.setText("");
}
TextView ext = (TextView) row.findViewById(R.id.setprice);
if (product.getQuantity() != 0) {
ext.setText("$" + df.format(product.getExt()));
} else {
ext.setText("");
}
holder.recipeprice
.setText(String.valueOf(lContact.getprice() + "X"));
/* ====DELETING RECIPE ITEMS==== */
holder.dlttxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
setvaluefinal = qtyView.getText().toString();
ordercount = Integer.parseInt(setvaluefinal);
Log.e("", "------yyyyyy-------" + ordercount);
Log.e("---pos---", "----position----" + position);
Contact lContact = (Contact) list
.getItemAtPosition(position);
Log.e("---pos---", "----position----" + lContact);
Log.e("TAG", "" + lContact.getID());
db.deleteContact(lContact.getID());
// db.deleteContact(pos);
Log.e("", "======deleted=====" + lContact.getID());
Log.e("", "====NAME====" + lContact.getName());
quan = lContact.getName();
Log.e("---lcontact price---", "------lcntact price----"
+ lContact.getprice());
adaptercount = lContact.getprice();
Log.e("", "quantity---" + quantityt.getText());
Toast.makeText(getContext(),
lContact.getName() + ":" + "Deleted Sucessfully",
Toast.LENGTH_SHORT).show();
// editcount=adaptercount * ordercount;
Log.e("", "----edit count----" + editcount);
// Log.e("", "----order total value----"+orderTotal);
// recipeamount=orderTotal-editcount;
// Log.e("", "------recipe amount-------"+recipeamount);
imageArry.remove(lContact);
adapter.notifyDataSetChanged();// updating adapter
count = db.getContactsCount();
Log.d("", "----updated count----" + db.getContactsCount());
HelperActivity.num.setText(String.valueOf(count));
// toatalamount.setText(String.valueOf(recipeamount));
// YourOrder.toatalamount.setText();
}
});
holder.quantity.setText("1");
Contact picture = data.get(position);
holder.txtTitle.setText(picture._name);
// convert byte to bitmap take from contact class
byte[] outImage = picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(
outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
// db.deleteContact(null);
return row;
}
public class ImageHolder {
ImageView imgIcon;
TextView txtTitle;
TextView dlttxt;
EditText quantity;
TextView recipeprice;
}
}
I want to do the following.
Pick up three to five contacts out of a special group of contacts or all contacts.
In the list it would be nice to show the contact image.
The selected contacts should have the following information (contact-id, first name, the small version of the contact image to save it as a blob in the database)
I found solutions for the different aspects.
-select multiple contacts:
How to obtain the checked rows in a custom view list
-show contacts from one group
getting contacts from a specified group in android
- photo problem
Getting a Photo from a Contact
But I dont know how to put those together. It would be great if someone could help me putting it together.
Thank you very much!
Frank J.
Solved it, but cant post the answer for some hours.
Solution (not prettyfied yet)
package com.pinkpony.frankj.contactpicker2;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Frank on 28.07.2014.
*/
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> name2 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> img1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadGroups();
//Toast.makeText(MainActivity.this, toString(), Toast.LENGTH_LONG).show();
Log.d("LongValue", toString());
getAllCallLogs(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
//Toast.makeText(getApplicationContext(), checkedcontacts, 1000).show();
Toast.makeText(MainActivity.this, checkedcontacts, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
/* Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
Cursor phones = cr.query(uri, projection, selection, selectionArgs,
sortOrder);
*/
// long groupId = id;
String[] cProjection = { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID };
Cursor groupCursor = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
cProjection,
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "= ?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'",
new String[] { String.valueOf(6) }, null);
if (groupCursor != null && groupCursor.moveToFirst())
{
do
{
int nameCoumnIndex = groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = groupCursor.getString(nameCoumnIndex);
String szFullname=name;
//long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
long contactId = groupCursor.getLong(groupCursor.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID));
// Log.d("your tag", "contact " + name + ":"+String.valueOf(contactId));
name1.add(name);
phno1.add(String.valueOf(contactId));
boolean foundToken = false;
// IDENTIFY Contact based on name and token
String szLookupKey = "";
Uri lkup = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, szFullname);
ContentResolver cr2 = getContentResolver();
Cursor idCursor = getContentResolver().query(lkup, null, null, null, null);
// get all the names
while (idCursor.moveToNext()) {
// get current row/contact ID = ID's are unreliable, so we will go for the lookup key
String szId = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts._ID));
String szName = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
szLookupKey = idCursor.getString(idCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
// for this contact ID, search the custom field
Log.d("", "Searching token:" + szId + " Name:" + szName + " LookupKey:" + szLookupKey);
//Log.d(LOG_TAG, "search: "+lid + " key: "+key + " name: "+name);
}
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?";
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, String.valueOf(contactId) };
Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
Log.d("your tag", "Vorname " + ":" + given);
name2.add(given);
}
nameCur.close();
} while (groupCursor.moveToNext());
groupCursor.close();
}
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
ImageView im1;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void retrieveContactPhoto(Long contactID) {
Bitmap photo = null;
try {
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(photo);
}
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public Bitmap openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri,
new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
// tv1= (TextView) vi.findViewById(R.id.textView2);
im1= (ImageView) vi.findViewById(R.id.imageView1);
Bitmap photo = null;
Long contactID=Long.valueOf(phno1.get(position));
im1.setImageBitmap(openPhoto(contactID));
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(""+ name1.get(position));
// tv1.setText(""+phno1.get(position));//
// retrieveContactPhoto(Long.valueOf(phno1.get(position)));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private class GroupInfo {
String id;
String title;
#Override
public String toString() {
return title+ " ("+id+")";
}
public String getId() {
return id;
}
}
List<GroupInfo> groups = new ArrayList<GroupInfo>();
public void loadGroups() {
final String[] GROUP_PROJECTION = new String[] {
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE,
ContactsContract.Groups.SUMMARY_WITH_PHONES
};
Cursor c = getContentResolver().query(
ContactsContract.Groups.CONTENT_SUMMARY_URI,
GROUP_PROJECTION,
ContactsContract.Groups.DELETED+"!='1' AND "+
ContactsContract.Groups.GROUP_VISIBLE+"!='0' "
,
null,
null);
final int IDX_ID = c.getColumnIndex(ContactsContract.Groups._ID);
final int IDX_TITLE = c.getColumnIndex(ContactsContract.Groups.TITLE);
Map<String,GroupInfo> m = new HashMap<String, GroupInfo>();
while (c.moveToNext()) {
GroupInfo g = new GroupInfo();
g.id = c.getString(IDX_ID);
g.title = c.getString(IDX_TITLE);
int users = c.getInt(c.getColumnIndex(ContactsContract.Groups.SUMMARY_WITH_PHONES));
if (users>0) {
// group with duplicate name?
GroupInfo g2 = m.get(g.title);
if (g2==null) {
m.put(g.title, g);
groups.add(g);
} else {
g2.id+=","+g.id;
}
}
Log.d("LongValue", g.id+g.title);
}
c.close();
}
}
In my Android application, I have a List of Phone Contacts. I want to add these contacts in private list by selection through CheckBoxe and onButtonClick. What I want here is that if contacts are already present there in database then they should not be added. How can i do so ? Please help.
Here is the code :
private MyListAdapter adapter;
ArrayList<String> item_id = new ArrayList<String>();
ArrayList<String> item_contact_name = new ArrayList<String>();
ArrayList<String> filteredList = new ArrayList<String>();
ArrayList<String> item_contact_number = new ArrayList<String>();
Uri queryUri;
boolean flag = false;
boolean[] selection;
static ArrayList<String> selection_val;
private Button btn_select, btn_remove;
DbManager manager;
String[] contactArray;
Cursor Cursor, cursor1;
public static String[] selectedData;
String phoneNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contacts);
manager = new DbManager(this);
try{
queryUri = ContactsContract.Contacts.CONTENT_URI;
//String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
Cursor Cursor = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
showEvents(Cursor);
cursor1 = manager.Return_All_Contacts();
contactArray = showEvents2(cursor1);
//final ViewHolder holder = new ViewHolder();
selection = new boolean[item_id.size()];
selection_val = new ArrayList<String>();
selectedData=new String[selection.length];
adapter = new MyListAdapter(this);
setListAdapter(adapter);
btn_select = (Button) findViewById(R.id.button1);
btn_select.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
// selectedData[i]=item_msg_body.get(i);
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
try{
addContacts(selectedData);
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(
getApplicationContext(),
"Your have Selected " + cnt + " ids. " + " "+ selectIds, Toast.LENGTH_LONG).show();
}
}
});
}
catch(Exception ex)
{
Log.e("Error in retrieving phone", ex.toString());
}
btn_remove = (Button)findViewById(R.id.remove);
btn_remove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
deleteMultiple(selectedData);
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
} else {
}
}
});
}
public class MyListAdapter extends BaseAdapter{
Context con;
private LayoutInflater layoutinf;
ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
ArrayList<String> items_ = new ArrayList<String>();
public MyListAdapter(
privateContacts sample_MultipleSelectionActivity) {
con = sample_MultipleSelectionActivity;
}
public int getCount() {
return item_id.size();
}
public Object getItem(int position) {
return item_id.size();
}
public long getItemId(int position) {
return item_id.get(position).hashCode();
}
public View getView(final int position, View convertView, ViewGroup arg2) {
View v = convertView;
ViewHolder holder = null;
if (v == null) {
layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_add_contacts, null);
holder = new ViewHolder();
holder.chk = (CheckBox) v.findViewById(R.id.checkBox);
holder.tv_contact_name = (TextView) v.findViewById(R.id.tvname);
holder.tv_number = (TextView) v.findViewById(R.id.tvphone);
holder.iv_contact = (ImageView) v.findViewById(R.id.iv_contacts);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.chk.setId(position);
holder.tv_contact_name.setId(position);
holder.chk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
CheckBox cb = (CheckBox) v;
int id = cb.getId();
String val = cb.getText().toString();
if (selection[id]) {
cb.setChecked(false);
selection[id] = false;
selection_val.remove("" + item_contact_name.get(id));
} else {
cb.setChecked(true);
selection[id] = true;
selection_val.add("" + item_contact_name.get(id));
}
adapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("error", "" + e.toString());
}
}
});
holder.chk.setChecked(selection[position]);
if(selection[position] == true)
{
//holder.tv_contact_name.setBackgroundColor(Color.GRAY);
}
else
{
holder.tv_contact_name.setBackgroundColor(Color.TRANSPARENT);
}
// for(int i=0;i<contactArray.length;i++){
//
// holder.tv_contact_name.setBackgroundColor(Color.GREEN);
// }
//holder.chk.setText(item_id.get(position));
holder.tv_contact_name.setText("" + item_contact_name.get(position));
holder.tv_number.setText("" + item_contact_number.get(position));
return v;
}
}
public class ViewHolder {
private CheckBox chk;
private TextView tv_contact_name;
private TextView tv_number;
private ImageView iv_contact;
}
private void addContacts(final String[] selectedItems) {
try{
manager.open();
manager.Insert_phone_contact(selectedItems);
manager.close();
moveToLogActivity();
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
}
private void showEvents(Cursor cursor) {
item_id = new ArrayList<String>(cursor.getCount());
item_contact_name = new ArrayList<String>(cursor.getCount());
item_contact_number = new ArrayList<String>(cursor.getCount());
//String ContactNames[] = new String[cursor.getCount()];
String id[]=new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
item_contact_name.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
item_contact_number.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
i++;
}
}
private String[] showEvents2(Cursor cursor) {
String addedContacts[]=new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
addedContacts[i] = cursor.getString(1);
i++;
}
return addedContacts;
}
#Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
private void moveToLogActivity() {
Intent i = new Intent(this, LogActivity.class);
startActivity(i);
finish();
}
private void deleteMultiple(String[]selectedItems) {
manager.deleteContactsMultiselected(selectedItems);
moveToLogActivity();
}
The database code where i am saving data is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
if (contact[i] !=null){
cv.put(CONTACT_NAME, ""+contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}// insert in db
}
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
ContactTable code in database is as :
// define table name
public static final String TABLE_CONTACTS = "CONTACTS_TABLE";
//define column of TABLE_CONTACTS
public static final String KEY_CONTACTID = "_id";
public static final String CONTACT_NAME = "Contact_name";
I am working on video recording application.I want to list the videos which I would be stored in particular folder.By the following code,I can able to fetch all videos from mobile.But i need to list the videos from particular folder.Can anyone guide me please.Thanks in Advance
public class VideoListActivity extends Activity {
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_list);
init_phone_video_grid();
}
private void init_phone_video_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE };
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.listView1);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
System.gc();
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
String filename = videocursor.getString(video_column_index);
Intent intent = new Intent(VideoListActivity.this, Viewvideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
}
};
public class VideoAdapter extends BaseAdapter {
private Context vContext;
public VideoAdapter(Context c) {
vContext = 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();
TextView tv = new TextView(vContext.getApplicationContext());
String id = null;
if (convertView == null) {
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
id = videocursor.getString(video_column_index);
video_column_index = videocursor
.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videocursor.moveToPosition(position);
id += " Size(KB):" + videocursor.getString(video_column_index);
ImageView iv = new ImageView(vContext);
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, position, MediaStore.Video.Thumbnails.MICRO_KIND, options);
iv.setImageBitmap(curThumb);
tv.setText(id);
} else
tv = (TextView) convertView;
return tv;
}
}
}
Try the following code:
public static ArrayList<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files;
files = parentDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.getName().endsWith(".mp4") ||
file.getName().endsWith(".gif")) {
if (!inFiles.contains(file)) inFiles.add(file);
if (!inFiles.contains(file)) inFiles.add(file);
}
}
}
return inFiles;
}
Use :
private static final String WHATSAPP_STATUSES_LOCATION =
"/storage/emulated/0/yourfoldername";
getListFiles(new File(WHATSAPP_STATUSES_LOCATION));
use this code :
package com.vt.soc;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
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.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity 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;
String filename;
int flag = 0;
protected Context _context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_context = getApplicationContext();
setContentView(R.layout.activity_main);
//set GridView for gallery
_gallery = (GridView) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(_itemClickLis);
flag = 1;
}
private AdapterView.OnItemClickListener _itemClickLis = new OnItemClickListener()
{
#SuppressWarnings({ "deprecation", "unused", "rawtypes" })
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
MEDIA_DATA + " like ? ", // WHERE clause; which rows to return (all rows)
new String[] {"%Movies%"}, // 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);
// And here we get the filename
filename = _cursor.getString(_columnIndex);
//*********** You can do anything when you know the file path :-)
showToast(filename);
Intent i = new Intent(MainActivity.this, Player.class);
i.putExtra("videoPath", filename);
startActivity(i);
//
}
};
#SuppressWarnings("deprecation")
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
MEDIA_DATA + " like ? ", // WHERE clause; which rows to return (all rows)
new String[] {"%Movies%"}, // 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)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
//
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(200, 200));
imgVw.setPadding(8, 8, 8, 8);
}
catch(Exception ex)
{
System.out.println("MainActivity: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;
}
}
}
and add permission to manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
A bit late but posting for future viewers
Uri uri= MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String condition=MediaStore.Video.Media.DATA +" like?";
String[] selectionArguments=new String[]{"%FolderPath%"};
String sortOrder = MediaStore.Video.Media.DATE_TAKEN + " DESC";
String[] projection = { MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,projection, condition, selectionArguments, sortOrder);
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int pathColumn=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if(cursor!=null){
ContentResolver resolver = getApplicationContext().getContentResolver();
while(cursor3.moveToNext()){
String filePath=cursor.getString(pathColumn);
int id = cursor.getInt(idColumn );
Bitmap thumbNail = bitmap=MediaStore.Video.Thumbnails.getThumbnail(resolver, imageID,
MediaStore.Video.Thumbnails.MICRO_KIND, null);
}
}
use this code`
String path = Environment.getExternalStorageDirectory().toString()+"/Your Folder/";`
File f = new File(path);
File file[] = f.listFiles();
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].getName());
}
above code give you all file from the folder ,after you can separate
using it's extension
iam using following code it is not displaying thumb image in gridview but displaying in emulator pls suggest me how to show thumb image in gridview from sdcard
String[] projection = {MediaStore.Images.Media._ID};
final String orderBy = MediaStore.Images.Media._ID+" DESC";
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
orderBy);
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int size = cursor.getCount();
// If size is 0, there are no images on the SD Card.
if (size == 0) {
//No Images available, post some message to the user
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 86, 96, true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
Try this code, it will work
package com.video;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
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.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class StartActivity 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);
_context = getApplicationContext();
setContentView(R.layout.main);
//set GridView for gallery
_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);
// And here we get the filename
String filename = _cursor.getString(_columnIndex);
//*********** You can do anything when you know the file path :-)
showToast(filename);
//
}
};
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)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
//
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;
}
}
}