Wrong URL for using Calendar Android - java

I'm trying to add events to the basic Calendar by using Intent. I think it's working fine but when I try to read it I always got an exception. java.lang.IllegalArgumentException: Unknown URL content://com.android.calendar/
If I'm using this URL: "content://com.android.calendar/calendars" my ReadFromCalendar() method shows me two IDs but non of them is correct and if I add a new event the number of the IDs doesn't change. So I guess it's not the correct URL.
If I'm using this URL:"content://com.android.calendar/" + "events" then I got IDs from the lowest value to the highest value. When I add a new event the IDs value growing with +1 no matter what set to ID.
So the quesiton is how can I get the correct eventID-s from my calendar? Am I using the wrong URL?
Here is the what I'm using:
public class CalendarUtils {
static int numC = 0;
private final Activity activity;
public CalendarUtils(Activity activity) {
this.activity = activity;
}
public void InsertAnEvent() {
numC++;
long event_id = numC;
Calendar calendarEvent = Calendar.getInstance();
Intent i = new Intent(Intent.ACTION_EDIT);
i.setType("vnd.android.cursor.item/event");
i.putExtra("beginTime", calendarEvent.getTimeInMillis());
i.putExtra("allDay", true);
i.putExtra("_id", event_id);
i.putExtra("rule", "FREQ=YEARLY");
i.putExtra("endTime", calendarEvent.getTimeInMillis() + 60 * 60 * 1000);
i.putExtra("title", "Eskuvo");
activity.startActivity(i);
}
public void ReadFromCalendar() {
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(activity));
ContentResolver cr = activity.getContentResolver();
Cursor cursor;
cursor = cr.query(EVENTS_URI, null, null, null, null);
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex("_id"));
Log.d("TAG", "ID: " + id);
if (id == 63) {
Toast.makeText(activity, "győztél", Toast.LENGTH_SHORT).show();
}
}
cursor.close();
}
public static String getCalendarUriBase(Activity activity) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = activity.getContentResolver().query(calendars,
null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = activity.getContentResolver().query(calendars,
null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
}

Related

how to get the items name from listview after using intent with sqlite?

i have two listviews each one of them is in different activity i want to send an item from the first listview to the other one by long click on it im using intent, im using string file to get the data it sends the item perfectly but its not saved to sqlite i dont know where is the problem please take a look at my code
First Activity(Main Activity):
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l);// THIS ADDED
startActivity(intent);
fav_name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, fav_name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
Second Activity(cc):
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
manageFavouritesListView();
if (fav_id==0){
}
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (getDataInCurrentLocaleById.moveToFirst()) {
fav_name = getDataInCurrentLocaleById.getString(getDataInCurrentLocaleById.getColumnIndex(FAVOURITES_COL_NAME));
}
getDataInCurrentLocaleById.close();
}
private void manageFavouritesListView() {
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview2,
getDataInCurrentLocaleById,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(favourites_adapter);
setListViewHandler(listView, true);
} else {
favourites_adapter.swapCursor(getDataInCurrentLocaleById);
}
}
Db_Sqlite:
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
public String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
i dont where is the problem please help me thank you in advance
You should notify the adapter that data changed.
private void manageFavouritesListView() {
getDataInCurrentLocaleById = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview2,
getDataInCurrentLocaleById,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(favourites_adapter);
favourites_adapter.notifyDataSetChanged();
setListViewHandler(listView, true);
} else {
favourites_adapter.swapCursor(getDataInCurrentLocaleById);
}
}

Find all mp3 files in storage in android

Im trying to find all mp3 files but a have no idea and I found this code, the only problem is the getActivity() wasn't declared, I don't how know to fix, please help me. If has the better way of to do this, I accept sugestion.
here is my class:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs() {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = getActivity().getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
Set parameter for Method (getMp3Songs) as Context:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs(Context ctx) {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = ctx.getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
create Constructor and put there Context. And then call context instead of getActivity();
public class SongsManager {
private Context context;
public SongsManager(Context context){
this.context = context;
}
}

How to get the URI of profile pic from a contact number?

I have create custom incoming call screen that can current show the name and phone number of an incoming call. If the contact has a profile pic set that image should display in the ImageView. I calls the below method, and assigns the picture to the ImageView. The problem is that the else statement is always executed:
public static Uri getPhotoUri(String savedNumber, Context context) {
try {
Cursor cur = context
.getContentResolver()
.query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ getContactIDFromNumber(savedNumber,
context)
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
getContactIDFromNumber(savedNumber, context));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
public static int getContactIDFromNumber(String contactNumber,Context context) {
int phoneContactID = 0;
Cursor contactLookupCursor = context.getContentResolver().query(
Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(contactNumber)),
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
try {
contactLookupCursor.moveToFirst();
while (contactLookupCursor.moveToNext()) {
phoneContactID = contactLookupCursor.getInt(contactLookupCursor
.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
} finally {
contactLookupCursor.close();
}
return phoneContactID;
}
IncomingActivity:
#Override
protected void onResume() {
super.onResume();
callerNumber.setText(savedNumber);
callerName.setText(CommonMethods.getCallerName(savedNumber, this));
callerImageUri = CommonMethods.getPhotoUri(savedNumber, this);
if (callerImageUri != null) {
callerImage.setImageURI(callerImageUri);
} else {
callerImage.setImageResource(R.drawable.contact_default);
}
}
Does anyone have any ideas as to why "callerInamgeUri" is remaining null?

Android get Media.Images Uri from ID

I am new to Android and Java and this week I've been doing a self-taught crash course. So far what I've learned has not been too complicated as I've already built a number of years of coding experience. So, background history out of the way, onto my question.
The below code is two functions I wrote to take an image ID from a database and parse the correct Uri which I can then use to upload the photo to a website. So could you kind folks look over my code and let me know if I'm doing a terrible job or if I am heading in the right direction or even if there is a better/native way to do what I need.
Also, note: the below code does work. I just don't know if it is the right way to do it.
Thanks!
// Usage Map idPath = ImageIdPathFetcher.getRealIdPathFromID(getApplicationContext(), Integer.valueOf(image_id));
public static Map getRealIdPathFromID(Context context, Integer id) {
Map<String,String> idPath = new HashMap<String, String>();
Uri external_images_uri = MediaStore.Images.Media.getContentUri("external");
Uri internal_images_uri = MediaStore.Images.Media.getContentUri("internal");
// initialize uri
Uri uri = external_images_uri;
String ext_img_uri = external_images_uri.toString()+"/"+id;
String int_img_uri = internal_images_uri.toString()+"/"+id;
if(check_uri(context, ext_img_uri))
{
uri = Uri.parse(ext_img_uri);
}else if(check_uri(context, int_img_uri))
{
uri = Uri.parse(int_img_uri);
}else {
idPath.put("id", "");
idPath.put("path", "");
return idPath;
}
String[] proj = { Media.DATA, Media._ID };
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(Media.DATA);
cursor.moveToFirst();
String filepath = cursor.getString(column_index);
idPath.put("id", id.toString());
idPath.put("path", filepath);
return idPath;
}
public static boolean check_uri(Context context, String uri)
{
try{
ContentResolver cr = context.getContentResolver();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cur = cr.query(Uri.parse(uri), projection, null, null, null);
if(cur != null)
{
cur.moveToFirst();
String filePath = cur.getString(0);
if(! new File(filePath).exists()){
return false;
}
} else {
return false;
}
} catch (Exception e)
{
return false;
}
return true;
}
This is what I use
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
}
} finally {
cursor.close();
}
}
cursor = context.getContentResolver().query(
MediaStore.Images.Media.INTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, String.valueOf(id));
}
} finally {
cursor.close();
}
}
return null;
}
It is possible to query both internal and external MediaStore database also with MergeCursor:
String myIdImgStr = "123"; // the unique ID of the image in the MediaStore
ContentResolver contentResolver = this.getContext().getContentResolver();
String [] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
MergeCursor cursor = new MergeCursor(new Cursor[] {
MediaStore.Images.Media.query(contentResolver,
Uri.parse(MediaStore.Images.Media.INTERNAL_CONTENT_URI + "/" + myIdImgStr),
proj),
MediaStore.Images.Media.query(contentResolver,
Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + myIdImgStr),
proj)
});
if(cursor.getCount() == 1) {
cursor.moveToFirst();
String filepath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}

Service insert more than expected on database

I'm getting the contacts from CallLog and inserting it on the database using a Service with a ContentObserver. So, the ContentObserver keep watching if some new changes happens to the CallLog, and if yes, inside the method onChange() it calls the method that get the data in the CallLog and insert it on database.
But, the problem is that, If I make a new call, there is one new data, so, it must be inserted in the database, only one new row, but it inserts 3 rows. I don't know why. I tested it on Android 2.3 Emulator and on the emulator it is ok, but on a real 2.3 device it happens. And in the 2.1 emulator it happens too.
So here is my code. The Service is posted. Thanks!
Here is the Service MyApplicationService.java
public class MyApplicationService extends Service {
private Handler handler = new Handler();
private SQLiteDatabase db;
private OpenHelper helper;
class MyApplicationContentObserver extends ContentObserver {
public MyApplicationContentObserver(Handler h) {
super(h);
helper = new OpenHelper(getApplicationContext());
db = helper.getWritableDatabase();
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
searchInsert();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
db = DataHandlerDB.createDB(this);
registerContentObservers();
}
#Override
public void onDestroy() {
db.close();
}
private void searchInsert() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
if (cursor.moveToFirst()) {
int numberColumnId = cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int durationId = cursor
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int contactNameId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
int callTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.TYPE);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
SimpleDateFormat dateFormat = new SimpleDateFormat("M/d/yyyy");
Date date = new Date();
cursor.moveToFirst();
String contactNumber = cursor.getString(numberColumnId);
String contactName = (null == cursor.getString(contactNameId) ? ""
: cursor.getString(contactNameId));
String duration = cursor.getString(durationId);
String numType = cursor.getString(numTypeId);
String callType = cursor.getString(callTypeId);
ContentValues values = new ContentValues();
values.put("contact_id", 1);
values.put("contact_name", contactName);
values.put("number_type", numType);
values.put("contact_number", contactNumber);
values.put("duration", duration);
values.put("date", dateFormat.format(date));
values.put("current_time", currTime);
values.put("cont", 1);
values.put("type", callType);
if (!db.isOpen()) {
db = getApplicationContext()
.openOrCreateDatabase(
"/data/data/com.myapp.app/databases/my_database.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
cursor.close();
}
}
public void registerContentObservers() {
this.getApplicationContext()
.getContentResolver()
.registerContentObserver(
android.provider.CallLog.Calls.CONTENT_URI, true,
new MyApplicationContentObserver(handler));
}
}

Categories

Resources