Whatsapp stickers showing error while adding to whatsapp - android

I am working on whatsapp stickers. I have tried this demo https://github.com/viztushar/stickers-internet .Also with the same data i am able add stickers in demo but not working in my code.
Content provide class :
public class StickerContentProvider extends ContentProvider {
/**
* Do not change the strings listed below, as these are used by WhatsApp. And changing these will break the interface between sticker app and WhatsApp.
*/
public static final String STICKER_PACK_IDENTIFIER_IN_QUERY = "sticker_pack_identifier";
public static final String STICKER_PACK_NAME_IN_QUERY = "sticker_pack_name";
public static final String STICKER_PACK_PUBLISHER_IN_QUERY = "sticker_pack_publisher";
public static final String STICKER_PACK_ICON_IN_QUERY = "sticker_pack_icon";
public static final String ANDROID_APP_DOWNLOAD_LINK_IN_QUERY = "android_play_store_link";
public static final String IOS_APP_DOWNLOAD_LINK_IN_QUERY = "ios_app_download_link";
public static final String PUBLISHER_EMAIL = "sticker_pack_publisher_email";
public static final String PUBLISHER_WEBSITE = "sticker_pack_publisher_website";
public static final String PRIVACY_POLICY_WEBSITE = "sticker_pack_privacy_policy_website";
public static final String LICENSE_AGREENMENT_WEBSITE = "sticker_pack_license_agreement_website";
public static final String STICKER_FILE_NAME_IN_QUERY = "sticker_file_name";
public static final String STICKER_FILE_EMOJI_IN_QUERY = "sticker_emoji";
public static final String CONTENT_FILE_NAME = "contents.json";
public static final String CONTENT_SCHEME = "content";
private static final String TAG = StickerContentProvider.class.getSimpleName();
public static Uri AUTHORITY_URI = new Uri.Builder().scheme(StickerContentProvider.CONTENT_SCHEME).authority(BuildConfig.CONTENT_PROVIDER_AUTHORITY).appendPath(StickerContentProvider.METADATA).build();
/**
* Do not change the values in the UriMatcher because otherwise, WhatsApp will not be able to fetch the stickers from the ContentProvider.
*/
private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
static final String METADATA = "metadata";
private static final int METADATA_CODE = 1;
private static final int METADATA_CODE_FOR_SINGLE_PACK = 2;
static final String STICKERS = "stickers";
private static final int STICKERS_CODE = 3;
static final String STICKERS_ASSET = "stickers_asset";
private static final int STICKERS_ASSET_CODE = 4;
private static final int STICKER_PACK_TRAY_ICON_CODE = 5;
private List<StickerPack> stickerPackList = new ArrayList<>();
#Override
public boolean onCreate() {
Hawk.init(getContext()).build();
final String authority = BuildConfig.CONTENT_PROVIDER_AUTHORITY;
if (!authority.startsWith(Objects.requireNonNull(getContext()).getPackageName())) {
throw new IllegalStateException("your authority (" + authority + ") for the content provider should start with your package name: " + getContext().getPackageName());
}
//the call to get the metadata for the sticker packs.
MATCHER.addURI(authority, METADATA, METADATA_CODE);
//the call to get the metadata for single sticker pack. * represent the identifier
MATCHER.addURI(authority, METADATA + "/*", METADATA_CODE_FOR_SINGLE_PACK);
//gets the list of stickers for a sticker pack, * respresent the identifier.
MATCHER.addURI(authority, STICKERS + "/*", STICKERS_CODE);
for (StickerPack stickerPack : getStickerPackList()) {
Log.e(TAG, "onCreate: " + stickerPack.identifier);
MATCHER.addURI(authority, STICKERS_ASSET + "/" + stickerPack.identifier + "/" + stickerPack.tray_image_file, STICKER_PACK_TRAY_ICON_CODE);
if (stickerPack.getStickers() != null) {
for (Sticker sticker : stickerPack.getStickers()) {
MATCHER.addURI(authority, STICKERS_ASSET + "/" + stickerPack.identifier + "/" + sticker.image_file, STICKERS_ASSET_CODE);
}
}
}
return true;
}
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final int code = MATCHER.match(uri);
Log.d(TAG, "query: " + code + uri);
if (code == METADATA_CODE) {
return getPackForAllStickerPacks(uri);
} else if (code == METADATA_CODE_FOR_SINGLE_PACK) {
return getCursorForSingleStickerPack(uri);
} else if (code == STICKERS_CODE) {
return getStickersForAStickerPack(uri);
} else {
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
#Nullable
#Override
public AssetFileDescriptor openAssetFile(#NonNull Uri uri, #NonNull String mode) throws FileNotFoundException {
MATCHER.match(uri);
final int matchCode = MATCHER.match(uri);
final List<String> pathSegments = uri.getPathSegments();
Log.d(TAG, "openFile: " + matchCode + uri + "\n" + uri.getAuthority()
+ "\n" + pathSegments.get(pathSegments.size() - 3) + "/"
+ "\n" + pathSegments.get(pathSegments.size() - 2) + "/"
+ "\n" + pathSegments.get(pathSegments.size() - 1));
return getImageAsset(uri);
}
private AssetFileDescriptor getImageAsset(Uri uri) throws IllegalArgumentException {
AssetManager am = Objects.requireNonNull(getContext()).getAssets();
final List<String> pathSegments = uri.getPathSegments();
if (pathSegments.size() != 3) {
throw new IllegalArgumentException("path segments should be 3, uri is: " + uri);
}
String fileName = pathSegments.get(pathSegments.size() - 1);
final String identifier = pathSegments.get(pathSegments.size() - 2);
if (TextUtils.isEmpty(identifier)) {
throw new IllegalArgumentException("identifier is empty, uri: " + uri);
}
if (TextUtils.isEmpty(fileName)) {
throw new IllegalArgumentException("file name is empty, uri: " + uri);
}
//making sure the file that is trying to be fetched is in the list of stickers.
for (StickerPack stickerPack : getStickerPackList()) {
if (identifier.equals(stickerPack.identifier)) {
if (fileName.equals(stickerPack.tray_image_file)) {
return fetchFile(uri, am, fileName, identifier);
} else {
for (Sticker sticker : stickerPack.getStickers()) {
if (fileName.equals(sticker.image_file)) {
return fetchFile(uri, am, fileName, identifier);
}
}
}
}
}
return null;
}
private AssetFileDescriptor fetchFile(#NonNull Uri uri, #NonNull AssetManager am, #NonNull String fileName, #NonNull String identifier) {
try {
File file;
if(fileName.endsWith(".png")){
file = new File(getContext().getFilesDir()+ "/" + "stickers_asset" + "/" + identifier + "/try/", fileName);
} else {
file = new File(getContext().getFilesDir()+ "/" + "stickers_asset" + "/" + identifier + "/", fileName);
}
if (!file.exists()) {
Log.d("fetFile", "StickerPack dir not found");
}
Log.d("fetchFile", "StickerPack " + file.getPath());
return new AssetFileDescriptor(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY), 0L, -1L);
} catch (IOException e) {
Log.e(Objects.requireNonNull(getContext()).getPackageName(), "IOException when getting asset file, uri:" + uri, e);
return null;
}
}
#Override
public String getType(#NonNull Uri uri) {
final int matchCode = MATCHER.match(uri);
switch (matchCode) {
case METADATA_CODE:
return "vnd.android.cursor.dir/vnd." + BuildConfig.CONTENT_PROVIDER_AUTHORITY + "." + METADATA;
case METADATA_CODE_FOR_SINGLE_PACK:
return "vnd.android.cursor.item/vnd." + BuildConfig.CONTENT_PROVIDER_AUTHORITY + "." + METADATA;
case STICKERS_CODE:
return "vnd.android.cursor.dir/vnd." + BuildConfig.CONTENT_PROVIDER_AUTHORITY + "." + STICKERS;
case STICKERS_ASSET_CODE:
return "image/webp";
case STICKER_PACK_TRAY_ICON_CODE:
return "image/png";
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
private synchronized void readContentFile(#NonNull Context context) {
if (Hawk.get("sticker_pack", new ArrayList<StickerPack>()) != null) {
stickerPackList.addAll(Hawk.get("sticker_pack", new ArrayList<StickerPack>()));
}
}
public List<StickerPack> getStickerPackList() {
/* if (stickerPackList == null) {
readContentFile(Objects.requireNonNull(getContext()));
}*/
return (List)Hawk.get("sticker_packs",new ArrayList<StickerPack>());
}
private Cursor getPackForAllStickerPacks(#NonNull Uri uri) {
return getStickerPackInfo(uri, getStickerPackList());
}
private Cursor getCursorForSingleStickerPack(#NonNull Uri uri) {
final String identifier = uri.getLastPathSegment();
for (StickerPack stickerPack : getStickerPackList()) {
if (identifier.equals(stickerPack.identifier)) {
return getStickerPackInfo(uri, Collections.singletonList(stickerPack));
}
}
return getStickerPackInfo(uri, new ArrayList<StickerPack>());
}
#NonNull
private Cursor getStickerPackInfo(#NonNull Uri uri, #NonNull List<StickerPack> stickerPackList) {
MatrixCursor cursor = new MatrixCursor(
new String[]{
STICKER_PACK_IDENTIFIER_IN_QUERY,
STICKER_PACK_NAME_IN_QUERY,
STICKER_PACK_PUBLISHER_IN_QUERY,
STICKER_PACK_ICON_IN_QUERY,
ANDROID_APP_DOWNLOAD_LINK_IN_QUERY,
IOS_APP_DOWNLOAD_LINK_IN_QUERY,
PUBLISHER_EMAIL,
PUBLISHER_WEBSITE,
PRIVACY_POLICY_WEBSITE,
LICENSE_AGREENMENT_WEBSITE
});
for (StickerPack stickerPack : stickerPackList) {
MatrixCursor.RowBuilder builder = cursor.newRow();
builder.add(stickerPack.identifier);
builder.add(stickerPack.name);
builder.add(stickerPack.publisher);
builder.add(stickerPack.tray_image_file);
builder.add(stickerPack.androidPlayStoreLink);
builder.add(stickerPack.iosAppStoreLink);
builder.add(stickerPack.publisher_email);
builder.add(stickerPack.publisher_website);
builder.add(stickerPack.privacy_policy_website);
builder.add(stickerPack.license_agreement_website);
}
Log.d(TAG, "getStickerPackInfo: " + stickerPackList.size());
cursor.setNotificationUri(Objects.requireNonNull(getContext()).getContentResolver(), uri);
return cursor;
}
#NonNull
private Cursor getStickersForAStickerPack(#NonNull Uri uri) {
final String identifier = uri.getLastPathSegment();
MatrixCursor cursor = new MatrixCursor(new String[]{STICKER_FILE_NAME_IN_QUERY, STICKER_FILE_EMOJI_IN_QUERY});
for (StickerPack stickerPack : getStickerPackList()) {
if (identifier.equals(stickerPack.identifier)) {
for (Sticker sticker : stickerPack.getStickers()) {
cursor.addRow(new Object[]{sticker.image_file, TextUtils.join(",", sticker.emojis)});
}
}
}
cursor.setNotificationUri(Objects.requireNonNull(getContext()).getContentResolver(), uri);
return cursor;
}
#Override
public int delete(#NonNull Uri uri, #Nullable String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("Not supported");
}
#Override
public Uri insert(#NonNull Uri uri, ContentValues values) {
throw new UnsupportedOperationException("Not supported");
}
#Override
public int update(#NonNull Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
throw new UnsupportedOperationException("Not supported");
}
}
Please let me know if any other code require.
Error trace :
IOException when getting asset file, uri:content://com.mercatus.shoppers.stag.provider.StickerContentProvider/stickers_asset/1/69DEA9206D7A4EDF8D8E6439B41BBBB4.ashx
java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
at android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:313)
at android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:211)
at com.mall.provider.StickerContentProvider.fetchFile(StickerContentProvider.java:187)
at com.mall.provider.StickerContentProvider.getImageAsset(StickerContentProvider.java:162)
at com.mall.provider.StickerContentProvider.openAssetFile(StickerContentProvider.java:140)
at android.content.ContentProvider.openTypedAssetFile(ContentProvider.java:1746)
at android.content.ContentProvider.openTypedAssetFile(ContentProvider.java:1812)
at android.content.ContentProvider$Transport.openTypedAssetFile(ContentProvider.java:425)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:302)
at android.os.Binder.execTransact(Binder.java:739)
Error :
File location :

Related

How to update insert delete to Contentprovider with nosql

I am not using sql db. a single key contains all my data as list of object.
(key:list)
How would I remove or insert or update the files and object holding paths of those files and also effect on content provider so that third party apps should know the changes and also dir, key-value storage and content provider all should synced .
Hawk storage storing the list of all Objects so I cannot access any specific object directly. For adding new object I have to store all objects in a list and add new object to list then put the list into Hawk with same key so it will replace the exisitng list.
I am using a key-value pair storage called Hawk which holds list of objects.
Objects has paths of stored files
files are stored in app specific storagei.e. CacheDir.
Content provider adds uri each time I create new Object
ContentProvider:
#Override
public boolean onCreate() {
Hawk.init(getContext()).build();
final String authority = RNWhatsAppStickersModule.getContentProviderAuthority(getContext());
if (!authority.startsWith(Objects.requireNonNull(getContext()).getPackageName())) {
throw new IllegalStateException("your authority (" + authority + ") for the content provider should start with your package name: " + getContext().getPackageName());
}
Log.d("ReactNative","authority "+authority);
//the call to get the metadata for the sticker packs.
MATCHER.addURI(authority, METADATA, METADATA_CODE);
//the call to get the metadata for single sticker pack. * represent the identifier
MATCHER.addURI(authority, METADATA + "/*", METADATA_CODE_FOR_SINGLE_PACK);
//gets the list of stickers for a sticker pack, * respresent the identifier.
MATCHER.addURI(authority, STICKERS + "/*", STICKERS_CODE);
for (StickerPack stickerPack : getStickerPackList()) {
MATCHER.addURI(authority, STICKERS_ASSET + "/" + stickerPack.identifier + "/" + stickerPack.trayImageFile, STICKER_PACK_TRAY_ICON_CODE);
for (Sticker sticker : stickerPack.getStickers()) {
MATCHER.addURI(authority, STICKERS_ASSET + "/" + stickerPack.identifier + "/" + sticker.imageFileName, STICKERS_ASSET_CODE);
}
}
return true;
}
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
final int code = MATCHER.match(uri);
if (code == METADATA_CODE) {
Log.d("ReactNative","METADATA_CODE "+String.valueOf(code));
return getPackForAllStickerPacks(uri);
} else if (code == METADATA_CODE_FOR_SINGLE_PACK) {
Log.d("ReactNative","METADATA_CODE_FOR_SINGLE_PACK "+String.valueOf(code));
return getCursorForSingleStickerPack(uri);
} else if (code == STICKERS_CODE) {
Log.d("ReactNative","STICKERS_CODE "+String.valueOf(code));
return getStickersForAStickerPack(uri);
} else {
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
#Nullable
#Override
public AssetFileDescriptor openAssetFile(#NonNull Uri uri, #NonNull String mode) {
final int matchCode = MATCHER.match(uri);
// if (matchCode == STICKERS_ASSET_CODE || matchCode == STICKER_PACK_TRAY_ICON_CODE) {
return getImageAsset(uri);
// return null;
}
#Override
public String getType(#NonNull Uri uri) {
final int matchCode = MATCHER.match(uri);
switch (matchCode) {
case METADATA_CODE:
return "vnd.android.cursor.dir/vnd." + RNWhatsAppStickersModule.getContentProviderAuthority(getContext()) + "." + METADATA;
case METADATA_CODE_FOR_SINGLE_PACK:
return "vnd.android.cursor.item/vnd." + RNWhatsAppStickersModule.getContentProviderAuthority(getContext()) + "." + METADATA;
case STICKERS_CODE:
return "vnd.android.cursor.dir/vnd." + RNWhatsAppStickersModule.getContentProviderAuthority(getContext()) + "." + STICKERS;
case STICKERS_ASSET_CODE:
return "image/webp";
case STICKER_PACK_TRAY_ICON_CODE:
return "image/png";
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
private synchronized void readContentFile(#NonNull Context context) {
// try (InputStream contentsInputStream = context.getAssets().open(CONTENT_FILE_NAME)) {
// stickerPackList = ContentFileParser.parseStickerPacks(contentsInputStream);
// } catch (IOException | IllegalStateException e) {
// throw new RuntimeException(CONTENT_FILE_NAME + " file has some issues: " + e.getMessage(), e);
// }
Log.d("ReactNative","readContentFile ");
if (Hawk.get("sticker_packs", new ArrayList<StickerPack>()) != null) {
stickerPackList.addAll(Hawk.get("sticker_packs", new ArrayList<StickerPack>()));
}
}
public List<StickerPack> getStickerPackList() {
// if (stickerPackList == null) {
// readContentFile(Objects.requireNonNull(getContext()));
// }
// return stickerPackList;
/*
* if (stickerPackList == null) {
* readContentFile(Objects.requireNonNull(getContext())); }
*/
Log.d("ReactNative","getStickerPackList ");
return (List) Hawk.get("sticker_packs", new ArrayList<StickerPack>());
}
private Cursor getPackForAllStickerPacks(#NonNull Uri uri) {
return getStickerPackInfo(uri, getStickerPackList());
}
private Cursor getCursorForSingleStickerPack(#NonNull Uri uri) {
final String identifier = uri.getLastPathSegment();
for (StickerPack stickerPack : getStickerPackList()) {
if (identifier.equals(stickerPack.identifier)) {
return getStickerPackInfo(uri, Collections.singletonList(stickerPack));
}
}
return getStickerPackInfo(uri, new ArrayList<StickerPack>());
}
#NonNull
private Cursor getStickerPackInfo(#NonNull Uri uri, #NonNull List<StickerPack> stickerPackList) {
MatrixCursor cursor = new MatrixCursor(
new String[]{
STICKER_PACK_IDENTIFIER_IN_QUERY,
STICKER_PACK_NAME_IN_QUERY,
STICKER_PACK_PUBLISHER_IN_QUERY,
STICKER_PACK_ICON_IN_QUERY,
ANDROID_APP_DOWNLOAD_LINK_IN_QUERY,
IOS_APP_DOWNLOAD_LINK_IN_QUERY,
PUBLISHER_EMAIL,
PUBLISHER_WEBSITE,
PRIVACY_POLICY_WEBSITE,
LICENSE_AGREENMENT_WEBSITE,
IMAGE_DATA_VERSION, // #3373
AVOID_CACHE, // #3373
ANIMATED_STICKER_PACK, // #3373
});
int i = 1;
for (StickerPack stickerPack : stickerPackList) {
Log.d("ReactNative","builder.add "+String.valueOf(i));
i++;
MatrixCursor.RowBuilder builder = cursor.newRow();
builder.add(stickerPack.identifier);
builder.add(stickerPack.name);
builder.add(stickerPack.publisher);
builder.add(stickerPack.trayImageFile);
builder.add(stickerPack.androidPlayStoreLink);
builder.add(stickerPack.iosAppStoreLink);
builder.add(stickerPack.publisherEmail);
builder.add(stickerPack.publisherWebsite);
builder.add(stickerPack.privacyPolicyWebsite);
builder.add(stickerPack.licenseAgreementWebsite);
builder.add(stickerPack.imageDataVersion); // #373
builder.add(stickerPack.avoidCache ? 1 : 0); // #373
builder.add(stickerPack.animatedStickerPack ? 1 : 0); // #373
}
cursor.setNotificationUri(Objects.requireNonNull(getContext()).getContentResolver(), uri);
return cursor;
}
#NonNull
private Cursor getStickersForAStickerPack(#NonNull Uri uri) {
final String identifier = uri.getLastPathSegment();
MatrixCursor cursor = new MatrixCursor(new String[]{STICKER_FILE_NAME_IN_QUERY, STICKER_FILE_EMOJI_IN_QUERY});
for (StickerPack stickerPack : getStickerPackList()) {
if (identifier.equals(stickerPack.identifier)) {
for (Sticker sticker : stickerPack.getStickers()) {
cursor.addRow(new Object[]{sticker.imageFileName, TextUtils.join(",", sticker.emojis)});
}
}
}
cursor.setNotificationUri(Objects.requireNonNull(getContext()).getContentResolver(), uri);
return cursor;
}
private AssetFileDescriptor getImageAsset(Uri uri) throws IllegalArgumentException {
Log.d("ReactNative","getImageAsset "+uri.toString());
AssetManager am = Objects.requireNonNull(getContext()).getAssets();
final List<String> pathSegments = uri.getPathSegments();
if (pathSegments.size() != 3) {
throw new IllegalArgumentException("path segments should be 3, uri is: " + uri);
}
String fileName = pathSegments.get(pathSegments.size() - 1);
final String identifier = pathSegments.get(pathSegments.size() - 2);
if (TextUtils.isEmpty(identifier)) {
throw new IllegalArgumentException("identifier is empty, uri: " + uri);
}
if (TextUtils.isEmpty(fileName)) {
throw new IllegalArgumentException("file name is empty, uri: " + uri);
}
//making sure the file that is trying to be fetched is in the list of stickers.
for (StickerPack stickerPack : getStickerPackList()) {
android.util.Log.d("ReactNative","stickerPack.identifier "+stickerPack.identifier);
if (identifier.equals(stickerPack.identifier)) {
if (fileName.equals(stickerPack.trayImageFile)) {
return fetchFile(uri, am, fileName, identifier, true);
} else {
for (Sticker sticker : stickerPack.getStickers()) {
if (fileName.equals(sticker.imageFileName)) {
return fetchFile(uri, am, fileName, identifier, false);
}
}
}
}
}
return null;
}
private AssetFileDescriptor fetchFile(#NonNull Uri uri, #NonNull AssetManager am, #NonNull String fileName, #NonNull String identifier, Boolean isTrayFile) {
Log.d("ReactNative","fetchFile "+fileName);
try {
File file;
file = new File(getContext().getFilesDir() + "/" + "stickers_asset" + "/" + identifier + "/", fileName);
if (!file.exists()) {
Log.d("ReactNative", "StickerPack dir not found");
// Log.d("fetFile", "StickerPack dir not found");
}
return new AssetFileDescriptor(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY), 0L, -1L);
} catch (IOException e) {
Log.e(Objects.requireNonNull(getContext()).getPackageName(),
"IOException when getting asset file, uri:" + uri, e);
Log.d("ReactNative","IOException when getting asset file, uri:" + uri);
try {
return am.openFd("1" + "/" + "namaskar.webp");
} catch (IOException err) {
Log.e(Objects.requireNonNull(getContext()).getPackageName(), "IOException when getting asset file, uri:" + uri, err);
return null;
}
}
}
#Override
public int delete(#NonNull Uri uri, #Nullable String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("Not supported");
}
#Override
public Uri insert(#NonNull Uri uri, ContentValues values) {
throw new UnsupportedOperationException("Not supported");
}
#Override
public int update(#NonNull Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
throw new UnsupportedOperationException("Not supported");
}
Adding new object to Hawk Storage:
...
// first extract all stored objects by Hawk.get("sticker_packs")
List<StickerPack> temp = Hawk.get("sticker_packs");
temp.add(newStickerPack);
Hawk.put("sticker_packs", temp);
// I am new to content provider . I understood how to do CRUD with content provider +sqlite. But here only uri are being added
...
I want to update the content provider and also want to make sure that Hawk storage and physical files should be updated as well. I am worried that if I change content uri then It wont hawk storage and real files path will be different.

How to retrieve multiple audio files from android internal/External storage to a listview in another activity?

I am new to android programming and i am trying to get my hands dirty by building an app. I am try to retrieve multiple audio files(mp3) from internal or external storage and displaying each song in a listview in another activity. Then from there i want to be able to manipulate each song in the list. I am not interested in playing the song immediately. I am only able the get only one song title in another activity. I am confused right now and i dont know what to do or how to go about it. Any help or pointers would be very appreciated.
Here is my work so far. Its very basic.
public class MainActivity extends AppCompatActivity {
private static final int READ_REQUEST_CODE = 42;
private static final String TAG = "DATA";
Button btnOpenFileExplorer, btnViewTones, btnExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOpenFileExplorer = findViewById(R.id.btnOpenFileExplorer);
btnViewTones = findViewById(R.id.btnViewSongs);
btnExit = findViewById(R.id.btnExit);
btnOpenFileExplorer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("audio/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i(TAG, "Display Name: " + displayName);
Intent intent = new Intent(MainActivity.this, SongListActivity.class);
intent.putExtra("Song", displayName);
startActivity(intent);
Toast.makeText(this, "Display Name: " + displayName, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
cursor.close();
}
}
}
}
}
I used this code retrieving songs from a custom location
by use this code Context.getContentResolver().query(uri, null, selection, filter, sortOrder)
/**
* Read the songs present in external storage
*
* #param context
* #return
* selection == "your audio selection criteria"
* filter= "your custom audio location (internal/external) "
* sortOrder="your audio list order "
*/
public static ArrayList<MediaItem> listOfSongs(Context context) {
// File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + .......path.... + "/");
// if (!file.exists()) {
//file.mkdir();
// }
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String loc = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "......" + "/";
// Filter only mp3s, only those marked by the MediaStore to be music and longer than 1 minute
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
+ " AND " + MediaStore.Audio.Media.DATA + " LIKE ? AND " +
MediaStore.Audio.Media.DATA + " NOT LIKE ?";
// + " AND " + MediaStore.Audio.Media.MIME_TYPE + "= 'audio/mpeg'";
// + " AND " + MediaStore.Audio.Media.DURATION + " > 60000";
String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
String test = MediaStore.Audio.Media.DATA + " LIKE ? AND " +
MediaStore.Audio.Media.DATA + " NOT LIKE ?";
// String[] test1 = new String[]{loc + "%", loc + "%/%"};
String[] filter = new String[]{loc + "%", loc + "%/%"};
Log.d(TAG, "Songs: loc " + loc);
Cursor c = context.getContentResolver().query(uri, null, selection, filter, sortOrder);
ArrayList<MediaItem> listOfSongs = new ArrayList<MediaItem>();
try {
// c.moveToFirst();
while (c.moveToNext()) {
MediaItem songData = new MediaItem();
String title = c.getString(c.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = c.getString(c.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String album = c.getString(c.getColumnIndex(MediaStore.Audio.Media.ALBUM));
long duration = c.getLong(c.getColumnIndex(MediaStore.Audio.Media.DURATION));
String data = c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA));
long albumId = c.getLong(c.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
String composer = c.getString(c.getColumnIndex(MediaStore.Audio.Media.COMPOSER));
songData.setTitle(title);
songData.setAlbum(album);
songData.setArtist(artist);
songData.setDuration(duration);
songData.setPath(data);
songData.setAlbumId(albumId);
songData.setComposer(composer);
listOfSongs.add(songData);
}
c.close();
} catch (Exception e) {
Log.d(TAG, "listOfSongs() " + e.getMessage());
}
Log.d(TAG, "listOfSongs: size :" + listOfSongs.size());
return listOfSongs;
}
MediaItem.java
public class MediaItem {
String title;
String artist;
String album;
String path;
long duration;
long albumId;
String composer;
#Override
public String toString() {
return title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public long getAlbumId() {
return albumId;
}
public void setAlbumId(long albumId) {
this.albumId = albumId;
}
public String getComposer() {
return composer;
}
public void setComposer(String composer) {
this.composer = composer;
}
}

How to make MultipartBbody.Part request from cache image using retrofit

My image is cached at located:
file:///data/user/0/com.example.muhammadusman.project/cache/cropped1340954678061130725.jpg
how can i make the Multipart.body request for this interface:
#Multipart
#POST("/image/{name}")
Call<Recognition> recognizeImage(
#Path("name")String name,
#Part MultipartBody.Part image);
Input to the Function
key="40"
imageName="cropped1340954678061130725.jpg"
path="file:///data/user/0/com.example.muhammadusman.project/cache/cropped1340954678061130725.jpg"
This is My Code: i am using this code to make the MultipartBody.Part object. But i am not able to make the object. Always program crash.
public static MultipartBody.Part creatPartFromPath(String key,String imageName,String path){
File file=new File(path);
String mediaType= getMimeType(path);
RequestBody intermediateFile=RequestBody.create(MediaType.parse(mediaType),file);
return MultipartBody.Part.createFormData(key,imageName,intermediateFile);
}
public static String getMimeType(String url) {
return url.substring(url.lastIndexOf(".") + 1);
}
Github link for source code:
https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
Use this code:
i have test this code this works fine. The link contain the whole source code. But i customize the file for you this will work fine for you.
Problem Solution:
String path=FileUtils1.getPath(getContext(),titleImageUri);
now you path will be
path="/data/user/0/com.example.muhammadusman.project/cache/cropped8174258068738559892.jpg"
replace your previous path with this new path.
public class FileUtils1 {
private FileUtils1() {} //private constructor to enforce Singleton pattern
/** TAG for log messages. */
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
public static final String MIME_TYPE_AUDIO = "audio/*";
public static final String MIME_TYPE_TEXT = "text/*";
public static final String MIME_TYPE_IMAGE = "image/*";
public static final String MIME_TYPE_VIDEO = "video/*";
public static final String MIME_TYPE_APP = "application/*";
public static final String HIDDEN_PREFIX = ".";
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
public static boolean isLocal(String url) {
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
return true;
}
return false;
}
public static String getPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// LocalStorageProvider
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}

How to specify which table in a content provider to insert into

I have the content provider below. It's the inteface to my database which has several tables, message, phone, transaction etc.
I can retrieve data ok using the query method and a cursor loader. I do this when displaying data in a listview.
I understand that if i want to insert data, i must use a contentResolver. Something like the following.
getContentResolver().insert(URI, values);
.
How can i insert into the message table for example?
I can see there is a uriMatching mechanism within the content provider, but how do i specify a specific table when using the content provider to perform an insert. How can i specify this in the contentResolver?
would i have to perform a switch like i do in the query method?
Thanks in advance
Matt.
public class RR3ContentProvider extends ContentProvider {
private static final String TAG = RR3ContentProvider.class.getSimpleName();
NfcScannerApplication nfcAppObj;
static final String PROVIDER_NAME = "com.carefreegroup.rr3.ContentProvider";
static final String URLPHONENUMBERS = "content://" + PROVIDER_NAME + "/phonenumbers";
static final Uri CONTENT_URI_PHONE_NUMBERS = Uri.parse(URLPHONENUMBERS);
static final String _ID_PHONENUMBERS = "_id";
static final String PHONE_NAME = "phonename";
static final String PHONE_NUMBER = "phonenumber";
static final String TABLEPHONE = "phone";
private static HashMap<String, String> PHONE_PROJECTION_MAP;
static final int PHONES = 1;
static final int PHONE_ID = 2;
static final String URLMESSAGES = "content://" + PROVIDER_NAME + "/messages";
static final Uri CONTENT_URI_MESSAGES = Uri.parse(URLMESSAGES);
static final String _ID_MESSAGES = "_id";
static final String MESSAGE_CREATED_AT = "messagecreatedat";
static final String MESSAGE_TEXT = "messagetext";
static final String MESSAGE_SENDER = "messagesender";
static final String TABLEMESSAGE = "message";
private static HashMap<String, String> MESSAGE_PROJECTION_MAP;
static final int MESSAGES = 3;
static final int MESSAGE_ID = 4;
public static final String C_ID = BaseColumns._ID; // special for id
// internally in system
static final String URLTRANSACTIONS = "content://" + PROVIDER_NAME + "/transactions";
static final Uri CONTENT_URI_TRANSACTIONS = Uri.parse(URLTRANSACTIONS);
static final String _ID_TRANSACTIONS = "_id";
static final String TRANSACTIONS_TYPE = "type";
static final String TRANSACTIONS_COMPANY_ID = "companyid";
static final String TRANSACTIONS_PERSON_ID = "person";
static final String TRANSACTIONS_NAME = "name";
static final String TRANSACTIONS_TAG_ID = "tagid";
static final String TRANSACTIONS_STATUS = "status";
static final String TRANSACTIONS_TAG_SCAN_TIME = "tagscantime";
static final String TRANSACTIONS_TAG_SENTSERVER_TIME = "tagsentservertime";
static final String TRANSACTIONS_TRANSACTIONS_LATITUDE = "transactionslatitude";
static final String TRANSACTIONS_TRANSACTIONS_LONGITUDE = "transactionslongitude";
static final String TRANSACTIONS_DRIVER = "driver";
static final String TABLETRANSACTIONS = "transactions";
private static HashMap<String, String> TRANSACTIONS_PROJECTION_MAP;
static final int TRANSACTIONS = 5;
static final int TRANSACTION_ID = 6;
static final String URLLOG = "content://" + PROVIDER_NAME + "/log";
static final Uri CONTENT_URI_LOG = Uri.parse(URLLOG);
static final String _ID_Log = "_id";
static final String LOG_CALLID = "logcallid";
static final String LOG_MESSAGE = "logmessage";
static final String LOG_CREATED_TIME = "logcreatedtime";
static final String LOG_CLIENTID = "logclientid";
static final String LOG_CARERID = "logcarerid";
static final String LOG_SERVER_TIME = "logservertime";
static final String TABLELOG = "log";
private static HashMap<String, String> LOG_PROJECTION_MAP;
static final int LOG = 7;
static final int LOG_ID = 8;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "phonenumbers", PHONES);
uriMatcher.addURI(PROVIDER_NAME, "phonenumbers/#", PHONE_ID);
uriMatcher.addURI(PROVIDER_NAME, "messages", MESSAGES);
uriMatcher.addURI(PROVIDER_NAME, "messages/#", MESSAGE_ID);
uriMatcher.addURI(PROVIDER_NAME, "transactions", TRANSACTIONS);
uriMatcher.addURI(PROVIDER_NAME, "transactions/#", TRANSACTION_ID);
uriMatcher.addURI(PROVIDER_NAME, "log", LOG);
uriMatcher.addURI(PROVIDER_NAME, "log/#", LOG_ID);
}
/**
* Database specific constant declarations
*/
private SQLiteDatabase db;
#Override
public boolean onCreate() {
Context context = getContext();
nfcAppObj = (NfcScannerApplication) getContext();
Log.e(TAG, "inside RR3ContentProvider onCreate");
return (nfcAppObj == null)? false:true;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
db = nfcAppObj.getDb();
long rowID = db.insert( TABLEPHONE, "", values);
/**
* If record is added successfully
*/
if (rowID > 0)
{
Uri _uri = ContentUris.withAppendedId(CONTENT_URI_PHONE_NUMBERS, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Failed to add a record into " + uri);
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Log.e(TAG, "inside RR3ContentProvider query method");
db = nfcAppObj.getDb();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch (uriMatcher.match(uri)) {
case PHONES:
Log.e(TAG, "CASE PHONES");
qb.setTables(TABLEPHONE);
qb.setProjectionMap(PHONE_PROJECTION_MAP);
if (sortOrder == null || sortOrder == ""){
sortOrder = PHONE_NAME;
}
break;
case PHONE_ID:
Log.e(TAG, "CASE PHONE_ID");
qb.setTables(TABLEPHONE);
qb.appendWhere( _ID_PHONENUMBERS + "=" + uri.getPathSegments().get(1));
if (sortOrder == null || sortOrder == ""){
sortOrder = PHONE_NAME;
}
break;
case MESSAGES:
Log.e(TAG, "CASE MESSAGES");
qb.setTables(TABLEMESSAGE);
qb.setProjectionMap(MESSAGE_PROJECTION_MAP);
if (sortOrder == null || sortOrder == ""){
sortOrder = MESSAGE_CREATED_AT + " DESC";
}
break;
case MESSAGE_ID:
Log.e(TAG, "CASE MESAAGE_ID");
qb.setTables(TABLEMESSAGE);
qb.appendWhere( _ID_MESSAGES + "=" + uri.getPathSegments().get(1));
if (sortOrder == null || sortOrder == ""){
sortOrder = MESSAGE_CREATED_AT + " DESC";
}
break;
case TRANSACTIONS:
Log.e(TAG, "CASE TRANSACTIONS");
qb.setTables(TABLETRANSACTIONS);
qb.setProjectionMap(TRANSACTIONS_PROJECTION_MAP);
if (sortOrder == null || sortOrder == ""){
sortOrder = TRANSACTIONS_TAG_SCAN_TIME + " DESC";
}
break;
case TRANSACTION_ID:
Log.e(TAG, "CASE TRANSACTION_ID");
qb.setTables(TABLETRANSACTIONS);
qb.appendWhere( _ID_TRANSACTIONS + "=" + uri.getPathSegments().get(1));
if (sortOrder == null || sortOrder == ""){
sortOrder = TRANSACTIONS_TAG_SCAN_TIME + " DESC";
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// switch (uriMatcher.match(uri)) {
// case PHONES:
//
// if (sortOrder == null || sortOrder == ""){
//
// sortOrder = PHONE_NAME;
// }
//
// break;
//
// case PHONE_ID:
//
// if (sortOrder == null || sortOrder == ""){
//
// sortOrder = PHONE_NAME;
// }
//
// break;
//
//
// case MESSAGES:
//
// if (sortOrder == null || sortOrder == ""){
//
// sortOrder = MESSAGE_CREATED_AT + " DESC";
// }
//
// break;
//
// case MESSAGE_ID:
//
// if (sortOrder == null || sortOrder == ""){
//
// sortOrder = MESSAGE_CREATED_AT + " DESC";
// }
//
// break;
//
// default:
//
// throw new IllegalArgumentException("Unknown URI " + uri);
// }
//
Log.e(TAG, "About to do the query method in content provider");
Cursor c = qb.query(db, projection, selection, selectionArgs,
null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}//end of query
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
db = nfcAppObj.getDb();
int count = 0;
switch (uriMatcher.match(uri)){
case PHONES:
count = db.delete(TABLEPHONE, selection, selectionArgs);
break;
case PHONE_ID:
String id = uri.getPathSegments().get(1);
count = db.delete( TABLEPHONE, _ID_PHONENUMBERS + " = " + id +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
case MESSAGES:
count = db.delete(TABLEMESSAGE, selection, selectionArgs);
break;
case MESSAGE_ID:
String id2 = uri.getPathSegments().get(1);
count = db.delete( TABLEMESSAGE, _ID_MESSAGES + " = " + id2 +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
db = nfcAppObj.getDb();
int count = 0;
switch (uriMatcher.match(uri)){
case PHONES:
count = db.update(TABLEPHONE, values,
selection, selectionArgs);
break;
case PHONE_ID:
count = db.update(TABLEPHONE, values, _ID_PHONENUMBERS +
" = " + uri.getPathSegments().get(1) +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
case MESSAGES:
count = db.update(TABLEMESSAGE, values,
selection, selectionArgs);
break;
case MESSAGE_ID:
count = db.update(TABLEMESSAGE, values, _ID_MESSAGES +
" = " + uri.getPathSegments().get(1) +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri );
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}//end of delete
#Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)){
/**
* Get all records
*/
case PHONES:
return "vnd.android.cursor.dir/vnd.example.phonenumbers";
/**
* Get a particular record
*/
case PHONE_ID:
return "vnd.android.cursor.item/vnd.example.phonenumbers";
/**
* Get all records
*/
case MESSAGES:
return "vnd.android.cursor.dir/vnd.example.messages";
/**
* Get a particular record
*/
case MESSAGE_ID:
return "vnd.android.cursor.item/vnd.example.messages";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
}
.
[Edit1]
I have got it working and inserting into the Log table with the following code.
Do i have to do a switch statement in the insert method if i want to specify different tables to insert into?
ContentValues cv = new ContentValues();
cv.putNull(LoginValidate.C_ID_LOG);
cv.putNull(LoginValidate.C_LOG_CALLID);
cv.put(LoginValidate.C_LOG_MESSAGE, logString);
cv.put(LoginValidate.C_LOG_CREATED_TIME, formattedNowTime);
cv.put(LoginValidate.C_LOG_CLIENTID, clientID);
cv.put(LoginValidate.C_LOG_CARERID, carerID);
cv.putNull(LoginValidate.C_LOG_SERVER_TIME);
getContentResolver().insert(RR3ContentProvider.CONTENT_URI_LOG, cv);
ContentValues cv = new ContentValues();
cv.putNull(LoginValidate.C_ID_LOG);
cv.putNull(LoginValidate.C_LOG_CALLID);
cv.put(LoginValidate.C_LOG_MESSAGE, logString);
cv.put(LoginValidate.C_LOG_CREATED_TIME, formattedNowTime);
cv.put(LoginValidate.C_LOG_CLIENTID, clientID);
cv.put(LoginValidate.C_LOG_CARERID, carerID);
cv.putNull(LoginValidate.C_LOG_SERVER_TIME);
getContentResolver().insert(RR3ContentProvider.CONTENT_URI_LOG, cv);

How to retrieve one or more phone numbers of one contact from android phone?

I want to retrieve multiple numbers from one contacts which is already saved to phone.
So how to read numbers of one contact programmatically in android?
I have created my own custom class for doing this , it may help you :
package com.android.addressbook.result;
import java.util.HashMap;
import android.graphics.Bitmap;
public class Contact {
String id = "";
String displayName = "";
String dateOfBirth = "";
String dateOfAnniversary = "";
String nickName = "";
String note = "";
Bitmap image = null;
HashMap<Integer, String> emails;
HashMap<Integer, String> phones;
HashMap<Integer, Address> addresses;
HashMap<Integer, Organization> organizations;
HashMap<Integer, String> im;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDateOfAnniversary() {
return dateOfAnniversary;
}
public void setDateOfAnniversary(String dateOfAnniversary) {
this.dateOfAnniversary = dateOfAnniversary;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public HashMap<Integer, String> getEmails() {
return emails;
}
public void setEmails(HashMap<Integer, String> emails) {
this.emails = emails;
}
public HashMap<Integer, String> getPhones() {
return phones;
}
public void setPhones(HashMap<Integer, String> phones) {
this.phones = phones;
}
public HashMap<Integer, Address> getAddresses() {
return addresses;
}
public void setAddresses(HashMap<Integer, Address> addresses) {
this.addresses = addresses;
}
public HashMap<Integer, Organization> getOrganizations() {
return organizations;
}
public void setOrganizations(HashMap<Integer, Organization> organizations) {
this.organizations = organizations;
}
public HashMap<Integer, String> getIm() {
return im;
}
public void setIm(HashMap<Integer, String> im) {
this.im = im;
}
/******************************************************************************************/
static class Address {
private String postBox = "";
private String street = "";
private String city = "";
private String state = "";
private String postalCode = "";
private String country = "";
private String neighborhood = "";
public String getPostBox() {
return postBox;
}
public void setPostBox(String postBox) {
this.postBox = postBox;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getNeighborhood() {
return neighborhood;
}
public void setNeighborhood(String neighborhood) {
this.neighborhood = neighborhood;
}
#Override
public String toString() {
return "Address [postBox=" + postBox + "\n street=" + street
+ "\n city=" + city + "\n state=" + state + "\n postalCode="
+ postalCode + "\n country=" + country + "\n neighborhood="
+ neighborhood + "]";
}
}
/**********************************/
static class Organization {
private String company = "";
private String jobTitle = "";
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
#Override
public String toString() {
return "Organization [company=" + company + "\n jobTitle="
+ jobTitle + "]";
}
}
/**********************************/
public static class Email_TYPE {
// Email Type
public static final int HOME = 1;
public static final int WORK = 2;
public static final int OTHER = 3;
public static final int MOBILE = 4;
}
/**********************************/
public static class PHONE_TYPE {
// / Phone Type
public static final int HOME = 1;
public static final int MOBILE = 2;
public static final int WORK = 3;
public static final int FAX_WORK = 4;
public static final int FAX_HOME = 5;
public static final int PAGER = 6;
public static final int OTHER = 7;
}
/**********************************/
public static class ADDRESS_TYPE {
// / Address Type
public static final int HOME = 1;
public static final int WORK = 2;
public static final int OTHER = 3;
}
/**********************************/
public static class ORGANIZATION_TYPE {
// / Organization Type
public static final int WORK = 2;
public static final int OTHER = 3;
}
/**********************************/
public static class IM_TYPE {
public static final int CUSTOM = -1;
public static final int AIM = 0;
public static final int MSN = 1;
public static final int YAHOO = 2;
public static final int SKYPE = 3;
public static final int QQ = 4;
public static final int GOOGLE_TALK = 5;
public static final int ICQ = 6;
public static final int JABBER = 7;
public static final int NETMEETING = 8;
}
#Override
public String toString() {
return "Contact [id=" + id + "\n displayName=" + displayName
+ "\n dateOfBirth=" + dateOfBirth + "\n dateOfAnniversary="
+ dateOfAnniversary + "\n nickName=" + nickName + "\n note="
+ note + "\n image=" + image + "\n emails=" + emails
+ "\n phones=" + phones + "\n addresses=" + addresses
+ "\n organizations=" + organizations + "\n im=" + im + "]";
}
}
PhoneContact.java
package com.android.addressbook.result;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import com.android.addressbook.result.Contact.Address;
import com.android.addressbook.result.Contact.Organization;
public class PhoneContact {
ContentResolver cr;
List<Contact> contactList;
Context context;
public PhoneContact(Context context) {
this.context = context;
cr = context.getContentResolver();
contactList = new ArrayList<Contact>();
readContacts();
}
public void readContacts() {
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Contact contact = new Contact();
// Get contact id (id)
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
contact.setId(id);
// Get contact name (displayName)
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contact.setDisplayName(displayName);
// Get BirthDay (dateOfBirth)
Uri URI_DOB = ContactsContract.Data.CONTENT_URI;
String SELECTION_DOB = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE
+ "="
+ ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] SELECTION_ARRAY_DOB = new String[] {
id,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor currDOB = cr.query(URI_DOB, null, SELECTION_DOB,SELECTION_ARRAY_DOB, null);
int indexDob = currDOB.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
if (currDOB.moveToNext()) {
String dobStr = currDOB.getString(indexDob);
contact.setDateOfBirth(dobStr);
}
currDOB.close();
// Get Anniversary (dateOfAnniversary)
Uri URI_DOA = ContactsContract.Data.CONTENT_URI;
String SELECTION_DOA = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE
+ "="
+ ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY;
String[] SELECTION_ARRAY_DOA = new String[] {
id,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor currDOA = cr.query(URI_DOA, null, SELECTION_DOA,SELECTION_ARRAY_DOA, null);
int indexDoa = currDOA.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
if (currDOA.moveToNext()) {
String doaStr = currDOA.getString(indexDoa);
contact.setDateOfAnniversary(doaStr);
}
currDOA.close();
// Get Nick Nmae(nickName)
Uri URI_NICK_NAME = ContactsContract.Data.CONTENT_URI;
String SELECTION_NICK_NAME = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_NICK_NAME = new String[] {
id,
ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE };
Cursor currNickName = cr.query(URI_NICK_NAME, null,
SELECTION_NICK_NAME, SELECTION_ARRAY_NICK_NAME,
null);
int indexNickName = currNickName.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
if (currNickName.moveToNext()) {
String nickNameStr = currNickName
.getString(indexNickName);
contact.setNickName(nickNameStr);
}
currNickName.close();
// GetNote(note)
Uri URI_NOTE = ContactsContract.Data.CONTENT_URI;
String SELECTION_NOTE = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_NOTE = new String[] {
id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
Cursor currNote = cr.query(URI_NOTE, null, SELECTION_NOTE,SELECTION_ARRAY_NOTE, null);
int indexNote = currNote.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
if (currNote.moveToNext()) {
String noteStr = currNote.getString(indexNote);
contact.setNote(noteStr);
}
currNote.close();
// Get User Image (image)
Uri URI_PHOTO = ContactsContract.Data.CONTENT_URI;
String SELECTION_PHOTO = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_PHOTO = new String[] {
id,
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE };
Cursor currPhoto = cr.query(URI_PHOTO, null,SELECTION_PHOTO, SELECTION_ARRAY_PHOTO, null);
int indexPhoto = currPhoto.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO);
while (currPhoto.moveToNext()) {
byte[] photoByte = currPhoto.getBlob(indexPhoto);
if (photoByte != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = context.getCacheDir();
// Temporary file to store the contact image
// File tmpFile = new File(cacheDirectory.getPath()
// + "/image_"+id+".png");
File tmpFile = new File(cacheDirectory.getPath()+ "/image_.png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG, 100,fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// String photoPath = tmpFile.getPath();
contact.setImage(bitmap);
}
}
currPhoto.close();
// Get Email and Type.... (<HashMap<Integer, String> emails)
Uri URI_EMAIL = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String SELECTION_EMAIL = ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = ?";
String[] SELECTION_ARRAY_EMAIL = new String[] { id };
Cursor emailCur = cr.query(URI_EMAIL, null,SELECTION_EMAIL, SELECTION_ARRAY_EMAIL, null);
int indexEmail = emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
int indexEmailType = emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE);
if (emailCur.getCount() > 0) {
HashMap<Integer, String> emailMap = new HashMap<Integer, String>();
while (emailCur.moveToNext()) {
// This would allow you get several email addresses,
// if the email addresses were stored in an array
String emailStr = emailCur.getString(indexEmail);
String emailTypeStr = emailCur.getString(indexEmailType);
emailMap.put(Integer.parseInt(emailTypeStr),emailStr);
}
contact.setEmails(emailMap);
}
emailCur.close();
// Get Phone Number....(HashMap<Integer, String>phones)
Uri URI_PHONE = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String SELECTION_PHONE = ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?";
String[] SELECTION_ARRAY_PHONE = new String[] { id };
Cursor currPhone = cr.query(URI_PHONE, null,SELECTION_PHONE, SELECTION_ARRAY_PHONE, null);
int indexPhoneNo = currPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int indexPhoneType = currPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
if (currPhone.getCount() > 0) {
HashMap<Integer, String> phoneMap = new HashMap<Integer, String>();
while (currPhone.moveToNext()) {
String phoneNoStr = currPhone.getString(indexPhoneNo);
String phoneTypeStr = currPhone.getString(indexPhoneType);
phoneMap.put(Integer.parseInt(phoneTypeStr),phoneNoStr);
}
contact.setPhones(phoneMap);
}
currPhone.close();
// Get Postal Address....(HashMap<Integer, Address> addresses)
Uri URI_ADDRESS = ContactsContract.Data.CONTENT_URI;
String SELECTION_ADDRESS = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_ADDRESS = new String[] {
id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
Cursor currAddr = cr.query(URI_ADDRESS, null,SELECTION_ADDRESS, SELECTION_ARRAY_ADDRESS, null);
int indexAddType = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE);
int indexStreet = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET);
int indexPOBox = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX);
int indexNeighbor = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD);
int indexCity = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY);
int indexRegion = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION);
int indexPostCode = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
int indexCountry = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
if (currAddr.getCount() > 0) {
HashMap<Integer, Address> addressMap = new HashMap<Integer, Contact.Address>();
while (currAddr.moveToNext()) {
Contact.Address address = new Contact.Address();
String typeStr = currAddr.getString(indexAddType);
address.setStreet(currAddr.getString(indexStreet));
address.setNeighborhood(currAddr.getString(indexNeighbor));
address.setPostalCode(currAddr.getString(indexPostCode));
address.setPostBox(currAddr.getString(indexPOBox));
address.setCity(currAddr.getString(indexCity));
address.setState(currAddr.getString(indexRegion));
address.setCountry(currAddr.getString(indexCountry));
addressMap.put(Integer.parseInt(typeStr), address);
}
contact.setAddresses(addressMap);
}
currAddr.close();
// Get Organization (HashMap<Integer, Organization> organizations)
Uri URI_ORGNIZATION = ContactsContract.Data.CONTENT_URI;
String SELECTION_ORGNIZATION = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_ORGNIZATION = new String[] {
id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
Cursor currOrg = cr.query(URI_ORGNIZATION, null,
SELECTION_ORGNIZATION, SELECTION_ARRAY_ORGNIZATION,
null);
int indexOrgType = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE);
int indexOrgName = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA);
int indexOrgTitle = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE);
if (currOrg.getCount() > 0) {
HashMap<Integer, Organization> orgMap = new HashMap<Integer, Contact.Organization>();
while (currOrg.moveToNext()) {
Contact.Organization organization = new Organization();
String orgTypeStr = currOrg.getString(indexOrgType);
organization.setCompany(currOrg.getString(indexOrgName));
organization.setJobTitle(currOrg.getString(indexOrgTitle));
orgMap.put(Integer.parseInt(orgTypeStr),organization);
}
contact.setOrganizations(orgMap);
}
currOrg.close();
// Get Instant Messenger..... (HashMap<Integer, String> im)
Uri URI_IM = ContactsContract.Data.CONTENT_URI;
String SELECTION_IM = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_IM = new String[] {
id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
Cursor currIM = cr.query(URI_IM, null, SELECTION_IM,SELECTION_ARRAY_IM, null);
int indexName = currIM
.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA);
int indexType = currIM
.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL);
if (currIM.getCount() > 0) {
HashMap<Integer, String> imMap = new HashMap<Integer, String>();
while (currIM.moveToNext()) {
String imNameStr = currIM.getString(indexName);
String imTypeStr = currIM.getString(indexType);
imMap.put(Integer.parseInt(imTypeStr), imNameStr);
}
contact.setIm(imMap);
}
currIM.close();
/*****************************************/
contactList.add(contact);
}
}
}
cur.close();
}
public List<Contact> getAllContacts() {
return contactList;
}
}
and finally use this in your activity :
PhoneContact pCon = new PhoneContact(context);
List<Contact> conList = pCon.getAllContacts();
HashMap<Integer, String> phones = conList.get(0).getPhones();
String home = phones.get(Contact.PHONE_TYPE.HOME);
here is the tutorial. i think it may help you. check once
Working With Android Contacts
Hope this Snippet can help you out
String id , name;
ContentResolver cr = getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, sortOrder);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString( cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.i(tag, "Id is "+ id+"\t Name is"+name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
// this second loop will retrieve all the contact numbers for a paricular contact id
while (pCur.moveToNext()) {
// Do something with phones
int phNumber = pCur.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
String phn = pCur.getString(phNumber);
Log.i("phn number", phn);
}
pCur.close();
}
}
}

Categories

Resources