I'm developing Custom content provider in my app. And face issuel when get list from custom content provider. Detail, my custom content provider contain a Table. I just want get all object in this table. But it not working. This is my code, please show me what thing i wrong ?
public void onAdd(View v) {
String name = edtname.getText().toString();
Uri uri = Uri.parse("content://homework.iuh.hh.customcontentprovider.AccountProvider/accounts");
ContentValues values = new ContentValues();
values.put("NAME", name);
getContentResolver().insert(uri, values);
}
public void getList(View v) {
Uri uri = Uri.parse("content://homework.iuh.hh.customcontentprovider.AccountProvider/accounts");
Cursor c = getContentResolver().query(uri,null,null,null,null);
c.moveToFirst();
String res= "";
while(!c.isAfterLast())
{
res += c.getString(0);
c.moveToNext();
}
c.close();
Log.i(TAG,res);
And it is query method in content provider
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Log.i(TAG,"query()");
Cursor c = getContext().getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);
c.setNotificationUri(getContext().getContentResolver(),uri);
return c;
}
In method onAdd(), it working fine. But with method getList, it show log, query function is called very time. and crash app with message
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!
05-21 11:07:43.661 5876-5876/? E/AndroidRuntime: Error reporting crash
android.os.TransactionTooLargeException
Try changing your code to be as follows:
Cursor c = getContentResolver().query(uri,null,null,null,null);
String res= "";
while(c.moveToNext()){
res += c.getString(0);
}
c.close();
Log.i(TAG,res);
The real problem is that your Content Provider is just endlessly looping in your query method. You need to actually execute the SQL here, not call the content resolver. Take a look at this class
Related
I am trying to edit the contact of my phone using content provider. To load data i have used below code and it works fine.
private ArrayList<String> getRecords()
{
ArrayList<String> records=new ArrayList<String>();
Cursor cursor=getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
if (cursor.moveToFirst())
{
String name="";
String phone="";
String id="";
do{
id=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
name =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phone =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = id+" "+name+"\n"+phone;
records.add(name);
}
while(cursor.moveToNext());
}
return records;
}
Now i want to edit actually want to change the name of the selected contact. i am trying below code
Uri uri= ContentUris.withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id);
ContentValues values=new ContentValues();
values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, "<r XX");
getContentResolver().update(uri, values, null,null);
But it is not updating. What can i do know? Please help. I already check over internet as well as other ans but did not find satisfactory ans.
you dont seem to supply the update paramaters properlly:
the method consist of:
getContentResolver().update(uri, values, where, selectionArgs)
the where should contain:
"ContactsContract.CommonDataKinds.Phone._ID+"=?"
and the selectionArgs should contain the id of the contact to update.
In my android app when an incoming call i want to show my custom ui and i am able to do this.
No i want to check incoming number is from contacts or not.
Below is my code for doing so but it returns null for an incoming number which is stored in my contacts list.
public String findNameByNumber(String num){
Uri uri = Uri.withAppendedPath(Phones.CONTENT_FILTER_URL, Uri.encode(num));
String name = null;
Cursor cursor = mContext.getContentResolver().query(uri,
new String[] { Phones.DISPLAY_NAME }, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(Phones.DISPLAY_NAME));
cursor.close();
callyName.setText(name+" Calling..");
}
return name;
}
and i have incoming call from a number say+917878787878 but in my contacts this contact is stored as name XYZ with number 78 78 787878,which is formated because between number there are space.and also try by excluding +91 but still it returns null.
So how can i find number which is stored in any format.Which may be stored with country code or not.
Thanks In advance.
Try this code instead (using PhoneLookup.CONTENT_FILTER_URI instead of Phones):
String res = null;
try {
ContentResolver resolver = ctx.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor c = resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
if (c != null) { // cursor not null means number is found contactsTable
if (c.moveToFirst()) { // so now find the contact Name
res = c.getString(c.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));
}
c.close();
}
} catch (Exception ex) {
/* Ignore */
}
return res;
As docs says ContactsContract.PhoneLookup: A table that represents the result of looking up a phone number, for example for caller ID. To perform a lookup you must append the number you want to find to CONTENT_FILTER_URI. This query is highly optimized.
Hi how to send the String value which is in R.String.XXXX into database, i tried as below but getting address instead of the actual string content.
In my class
DatabaseHelper.getInstance(Aboutipc_fragment.this).addAboutData(R.string.aboutcontent, "haresh");
In my Database Helper class
public void addAboutData(int aboutcontent,String string) {
ContentValues cv = new ContentValues();
//System.out.println("geting notes from the database===== "+str);
cv.put(KEY_ABOUTCONTENT, aboutcontent);
cv.put(KEY_VALUE,string);
db.insert(CREATE_ABOUTIPC_TABLE, null, cv);
}
I am fetching Data As below
public Cursor fetchcontentvalues() {
Cursor c = null;
c = db.query(CREATE_ABOUTIPC_TABLE, new String[] {KEY_ABOUTCONTENT}, null, null, null, null,null);
//moving to the first note
//c.moveToFirst();
c.moveToPosition(0);
System.out.println("getting notes from the database"+c.getString(0));
return c;
}
Output
getting notes from the database 2131099663
The system out statement is giving some address value i want to display the actual content of the string.
this is very simple
get strings from r.string you can use method getString which return a String Value
String a=getString(R.string.name);
in your method you can use
addAboutData(getString(R.string.name), "haresh");
Use the following:
String aboutContent = getResources().getString(R.string.xxxx);
Change your addAboutData method as below
public void addAboutData(String aboutcontent,String string) {
ContentValues cv = new ContentValues();
cv.put(KEY_ABOUTCONTENT, aboutcontent);
cv.put(KEY_VALUE,string);
db.insert(CREATE_ABOUTIPC_TABLE, null, cv);
}
Then fetch data using
public Cursor fetchcontentvalues() {
Cursor c = null;
c = db.query(CREATE_ABOUTIPC_TABLE, new String[] {KEY_ABOUTCONTENT}, null, null, null, null,null);
//moving to the first note
//c.moveToFirst();
c.moveToPosition(0);
System.out.println("getting notes from the database"+c.getString(0));
return c;
}
I have the following code to get details of a contact.
"data": is the Uri I get back after selecting the contact.
I need to be sure that I will get to the right contact in the future so what should I be saving for future use? Is it "lookupUri" or "lookupKey"?
Cursor c = activity.managedQuery(data, null, null, null, null);
c.moveToFirst();
String lookupKey = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY ));
c.close();
// Next use that key to access the details of the contact in order to get the name and the photo
// Also, save it for future use.
// It will be used when we fetch the details from the database since the photo itself is not saved.
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI,lookupKey);
Uri uri = ContactsContract.Contacts.lookupContact(activity.getContentResolver(), deviceDetails.lookupUri);
LookupKey is the unique identifier that you want to store.
FYI; There is a bug in 2.1 where un-synced contacts LookupKey changes when the name is changed.
This works. My example looks up the name; add or remove the fields you want in the projection.
private String getContactNameFromAndroidKey (String key)
{
// Run query
Uri uri = Uri.parse (ContactsContract.Contacts.CONTENT_LOOKUP_URI + "/" + key);
String[] projection = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
};
Cursor cursor = context.getContentResolver().query (
uri,
projection,
null,
null,
null);
if (!cursor.moveToNext()) // move to first (and only) row.
throw new IllegalStateException ("contact no longer exists for key");
String name = cursor.getString(1);
cursor.close();
return name;
}
Hey guys,im working on a simple quiz and im gone crazy !!
The problem is that everything is working (database created as it shoulds) except when i am trying to get string from database shows java.lang.NullPointerException.I checked the uri is corrected and the number of items in array!!I am trying to find out why this is happening for 5 hours and i am stucked here!!!I dont know what elso to do!!Your help is more than appreciated!!
My main class where i am trying to get string is that one with bold
Uri newUri = ContentUris.withAppendedId(
QuestionsProvider.CONTENT_URI,
this.currentQuestion);
Log.d(TAG, "SHOWQUESTION " + " URI="+newUri.toString());
Cursor cursor = cr.query(newUri,
null, null, null, null);
if (cursor.moveToFirst()) {
**question.setText(cursor.getString(
QuestionsProvider.QUESTION_COLUMN)); //HERE I AM GETTING THE ERROR
currentAnswer = cursor.getString(
QuestionsProvider.ANSWER_COLUMN);**
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text;
String answerGiven =
answer.getText().toString();
answer.setText("");
if (answerGiven.
equalsIgnoreCase(currentAnswer))
{text = "Correct";
}else{
text = "Wrong - "+currentAnswer;
Toast.makeText(getApplicationContext(),
text, Toast.LENGTH_SHORT).show();
}
}});
}
cursor.close();
dialog.show();
and in my manifest i add succesfully the provider and is loading as it should!!
Why this error happens??I can see anything wrong!!
It doesn't look like you're specifying a projection in the query:
Cursor cursor = cr.query(newUri, null, null, null, null);
Try adding a projection with the columns you want returned:
Cursor cursor = cr.query(newUri, new String[] {KEY_ID, KEY_QUESTION, KEY_ANSWER}, null, null, null);
I found the solution guys! Thank you for helping me unstucking heh :P
This is the solution i found!!
String columns[] = new String[] { QuestionsProvider.KEY_QUESTION, QuestionsProvider.KEY_ANSWER };
Uri mUri = QuestionsProvider.CONTENT_URI;
Cursor cur = managedQuery(mUri, columns, // Which columns to return
QuestionsProvider.KEY_ID+"="+currentQuestionNumber, // WHERE clause; which rows to return(all rows)
null, // WHERE clause selection arguments (none)
null // Order-by clause (ascending by name)