What should I use for SQLite database - android

Ok, so here is my dilemma. I j ust started working with SQLite database's in android and I came across the Notepad Tutorial on the Android Developer website. Now I thought that this was pretty cool and was messing around with it until I noticed that Android Studio said that some of the code was deprecated.
One of the deprecated code was startManagingCursor. I decided to look into it more and found something called a CursorLoader with a ContentProvider, so I decided to look them up and it seems like the CursorLoader with a ContentProvider is a better choice. The problem is that I can't find a decent example that doesn't go into outrageous complexity. Like I said I just started learning this and I would like not to sit and try to figure out what someone else's code does for 3 hours.
So are there any good tutorials or examples that don't over complicate this topic so that I have a chance to learn it?

Example Code
package com.prgguru.example;
 
import java.util.ArrayList;
 
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;
 
public class SQLiteCrudExample  extends ListActivity {
    //DB name
    private final String dbName = "Android";
    //Table name
    private final String tableName = "Versions";
    //String array has list Android versions which will be populated in the list
    private final String[] versionNames= new String[]{"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean", "Kitkat"};
    #Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ArrayList<String> results = new ArrayList<String>();
        //Declare SQLiteDatabase object
        SQLiteDatabase sampleDB = null;
         
        try {
            //Instantiate sampleDB object
            sampleDB =  this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
            //Create table using execSQL
            sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + tableName +    " (versionname VARCHAR);");
            //Insert Android versions into table created
            for(String ver: versionNames){
                sampleDB.execSQL("INSERT INTO " + tableName + " Values ('"+ver+"');");
            }
             
            //Create Cursor object to read versions from the table
            Cursor c = sampleDB.rawQuery("SELECT versionname FROM " + tableName, null);
            //If Cursor is valid
            if (c != null ) {
                //Move cursor to first row
                if  (c.moveToFirst()) {
                    do {
                        //Get version from Cursor
                        String firstName = c.getString(c.getColumnIndex("versionname"));
                        //Add the version to Arraylist 'results'
                        results.add(firstName);
                    }while (c.moveToNext()); //Move to next row
                }
            }
             
            //Set the ararylist to Android UI List
            this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
             
        } catch (SQLiteException se ) {
            Toast.makeText(getApplicationContext(), "Couldn't create or open the database", Toast.LENGTH_LONG).show();
        } finally {
            if (sampleDB != null) {
                sampleDB.execSQL("DELETE FROM " + tableName);
                sampleDB.close();
            }
        }
    }
}
===
There is an example source code here to download
Also try this links:
http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/
http://developer.android.com/training/basics/data-storage/databases.html
http://www.vogella.com/tutorials/AndroidSQLite/article.html
http://www.tutorialspoint.com/android/android_sqlite_database.htm

Related

E/SQLiteLog﹕ (1) near "Table": syntax error

I'm trying to start with SQLite in android but I have some problems..
I took the code from a tutorial which was written in 2012, but it's not working for me now and shows me this error:
E/SQLiteLog﹕ (1) near "Table": syntax error
The problem is with creating/opening the Database.
package db.com.example.kids1.databasetest;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends ListActivity{
private final String DB_NAME = "Database";
private final String TABLE_NAME = "Table";
SQLiteDatabase DB = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> results = new ArrayList<>();
String[] res = {"Red", "Green", "Text"};
try {
DB = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +
TABLE_NAME +
"(Name VARCHAR, Street VARCHAR, Block INT, City VARCHAR, Tel VARCHAR);");
mFillDbsTable();
Cursor c = DB.rawQuery("SELECT Name, Street, Block, City, Tel FROM " +
TABLE_NAME +
" where Blcok == 9 LIMIT 5", null);
if (c!=null){
if (c.moveToFirst()) {
do {
String name = c.getString(c.getColumnIndex("Name"));
String street = c.getString(c.getColumnIndex("Street"));
int block = c.getInt(c.getColumnIndex("Block"));
String city = c.getString(c.getColumnIndex("City"));
String tel = c.getString(c.getColumnIndex("Tel"));
results.add(name + "," + street + "," + block + "," + city + "," + tel);
} while (c.moveToNext());
}
}
ListView list = (ListView)findViewById(android.R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, res);
list.setAdapter(adapter);
} catch (SQLiteException se){
Log.e(getClass().getSimpleName(), "Create/Open Database Problem.");
}
}
private void mFillDbsTable(){
try {
DB.execSQL("INSERT INTO " +
TABLE_NAME +
" Values('Noam', 'Shkolnik', 9, 'Rehovot', '054-4900807');");
DB.execSQL("INSERT INTO " +
TABLE_NAME +
" Values('Eyal', 'Shkolnik', 9, 'Rehovot', '055-4488779');");
DB.execSQL("INSERT INTO " +
TABLE_NAME +
" Values('Yehontan', 'Shkolnik', 9, 'Rehovot', '058-7789547');");
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create records.");
}
}
}
private final String TABLE_NAME = "Table"
You can't create a table named Table, because it's a reserved keyword.
You better create a table named MyTable (or _Table or better give a more talkative name, such as Persons - note the s for plurals).
So:
private final String TABLE_NAME = "MyTable"
For your reference: https://sqlite.org/lang_keywords.html
You could (but it's not recommended) use reserved keywords, but then you have to use special delimiters everytime you refer to that table.
Something like
private final String TABLE_NAME = "[Table]"
And there's also another (double) error in your query:
" where Blcok == 9 LIMIT 5"
Should be
" where Block = 9 LIMIT 5"
Try VARCHAR(100) and remove the trailing ;
You got couple of errors. First, do not name your table Table. Table is reserved word (see docs) and cannot be used directly. It's basically not recommended to use reserved words, so I suggest you change your table name, yet if you insist of using it, you need to quote it first:
If you want to use a keyword as a name, you need to quote it. There are four ways of quoting keywords in SQLite:
'keyword' A keyword in single quotes is a string literal.
"keyword" A keyword in double-quotes is an identifier.
[keyword] A
keyword enclosed in square brackets is an identifier. This is not
standard SQL. This quoting mechanism is used by MS Access and SQL
Server and is included in SQLite for compatibility.
keyword A
keyword enclosed in grave accents (ASCII code 96) is an identifier.
This is not standard SQL. This quoting mechanism is used by MySQL and
is included in SQLite for compatibility.
BTW: your further select query will fail too due to typo in where clause:
where Blcok == 9

SQLite database in Android, causes application crash

I'm testing SQLite database in android for the first time.
My program stops as I open it, and i cannot check it, i was wondering if there is a mistake in my code, or database connection,
any help will be appreciated :)
this is my Main.java file:
package de.blattsoft.SQLite;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT * FROM MyTable", null);
c.moveToFirst();
Log.d("Ali", c.getString(c.getColumnIndex("FirstName")));
db.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Note: I have asked this question many times ago, and I have written the full answer of how to implement databases in Android in the answers bellow.
First of all you need to create a database, then insert some data in it an then try to display.
What you are doing is ,if database is not there then create and select the column and display. It will obviously fail and your app crash.
Do something like
public void onCreate(SQLiteDatabase db) {
/*CREATE LOGIN TABLE*/
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT," + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
Then do this ,
public void addMessage(String id, String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, id); //
values.put(KEY_NAME, name);
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
Then you can display ,
You haven't created the database. And inserting or fetching values from the structure which doesn't exist will lead to crash your app. It's like climbing a building which doesn't exist.
So, first create the database then do rest of the things.
For better understanding follow the you tube video tutorial of Slidenerd. They have sequentially explained all the things for beginners here.
Hope it will help.
I have asked this question many times ago when I was an Android noob! :D
right now this is the way I recommend you to use android sqlite database using helper classes.
as an overview, we need to create two classes, DatabaseHelper class
and DataSource class.
What we need to create:
The DatabaseHelper class must extend SQLiteOpenHelper which is a built-in Android class from android.database.sqlite package and its purpose is to manage database creation and version management.
The DataSource class uses our helper class to implement methods which you need for your application.
For Example, we're going to create a database which has one table called users, and the table has 2 columns: id and name;
The id is going to be used as the primary key.
So, let's create the helper class:
DatabaseHelper.java:
package com.mpandg.android.dbtest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
// this tag is used for logging purposes.
public static final String TAG = "database";
// database version.
public static final int DATABASE_VERSION = 1;
// database file name.
public static final String DATABASE_NAME = "database.db";
// table details:
public static final String TABLE_USERS = "users";
public static final String USERS_COLUMN_ID = "id";
public static final String USERS_COLUMN_NAME = "name";
// query of creating users table.
public static final String CREATE_USERS_TABLE =
"CREATE TABLE " + TABLE_USERS + " (" +
USERS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
USERS_COLUMN_NAME + " TEXT" + ")";
// query string of deleting users table.
public static final String DELETE_TABLES =
"DROP TABLE IF EXISTS " + TABLE_USERS + ";";
// constructor method which takes the context and passes it
// to appropriate super method with other database details
// which creates the database.
public DatabaseHelper(Context context) {
// creates the database using given information.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// this line executes the query we made earlier
// to create the users table.
db.execSQL(CREATE_USERS_TABLE);
// log the table creation for debugging.
Log.i(TAG, TABLE_USERS + " has been created.");
}
// whenever you give a new update for your application,
// if you change the version of the database, this method
// will be called, you can do your own complicated operations
// on your tables if you need, but right now, I just delete
// the old table and I make an explicit call to onCreate
// method to create the tables again.
// but never forget that you should never make explicit
// calls to onCreate method, but this is an exception here.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// execute the delete query we made earlier.
db.execSQL(DELETE_TABLES);
// explicit call to onCreate. (read the comment above method)
onCreate(db);
}
}
As you see, we have actually created a subclass of SQLiteOpenHelper and we have implemented onCreate(SQLiteDatabase) and onUpgrade(SQLiteDatabase, int, int) methods, and the helper class we created, takes care of opening the database if it exists, creating it if it does not exist and upgrading it if it's necessary.
Now it's time to use the helper class we created and write our methods to use the database in DataSource class.
We will create a database object and we will instantiate it using the methods in our helper class, and we create methods to insert, select and delete.
So, Let's create DataSource.java:
package com.mpandg.android.dbtest;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class DataSource {
// create an instance of SQLiteOpenHelper
// but we're going to instantiate it using
// the helper class we created earlier.
SQLiteOpenHelper dbHelper;
// the main database object which will be
// instantiated using the helper class methods.
SQLiteDatabase dataBase;
private final String TAG = "dataSource";
// an string array holding our table's column names
// which is going to be used by database methods.
public static final String[] usersTableColumns = {
DatabaseHelper.USERS_COLUMN_ID,
DatabaseHelper.USERS_COLUMN_NAME
};
// constructor which receives the activity context.
public DataSource(Context context){
// instantiate the dbHelper object using our DatabaseHelper class.
dbHelper = new DatabaseHelper(context);
}
public void open(){
// opening the database or
// creating the table structures for the first time.
// the helper class knows when to open or create the database.
dataBase = dbHelper.getWritableDatabase();
// log the event for debugging purposes.
Log.i(TAG, "database opened");
}
public boolean isOpen () {
// check if the database is already open.
return dataBase.isOpen();
}
public void close(){
// close the database.
dataBase.close();
// log the event for debugging purposes.
Log.i(TAG, "database closed");
}
// insert a name record into database .
public void insertName (String name) {
// ContentValues implements a map interface.
ContentValues values = new ContentValues();
// put the data you want to insert into database.
values.put(DatabaseHelper.USERS_COLUMN_NAME, name);
// passing the string array which we created earlier
// and the contentValues which includes the values
// into the insert method, inserts the values corresponding
// to column names and returns the id of the inserted row.
long insertId = dataBase.insert(DatabaseHelper.TABLE_USERS , null, values);
// log the insert id for debugging purposes.
Log.i(TAG, "added name id:" + insertId);
}
// returns a list of string
// containing the names saved in the database.
public List<String> getNames (){
List<String> names;
// creating the cursor to retrieve data.
// cursor will contain the data when the
// query is executed.
Cursor cursor = dataBase.query(DatabaseHelper.TABLE_USERS, usersTableColumns,
null, null, null, null, null);
// log the number of returned rows for debug.
Log.i(TAG, "returned: " + cursor.getCount() + " name rows .");
// check if the cursor is not null.
if(cursor.getCount()>0){
// instantiate the list.
names = new ArrayList<>();
// cursor starts from -1 index, so we should call
// moveToNext method to iterate over the data it contains.
while (cursor.moveToNext()) {
// read the string in the cursor row using the index which is the column name.
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.USERS_COLUMN_NAME));
// log the retrieved name.
Log.i(TAG, "name retrieved:" + name);
// now add the retrieved name into the list.
names.add(name);
}
// now we have the names in our string list
return names;
} else {
// if the cursor was empty, it means that
// there was no name found in the table,
// so return null.
return null;
}
}
// returns a name corresponding to given id.
public String findNameById (long id){
String name;
// the where clause which is our condition.
String whereClause = DatabaseHelper.USERS_COLUMN_ID + " = ?";
// the arguments passed to
// the where clause. (here is only one argument)
String[] whereArgs = {id+""};
// creating the cursor to retrieve data.
// cursor will contain the data when the
// query is executed.
Cursor cursor = dataBase.query(DatabaseHelper.TABLE_USERS, usersTableColumns,
whereClause, whereArgs, null, null, null);
// log the number of returned rows for debug.
// (logically it should return one row here)
Log.i(TAG, "returned: " + cursor.getCount() + " name rows .");
// check if the cursor is not null.
if(cursor.getCount()>0){
// cursor starts from -1 index, so we should call
// moveToNext method to iterate over the data it contains.
cursor.moveToNext();
// read the string in the cursor row using the index which is the column name.
name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.USERS_COLUMN_NAME));
// log the retrieved name.
Log.i(TAG, "name retrieved:" + name);
return name;
} else {
// if the cursor was empty, it means that
// there was no name found with given id,
// so return null.
return null;
}
}
// delete a name from the table.
public void deleteName (String name) {
// where statement of our delete method.
String whereClause = DatabaseHelper.USERS_COLUMN_NAME + "=" + "?";
// the arguments passed to
// the where clause. (here is only one argument)
String[] whereArgs = {name};
// execute the delete query with delete method.
int deleteId = dataBase.delete(DatabaseHelper.TABLE_USERS , whereClause, whereArgs);
// log the id of the deleted row.
Log.i(TAG, "deleted name id:" + deleteId);
}
}
Now that we have done writing the necessary classes to create and use our database in an appropriate way, it's time to use the methods we wrote in our DataSource class.
All you have to do, is to create an object of DataSource class in your activity and use the methods in it.
when you are intending to use the database, you should open it, you can simply do it by the open() method we wrote in our DataSource class, and after you are done, you must close it to avoid leaks; you can close it using the close() method in 'DataSource` class.
For example, you have some users and you want to add them in the database:
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// insert the names.
dataSource.insertName("Amy");
dataSource.insertName("Johnny");
dataSource.insertName("Abbey");
dataSource.insertName("Miley");
// close the database.
dataSource.close();
Or you want to log all the users in the database:
//TAG for debug logs.
String TAG = "db log";
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// get the names.
List<String> names = dataSource.getNames();
// log all the names in the list.
for (String name: names) {
Log.i(TAG, "retrieved name:" + name);
}
// close the database.
dataSource.close();
Or you want to find a name by its id:
//TAG for debug logs.
String TAG = "db log";
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// find the name by id.
String name = dataSource.findNameById(1);
// log the retrieved name wit id:1.
Log.i(TAG, "retrieved name:" + name);
// close the database.
dataSource.close();
Finally if you want to delete a name:
// create the dataSource object
// "this" refers to the activity.
DataSource dataSource = new DataSource(this);
// open the dataBase
dataSource.open();
// delete the given name
dataSource.deleteName("Amy");
// close the database.
dataSource.close();
That's it.
This is a basic structure for creating databases in Android, as you can see, you can add other tables and columns, easily by adding your own code to the helper class and your own methods to use them in the DataSource class.
Try this
package ir.itstuff.SQLite;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
(EditText) fName = (EditText)findViewById(R.id.editText1);
(EditText) sName = (EditText)findViewById(R.id.editText2);
(Button) save = (Button)findViewById(R.id.button1);
SQLiteDatabase db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS MyTable(id INTEGER PRIMARY KEY AUTOINCREMENT, FirstName varchar,SecondName varchar);")
//Inserting data from inputs
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String first_name = fName.getText().toString();
String second_name = sName.getText().toString();
String insert_data="INSERT INTO MyTable (FirstName,SecondName) VALUES " + "('" + first_name + "'," + "'" + second_name + "'" + ")";
shoppingListDB.execSQL(insert_data);
Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
Cursor cr=shoppingListDB.rawQuery("SELECT * FROM MyTable;", null);
if (cr.moveToFirst()){
do{
String name = cr.getString(cr.getColumnIndex("FirstName"));
}
while (cr.moveToNext());
Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show;
}
cr.close();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Sqlite column id is not unique

below is my code i just want to display the data i inserted in the sqlite database to a text view but i have this error saying that the id is not unique.
package com.example.sqlitetest;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class Main extends Activity {
TextView scrName, fName;
Button go;
SQLiteDatabase db;
String screenName, fullName;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = openOrCreateDatabase("MyDataBase", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE if not exists MyTable(ScreenName Varchar, FullName Varchar, id int(3) PRIMARY KEY);");
db.execSQL("Insert into MyTable VALUES('joff', 'tiquez', 1);");
cursor = db.rawQuery("Select * from MyTable", null);
cursor.moveToFirst();
scrName = (TextView) findViewById(R.id.scrName);
fName = (TextView) findViewById(R.id.fName);
while(cursor.isAfterLast() == false){
//retrieving the data from sqlite (im not sure if im doing it right)
String screenname = cursor.getString(cursor.getColumnIndex("ScreenName"));
String fullname = cursor.getString(cursor.getColumnIndex("FullName"));
//this are the textview
scrName.setText(screenname);
fName.setText(fullname);
cursor.moveToNext();
}
db.close();
}
}
this is my whole java code. thanks :)
Well I think this project works fine when you run it first time. When you run it second time it gives error because id is your primary key and the row with the id 1 has been already inserted to your database.
To get rid of errors either :
1) uninstall the app and run it again
2) Don't make id as primary key
3) Catch the exception and handle it yourself
Might I suggest an alternative to this. What you can do is make the id column autoincrement as well while still keeping that column as primary key
EDIT:-
Also I have some other suggestions for you:-
db.execSQL("Insert into MyTable VALUES('joff', 'tiquez', 1);");
you can user ContentValues instead
while(cursor.isAfterLast() == false){
could be replaced with while(!cursor.isAfterLast()){. Looks cleaner this way.
Or you could directly replace while(cursor.isAfterLast() == false){ with while(cursor.moveToNext()){ and can remove out cursor.moveToNext(); from the while block.
Happy Coding!!!

Switching from TextView to ListView in Android

So, I've been following this Vogella ContentProvider tutorial sent to me by a friend, and if you look at the end of section 6.3 you'll see that he says:
If you run this application the data is read from the ContentProvider of the People application and displayed in a TextView. Typically you would display such data in a ListView.
Since I'm new to working with android (and programming in general), I just changed the TextView tag in the main.xml to ListView, and as expected, when I run the app in the emulator, it crashes.
On-demand code:
XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/contactview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Java File:
package de.vogella.android.contentprovider;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
public class ContactsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
TextView contactView = (TextView) findViewById(R.id.contactview);
Cursor cursor = getContacts();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
contactView.append("Name: ");
contactView.append(displayName);
contactView.append("\n");
}
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
}
I'm sure I'm doing something wrong, can someone point me in the right direction or tell me how to switch it from TextView to ListView?
Also, this is unrelated, but I downloaded the adt bundle and sometimes it doesn't generate the R.java file correctly, it doesn't make any changes to the R.java file and leaves it as the default one that gets generated when you make any new android project, any ideas why?
Note: You don't have to answer this question to get your answer accepted.

Getting the Relationship contact field on Android

I am working with Androids contacts and trying to get particular pieces of data. I can already get emails, phone numbers, their name, etc. However I am having difficulty getting the relationship field.
http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Relation.html
So my goal is: Given a particular userid (from the contact database on Android), figure out their relation field.
This should work. The idea is to connect search in the Data table but use stuff from CommonDataKinds. This is done in where clause ... Data.MIMETYPE == CommonDataKinds.Relation.CONTENT_ITEM_TYPE. This will get you the row with all the Relation stuff.
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Relation;
import android.provider.ContactsContract.Data;
import android.util.Log;
...
public void logCatTheRelation(long contactId){
Uri uri = Data.CONTENT_URI;
String where = String.format(
"%s = ? AND %s = ?",
Data.MIMETYPE,
Relation.CONTACT_ID);
String[] whereParams = new String[] {
Relation.CONTENT_ITEM_TYPE,
Long.toString(contactId),
};
String[] selectColumns = new String[]{
Relation.NAME,
// add additional columns here
};
Cursor relationCursor = this.getContentResolver().query(
uri,
selectColumns,
where,
whereParams,
null);
try{
if (relationCursor.moveToFirst()) {
Log.d("gizm0", relationCursor.getString(
relationCursor.getColumnIndex(Relation.NAME)));
}
Log.d("gizm0", "sadly no relation ... ");
}finally{
relationCursor.close();
}
}

Categories

Resources