I am trying to use MediaStore to get all images in phone/tablet. I am succesful with that.
String[] projection = new String[]{
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME
};
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Cursor cur = activity.getContentResolver().query(images,
projection, // Which columns to return
"", // Which rows to return (all rows)
null, // Selection arguments (none)
"" // Ordering
);
if (cur.moveToFirst()) {
String photo;
String album;
int bucketColumn = cur.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int photoColumn = cur.getColumnIndex(MediaStore.Images.Media.DATA);
album = cur.getString(bucketColumn);
photo = cur.getString(photoColumn);
}//Just parts of code
I want to create GridView with images I get from MediaStore.
Problems is when there is a lot of pictures it gets a little problematic. I use Universal Image Loader so its ok but I need it really really fast so I found that Android is supposed to have his own thumbnails of pictures stored in MediaStore.Images.Thumbnail so I will not have to create my own thumbnails.
Get thumbnail Uri/path of the image stored in sd card + android
Doesn't seem to work either. I looked in external database of device and there was nothing.
Have a look at Lucas Rochas smoothie library. This libary implements fast scrolling grids. I use it on my Playlist Manager(google play).
http://lucasr.org/2013/01/06/introducing-smoothie/
Related
I'm fairly new with Android development so I'm just trying some concepts.
For this POC I took the first 20 values from this IMDB list => https://www.imdb.com/chart/toptv/
added them into a JSON which is inside the assets folder of my project.
I have a method in my main activity to access the content of the JSON file, it goes like this:
public void readMovies() {
String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "movies.json");
Log.i("data", jsonFileString);
Gson gson = new Gson();
Type listUserType = new TypeToken<List<Movies>>() { }.getType();
List<Movies> movies = gson.fromJson(jsonFileString, listUserType);
for (int i = 0; i < movies.size(); i++) {
Log.i("data", "> Item " + i + "\n" + movies.get(i));
}
}
Using a textView I'm able to output all the titles (for example) in the layout, but I'd like to be able to display a view similar to the IMDB page, with an image to the left side, title on the centre and any other property on the right side.
How can I achieve a view like the shared URL?
You've to create a Listview with images and text. Attaching some resources.
Checkout the answers to this Stack overflow question
Check out this Youtube tutorial or this one.
These are the ones I found which provide a code walk-through. But now you know the keywords to search for, you can find resources on your own!
right now, I'm avoiding loading system audio for the devices and emulator I have by hardcoding them in SQLite NOT LIKE ... statements while querying the ContentResolver, but, what I have found that the location for the storage of sytem audio(like alarm tones and all the audio factory loaded) doesn't have a standard location in all android device.
So, to avoid loading all system audio, I need a way to fetch the directory where these audio are located, so far, I have gathered a data of these locations where the sytem audio might be:
"/system%",
"/storage/emulated/legacy/Ringtones/%",
"/storage/emulated/0/Ringtones%",
"/product/media/audio%"
but, since these might not be adequate, is there a way to fetch the directory path where the system audio is located in android?
Query audio files with MediaStore , then filter audio files with AudioColumns , and more specific for alarm sounds use IS_ALARM.
As you say :
I have found that the location for the storage of sytem audio doesn't have a standard location in all android device.
MediaStore is a database which holds references of the files and it is a solution to query files in different system storage locations.
You can use something like this:
String[] mProjection =
{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA, # path
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.SIZE
};
Cursor mCursor = getContentResolver().query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,
mProjection,
null,
null);
Note: for external storage use: MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
int index_data = mCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
if (mCursor != null) {
while (mCursor.moveToNext()) {
// Gets the value from the column.
newData = mCursor.getString(index_data);
// Insert code here to process the retrieved data.
// end of while loop
}
} else {
// Insert code here to report an error if the cursor is null or the provider threw an exception.
}
References:
https://developer.android.com/guide/topics/providers/content-provider-basics#java
https://stackoverflow.com/a/64539937/3541319
Code to List all alarms in fragment:
override fun onAttach(context: Context) {
super.onAttach(context)
val projection = arrayOf(
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATE_ADDED
)
val audio: Uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI
val cur = context.contentResolver.query(
audio,
projection, // Which columns to return
"${MediaStore.Audio.Media.IS_ALARM}>0", // Which rows to return (all rows)
null, // Selection arguments (none)
null // Ordering
) ?: return
if (cur.moveToFirst()) {
val displayNameColumn: Int = cur.getColumnIndex(
MediaStore.Audio.Media.DISPLAY_NAME
)
val dateColumn: Int = cur.getColumnIndex(
MediaStore.Audio.Media.DATE_ADDED
)
do {
val displayName = cur.getString(displayNameColumn)
val date = cur.getString(dateColumn)
Log.i(
"Listing Alarms",
" displayName=$displayName , date=$date"
)
} while (cur.moveToNext())
}
You need to add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I would like to limit the amount of contacts displayed in my app. Currently it is querying my Contactscontract.Contacts DB and returning every primary display name that has a phone number. Is there a simple way to reduce this to a numerical amount (say only display 5 contacts), or to certain specified ID's?
This is what I have so far:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = ContactsContract.Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
ContactsContract.Contacts.HAS_PHONE_NUMBER + " =?", // This is selection string, were looking for records that HAS_PHONE_NUMER is 1
new String[]{"1"}, // 1 means that contact has a phone number
ContactsContract.Contacts._COUNT,
new String[] {"5"},
null);
}
Whenever I try to add new parameters in the return section, Android Studio immediately goes red saying cannot resolve constructor. Is this because the CursorLoader is not defined to receive more parameters?
I defined it earlier in my code as:
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
Cheers,
Shyam
To achieve a limitation of query results, please add (string concatenate) a " LIMIT 5" to your query:
...
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=? LIMIT 5" //This is selection string, were looking for records that HAS_PHONE_NUMER is 1 AND
// the result set is limited to 5 rows
new String[]{"1"},
null);
...
As I was working through the following tutorial, I came across this code :
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL = "content://com.example.provider.College/students";
I am interested to see what kind of data this is, so I tried to go to the website http://com.example.provider.College/students to view the data, however it just gave some kind of error. Therefore my question is , is this URL some kind of xml document? what exactly is the format for this data... and how can I view it ?
I would recommend you familiarize yourself with the following documenation:
Content Providers:
http://developer.android.com/guide/topics/providers/content-providers.html
Essentially when you pass that "URL" to the ContentResolver (presumably you're doing somethign like this):
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
You're asking android to resolve that URL to a ContentProvider which is set up to handle that URL. The URL is not "imaginary" so much as it's targets are Local objects and processes which exist and are defined by applications which use the ContentProvider mechanism to store and make data available to other applications.
The goal of that URL (which is converted to a URI in this case) is to specify which ContentProvider you want, and what you want from it.
ContentProviders are generally used by applications that want to manage a database and make that information available to other applications while minimizing access violations etc..
EDIT:
This code is from your tutorial. See added comments:
/// this url points to the content provider.
//The content provider uses it to
///reference a specific database which it has knowledge of
//This URI doesn't represent an
//actual FILE on your system, rather it represents a way for you to tell the content //provider what DATABASE to access and what you want from it.
String URL = "content://com.example.provider.College/students";
// This line converts yoru "URL" into a URI
Uri students = Uri.parse(URL);
/// This call returns a Cursor - a cursor is a object type which contains the results of your QUERY in an order manner. IN this case it is a set of rows, each of which has a number of columns coresponding to your query and database, which can be iterated over to pull information from the DB..
/// managedQuery takes, as an argument, the URI conversion of the URL - this is
// where you are actually calling to the contentprovider, asking it to do a query on the
// databse for some information
Cursor c = managedQuery(students, null, null, null, "name");
// This line moves to the first ROW in the cursor
if (c.moveToFirst()) {
// this does somethign as long as the while loop conditional is true.
do{
// This line creates a pop up toast message with the information stored in the columns of the row you the cursor is currently on.
Toast.makeText(this,
c.getString(c.getColumnIndex(StudentsProvider._ID)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
}
Your question in the comments was:
"all I need is an example of this file: String URL = "content://com.example.provider.College/students"; , what would the data look like ? "
The answer to this is that you have an Sqlite Database on your phone somewhere - generally (and in this case definitely) created by the application and/or content provider you are accessing. You also know that the content resolver accepts this URI and some other information and will return you a CURSOR.
This question addresses what a cursor is.
use of cursor in android
If you read the tutorial fully you will find this code::
public class StudentsProvider extends ContentProvider {
static final String PROVIDER_NAME = "com.example.provider.College";
static final String URL = "content://" + PROVIDER_NAME + "/students";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String _ID = "_id";
static final String NAME = "name";
static final String GRADE = "grade";
You will also find, in the manifest of your tutorial:
<provider android:name="StudentsProvider"
android:authorities="com.example.provider.College">
</provider>
Which is the registration of your ContentProvider for the URI at question.
You will note that your URL and the "PROVIDER_NAME" and "URL" have eerie similarities. This is because the ContentProvider is utilizing these values to identify itself as the resolver for this partiuclar URI to the android system.
You should create the files as described in the tutorial, make the sample app function, and you will be able to start understanding this more clearly.
It's not real, and it's not a web url. That is an example of a hypothetical ContentURI.
As an example, you might consult the UserDictionary like so -
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
You might also create your own.
I'm new here and would be great if someone could help me with this small crisis I have been having. I have been following Jeff Sharkeys Separate List Adapter tutorial which can be found here and I got it all working appropriately to how he explains it.
My problem is I have a database, pre made one which has a table that I am trying to put the extracted data into a list view using Jeffs adapter. I need this data to be put in different sections according to the Category ID column.
The table I am currently extracting data from is the Food table, which has 6 columns, categoriID, menuID, Item, Description, price and a PK _id
My database works properly as in other activities I use a SimpleCursorAdapter to bind data to a list view. (from other tables)
I use the following method in the Database Helper class to retrieve the data I need
public List<FoodModel> getData(String catid, String menuid) {
List<FoodModel> FoodListModel = new ArrayList<FoodModel>();
Cursor cursor = myDataBase.query(FOOD_TABLE, new String [] {FOODITEM_COLUMN, FOODITEMDESCRIPTION_COLUMN,FOODPRICE_COLUMN}, "catid = ? AND menuid = ?",
new String[] { catid, menuid},null, null, null, null);
if (cursor.moveToFirst()){
do{
FoodModel FoodModel = new FoodModel();
FoodModel.setItem(cursor.getString(0));
FoodModel.setdescrription(cursor.getString(1));
FoodModel.setprice(Double.parseDouble(cursor.getString(2)));
FoodListModel.add(FoodModel);} while (cursor.moveToNext());
}
return FoodListModel;
}
the Food Model class is the standard get set class to store the cursors data.
This public method works accordingly as in my main activity (jeffs ListSample.java) I output to the log cat the required information using
Log.d("Reading: ", "Testing Cursor");
List<FoodModel> Data1 = dba.getData("1", "1");
for (FoodModel fd : Data1){
String log = "Item: "+fd.getitem()+" ,Description: " + fd.getdescription() + " ,Price: " + fd.getprice();
Log.d("Name: ", log);
This outputs a list of all the data I need to put into 1 section of the SeperateListAdapter but to the log cat
The 3 things i am trying to output to the list view are the Item, description and price.
My problem is How do I add this data to the list view under the correct section?
as oposed to manually inserting it as Jeff shows
List<Map<String,?>> security = new LinkedList<Map<String,?>>();
security.add(createItem("Remember passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Clear passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Show security warnings", "Show warning if there is a problem with a site's security"));
I didn't want to start my first experience of using this site by pasting all my classes is as this is my first time using this website, my English is not the best and it took me a while to write this I hope it is acceptable as a question, I would be really great full if someone could kindly help me or point me in the right direction.
EDIT: Will gladly post the rest of my code just didnt whant to bombard everyone with loads of information