Content values are assigned null even after putting values in it - android

As a part of Unit testing I wanted to insert values to DB using content resolver. But when I tried this,
#Before
public void runBeforeTestSignOut() {
ContentValues values = new ContentValues();
String userId="123";
String userInfo="test";
values.put(UserProvider.USER_ID, userId);
values.put(UserProvider.USER_INFO, userInfo);
System.out.print("Values are "+values);
Uri uri = contentResolver.insert(UserProvider.CONTENT_USER_URI, values);
}
Values are still assigned null. I can’t figure out why this is happening. I found some related questions but couldn’t find a solution. Please help me with this.

Related

Adding data to SQLite

I'm creating my first data enabled app but am struggling with the last part - actually adding and retrieving the data. For now I am only concerned with adding data to the table. Following this tutorial I have created model classes for my tables and a DBHelper class with all my CRUD methods (I can post all these if required but not sure they are necessary to answer this question. Please correct me if I am wrong!). Unfortunately the tutorial ends here and doesn't go into detail on how to pass the data from the UI of the app into the DB.
After some Google searches I have found an example of how to pass some data to these methods but only how to pass one piece of data at a time, so only really useful if my table has just one field - mine has more than one.
For example, if I have a a table for "Todo" tasks, in my dbhelper my create method may be;
public void createTodo(String todoText) {
ContentValues contentValues = new ContentValues();
contentValues.put("todo", todoText);
// Insert into DB
db.insert("todos", null, contentValues);
}
so from my activity I just need
dao.createTodo(todoTextValue);
For my app I will be adding more than one field at a time, so my create method looks like this;
public long createSite(Site site){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SITE_NAME, site.getSiteName());
values.put(KEY_SITE_LAT, site.getSiteLat());
values.put(KEY_SITE_LON, site.getSiteLon());
values.put(KEY_CREATED_AT, site.getSiteCreatedDateTime());
// Insert Row
long siteid = database.insert(TABLE_SITES, null, values);
So my question really is how I can pass all the different bits of data to the createSite method.
I don't know if this really needs an answer, but well here's a code...
Assuming your Site class is like this.
public class Site {
private String siteName;
private double siteLat;
private double siteLon;
private Date siteCreatedDateTime;
// getters and setters here
}
You then pass the data from your EditText value to your new Site object. It will look like this in your activity.
EditText siteNameInput = (EditText) findViewById(R.id.siteNameInput);
EditText siteLatInput = (EditText) findViewById(R.id.siteLatInput);
EditText siteLonInput = (EditText) findViewById(R.id.siteLonInput);
EditText siteCreatedDateTimeInput = (EditText) findViewById(R.id.siteCreatedDateTimeInput);
String siteName = siteNameInput.getText().toString();
String siteLat = siteLatInput.getText().toString();
String siteLon = siteLonInput.getText().toString();
String siteCreatedDateTime= siteCreatedDateTimeInput.getText().toString();
Site site = new Site();
site.setSiteName(siteName);
site.setSiteLat(siteLat);
site.setSiteLon(siteLon);
site.setSiteCreatedDateTime(siteCreatedDateTime);
dao.createSite(site);
Hope this helps you... You can learn more on Object-Oriented programming in Java here
public long createSite(Model site,String name, String address){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, site.name);
values.put(KEY_ADDRESS, site.address);
// Insert Row
long siteid = database.insert(TABLE_SITES, null, values);
to add elements to the class you just add
public class Model {
String name;
String address;
//add year as many as you need
Model(String name, String address){
this.name=name;
this.address=address;
}
}
And in you activity you call this
In java to add a new object in this case Model
Model x = new Model("josh","Ireland");
and you just pass to
dao.createTodo(x);
Todo and Site are models. Each variable represents a column of that table. You need to create a custom model for each of your tables. The createSite method takes an object of type Site and adds it as a row in the TABLE_SITES in the DB. values.put(...)takes columnName, value. So here you give your own column names and values.
Instead of getting into all this I suggest you use an orm like active android:
http://www.activeandroid.com/

Retrieve Contact name from phone number

I've been looking everywhere since the past few days to find a way to retrieve a contact name using a phone number I already have stored in a variable, unfortunately everything I found so far seems to be using deprecated functions/calls.
Of Course, I tried doing it my own way but I feel like my Android/JAVA knowledge is not good enough to understand this concept yet, keep getting some errors or force close when I try to run anything.
So far the best thing I could find was something like this:
public String getContactName(final String phoneNumber)
{
Uri uri;
String[] projection;
if (Build.VERSION.SDK_INT >= 5)
{
uri = Uri.parse("content://com.android.contacts/phone_lookup");
projection = new String[] { "display_name" };
}
else
{
uri = Uri.parse("content://contacts/phones/filter");
projection = new String[] { "name" };
}
uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
String contactName = "";
if (cursor.moveToFirst())
{
contactName = cursor.getString(0);
}
cursor.close();
cursor = null;
return contactName;
}
But by using this code, Eclipse tells me: context cannot be resolved.
A lot of the codes and explanations I found were using this Context thing, but I still don't understand it even after reading this: What is 'Context' on Android?
Any help will be greatly appreciated,
Thank you very much
If you're using this inside an activity, then a context is what you get by using this. So basically here, instead of calling context.getContentResolver(), call this.getContentResolver() or simply just getContentResolver().
Eclipse complains basically because you're trying to call a method of something called context which Eclipse doesn't know because it hasn't been declared anywhere. It would work if you previously did something like Context context = this;, but that's really useless.
getContentResolver() is a method declared and defined by Activity which is a class that your activity extends, therefore you can call it just like that.
I hope it helps. As to what this context really is, I am sorry, but I can't help you with that as I am not even sure I understand it correctly.
Also, please notice, that I haven't checked the code you posted and I don't know if it works for obtaining a contact's name from a phone number. Just wanted to help you with getting rid of the context cannot be resolved error.

Call logs restore in android

I am creating an application in android for call logs backup and restore using csv file.Backup was successfully created but while restoring all call logs are not restored from csv.Here is the code i am writing for backup
while((row = csvReader.readNext()) != null)
{
RestoreCallLogs(row[0],row[1],row[2],row[3],row[4]);
}
public void RestoreCallLogs(String Name,String number,String Date,String Type,String Duration){
ContentValues values = new ContentValues();
values.put(CallLog.Calls.NUMBER, number);
values.put(CallLog.Calls.DATE, Date);
values.put(CallLog.Calls.DURATION,Duration);
values.put(CallLog.Calls.TYPE, Type);
if(Name!="Unknown")
values.put(CallLog.Calls.CACHED_NAME, Name);
getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
}
You have a try-catch block which is hiding the exception generated here:
RestoreCallLogs(row[0],row[1],row[2],row[3],row[4]);
You should not use try-catch without understanding what it does.
To fix:
String[] row;
while((line = csvReader.readNext()) != null){
row = line.split(",");
RestoreCallLogs(row[0],row[1],row[2],row[3],row[4]);
}
Please read the documentation for .split(). You will need to do extra work to deal with commas and other non-alphanumeric characters inside strings of a contact record. You are also assuming that the csv only contains 5 columns. Can you guarantee that?
Finally, please use accepted conventions for naming identifiers in Java. Using a capital letter to start a variable name makes your code hard to read.
[EDIT]
I don't know how your code compiles. Please show the declarations for row and csvReader.

Can't update event on phone's calendar from code

I'm attempting to update a calendar's event on my phone from my code, but context.getContentResolver().update keeps returning 0, and of course there are no changes made to the event when I look at it in the Calendar app.
I'm getting the event ID, start time, etc with context.getContentResolver().query, and I'm getting unique numbers like 431, 4, 233, etc, so I'm presuming the event IDs I'm using are real.
I understand the official way to do this is to go through Google's servers instead of using update(), but for my implementation it doesn't make sense to do it that way (or even in general, but I digress).
Am I doing something wrong, or am I trying to do something that Android simply isn't going to allow?
Uri updateEventUri = ContentUris.withAppendedId(Uri.parse("content://com.android.calendar/events"), id);
ContentValues cv = new ContentValues();
begin.set(Calendar.HOUR_OF_DAY, arg0.getCurrentHour()); //begin is a java.util.Calendar object
begin.set(Calendar.MINUTE, arg0.getCurrentMinute());
//cv.put("_id", id);
//cv.put("title", "yeahyeahyeah!");
cv.put("dtstart", begin.getTimeInMillis());
int updatedrowcount = context.getContentResolver().update(updateEventUri, cv, null, null);
System.out.println("updated "+updatedrowcount+" rows with id "+id);
A related question was posted here with no replies https://stackoverflow.com/questions/5636350/update-android-calendar-event
Let me know if I can clarify anything; I would really appreciate any input you guys and dolls could provide!
i had tried a lot and finally ended up with solution (Unreliable though).. but works fine..
public static boolean updateCalendar(Context context,String cal_Id,String eventId)
{
try{
Uri CALENDAR_URI = Uri.parse(CAL_URI+"events");
Cursor c = context.getContentResolver().query(CALENDAR_URI, null, null, null, null);
String[] s = c.getColumnNames();
if (c.moveToFirst())
{
while (c.moveToNext())
{
String _id = c.getString(c.getColumnIndex("_id"));
String CalId = c.getString(c.getColumnIndex("calendar_id"));
if ((_id==null) && (CalId == null))
{
return false;
}
else
{
if (_id.equals(eventId) && CalId.equals(cal_Id))
{
Uri uri = ContentUris.withAppendedId(CALENDAR_URI, Integer.parseInt(_id));
context.getContentResolver().update(uri, null, null, null);// need to give your data here
return true;
}
}
}
}
}
finally
{
return true;
}
}
and finally i'm not sure if it works with every device.
Ok, so, the problem was that I was using different URIs between fetching the events and editing them. I used the code sample from here and was using the URI "content://com.android.calendar/instances/when" to fetch the events and display them on the screen. When I had made a change I was using "content://com.android.calendar/events" to edit by id as in my example above.
What I found, thanks to your response, ntc, was that the ids for events between the two URIs were different, and therefore I couldn't edit the events consistently with the information each was giving me. I was presuming the event ids I was getting were system ids and universal to the phone.
I guess I'll have to do some testing and see what hardware isn't compatible with this method. I am using an HTC Evo for testing and so far so good.
When querying the Instances table, use Instances.EVENT_ID to get the identifier for the event you want to edit, instead of Instances._ID.

how to create an array and fetch the data in sqlite database in android

in my app i have two edit boxes for email and username. Whatever the user types in it i am trying to move it over an url as follows
http//xxxxxxx.com/id?mail=*email&user=*usernane
By this i am getting a return data from the url, this is what i am doing if network is available. But if network is not available i am storing those two values in Sqlite database and in another activity if network is available i will be fetching the above said data and i will move them to the server.
My problem is, at the time of network not available if the user tries to send two set of username and email to the server it gets stored in database. How can i store those values in an array and how can i fetch them one by one. Please help me friends
Following is the part of my code for database
off = openOrCreateDatabase("Offline.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
off.setVersion(1);
off.setLocale(Locale.getDefault());
off.setLockingEnabled(true);
final String CREATE_TABLE_OFFLINEDATA ="CREATE TABLE IF NOT EXISTS offlinedata(spotid INTEGER, username TEXT, email TEXT);";
off.execSQL(CREATE_TABLE_OFFLINEDATA);
ContentValues values = new ContentValues();
values.put("id", millis);
values.put("name", username);
values.put("mail", email);
off.insert("offlinedata", null, values);
Cursor con = off.rawQuery("select * from offlinedata" , null);
if (con != null )
{
if (con.moveToFirst())
{
do
{
int spotid = con.getInt(con.getColumnIndex("id"));
String first = con.getString(con.getColumnIndex("username"));
String middle = con.getString(con.getColumnIndex("email"));
}
while (con.moveToNext());
}
}
off.close();
Please help me friends....
From looking at your sample code, it seems like you're storing them properly(ish), and you've managed an exhaustive job fetching them in a really narrow scope, so make first and middle more globalish and since you have two strings available, put them in an array.
Though I must say if this is your actual code it probably won't work the way you want this whole offline thing to work.

Categories

Resources