get a single row from table - android-sqlite

These are the ids in my table:
KEY_ID(autoincremented integer primary key) KEY_NAME(text) KEY_PH_NO(text)
1 james 1234567890
2 kristein 6484996755
3 Roen 4668798989
4 Ashlie 6897980909
What I want to know is, how can I get a single record from this table on the basis of unique(KEY_ID), for this i have built a getContact() method like this,
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
And Contact is a class where I have set all the getter and setter method for all attributes.
Please help with complete code.

See if this can help you out..
Assuming your table name is Employee
public String getEmployeeName(String empNo) {
Cursor cursor = null;
String empName = "";
try {
cursor = SQLiteDatabaseInstance_.rawQuery("SELECT EmployeeName FROM Employee WHERE EmpNo=?", new String[] {empNo + ""});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
empName = cursor.getString(cursor.getColumnIndex("EmployeeName"));
}
return empName;
}finally {
cursor.close();
}
}

Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
Assuming you have Entity Class for contact, And then you just call it your method above with this.
Contact singleContact = database.getContact(id);
then call contact entity, Im assuming you have method getter getPhone();
Log.d("Phone Number :" , singleContact.getPhone());

Try this
cursor.moveToPosition(position);
cursor.getString(listaTarefas1.getColumnIndex("Item"))

Related

How to concatenate value in database column on update in Entity Framework

I am trying to add last name on update with first name; first name is already in column but I want on update first name+last name
This is my event handler code
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Record REC = new Record();
REC.ID = Convert.ToInt32(txtID.Text);
int id = REC.ID;
REC.Name= TXTNAME.Text;
String updatedname=REC.Name;
RecordFactory FAC = new RecordFactory();
if (FAC.Update1(id,updatedname))
{
MessageBox.Show("update");
}
else
MessageBox.Show("not");
}
}
This is connection code between handler and query
public bool Update(int id, String name)
{
return rd.Update(id, name);
}
This is query code
AS UPDATE call concatenate last name with first name
before update
public bool Update(int id ,String name)
{
Record REC = red.Records.Where(X => X.ID == id).FirstOrDefault();
if (REC != null)
REC.Name =String.Concat(REC.Name+name);
return red.SaveChanges() >0;
}
To update a record, you need to set the Entity state to modified.
public bool Update(int id ,String name)
{
Record rec= red.Records.Where(x => x.ID == id).FirstOrDefault();
if (rec!= null)
{
rec.Name =String.Concat(REC.Name+name);
db.Entry(rec).State = EntityState.Modified;
return red.SaveChanges() >0;
}
return false;
}
EntityState is defined in Microsoft.Data.Entity namespace. You need to import that namespace to your class.with using Microsoft.Data.Entity statement.

SQLite app won't run at all. Force close message appears

I am creating an app using SQLite.
It crashes before loading.
I fixed all viable errors and since I do not even get a log info, I am having troubles figuring out the error.
Please help.
SQLHelper
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "MediaDB";
// Media table name
private static final String TABLE_MEDIA = "media";
// Media Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TYPE = "type";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";
private static final String[] COLUMNS = {KEY_ID,KEY_TYPE,KEY_TITLE,KEY_AUTHOR};
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create media table
String CREATE_MEDIA_TABLE = "CREATE TABLE media ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TYPE, "+
"title TEXT, "+
"author TEXT )";
// create media table
db.execSQL(CREATE_MEDIA_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older media table if existed
db.execSQL("DROP TABLE IF EXISTS media");
// create fresh media table
this.onCreate(db);
}
//ADD MEDIA
public void addMedia(Media media){
//for logging
Log.d("addMedia", media.toString());
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TYPE, media.getType()); // get title
values.put(KEY_TITLE, media.getTitle()); // get title
values.put(KEY_AUTHOR, media.getAuthor()); // get author
// insert
db.insert(TABLE_MEDIA, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// close
db.close();
}
//GET MEDIA
public Media getMedia(int id){
// get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// build query
Cursor cursor =
db.query(TABLE_MEDIA, // table
COLUMNS, // column names
" id = ?", // selections
new String[] { String.valueOf(id) }, // d. selections args
null, // group by
null, // having
null, // order by
null); // limit
// if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// build media object
Media media = new Media();
media.setId(Integer.parseInt(cursor.getString(0)));
media.setType(cursor.getString(1));
media.setTitle(cursor.getString(2));
media.setAuthor(cursor.getString(3));
//log
Log.d("getMedia("+id+")", media.toString());
// return media
return media;
}
//GET ALL MEDIA
public List<Media> getAllMedia() {
List<Media> medias = new LinkedList<Media>();
// build the query
String query = "SELECT * FROM " + TABLE_MEDIA;
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// go over each row, build media and add it to list
Media media = null;
if (cursor.moveToFirst()) {
do {
media = new Media();
media.setId(Integer.parseInt(cursor.getString(0)));
media.setType(cursor.getString(1));
media.setTitle(cursor.getString(2));
media.setAuthor(cursor.getString(3));
// Add media to media
medias.add(media);
} while (cursor.moveToNext());
}
Log.d("getAllMedia()", medias.toString());
// return media
return medias;
}
//UPDATE
public int updateMedia(Media media) {
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("type", media.getType()); // get title
values.put("title", media.getTitle()); // get title
values.put("author", media.getAuthor()); // get author
// updating row
int i = db.update(TABLE_MEDIA, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(media.getId()) }); //selection args
// close
db.close();
return i;
}
//DELETE
public void deleteMedia(Media media) {
// get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// delete
db.delete(TABLE_MEDIA, //table name
KEY_ID+" = ?", // selections
new String[] { String.valueOf(media.getId()) }); //selections args
// close
db.close();
//log
Log.d("deleteMedia", media.toString());
}
}
Media object class
public class Media {
private int id;
private String type;
private String title;
private String author;
public Media(){}
public Media(String type, String title, String author) {
super();
this.type = type;
this.title = title;
this.author = author;
}
//getters & setters
// getting ID
public int getId(){
return this.id;
}
// setting id
public void setId(int id){
this.id = id;
}
// getting type
public String getType(){
return this.type;
}
// setting title
public void setType(String type){
this.type = type;
}
// getting title
public String getTitle(){
return this.title;
}
// setting title
public void setTitle(String title){
this.title = title;
}
// getting author
public String getAuthor(){
return this.author;
}
// setting author
public void setAuthor(String author){
this.author = author;
}
#Override
public String toString() {
return "Media [id=" + id + ", type=" + type + ",title=" + title + ", author=" + author
+ "]";
}
}
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteHelper db = new MySQLiteHelper(this);
/**
* CRUD Operations
* */
// add Media
db.addMedia(new Media("Book", "Android Application Development Cookbook", "Wei Meng Lee"));
db.addMedia(new Media("Book", "Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));
db.addMedia(new Media("Book", "Learn Android App Development", "Wallace Jackson"));
// get all media
List<Media> list = db.getAllMedia();
// delete one media
db.deleteMedia(list.get(0));
// get all media
db.getAllMedia();
}
}
There's an error in you table creation:
String CREATE_MEDIA_TABLE = "CREATE TABLE media ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TYPE, "+
"title TEXT, "+
"author TEXT )";
TYPE is not a valid SQLlite Data Type.
Please refer to this page: https://www.sqlite.org/datatype3.html
I'd write your table creation as
String CREATE_MEDIA_TABLE = "CREATE TABLE media (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"tyoe TEXT, "+
"title TEXT, "+
"author TEXT)";

android listview with item and sub item not working properly

I have a database which i select 2 strings one as an item other one is description.I am trying to map these 2 strings into a listview item-subitem layout. the following code is what i tried so far.
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> datum = new HashMap<String, String>(2);
SimpleAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2,
new String[] { "item","descr" },
new int[] { android.R.id.text1, android.R.id.text2 });
itemList.setAdapter(adapter);
Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
+ menuid + " AND sub_flag = 1", null, null, null, null);
if (cours.moveToFirst()) {
do {
datum.put("item", cours.getString(cours.getColumnIndex("sub_label")));
datum.put("descr", cours.getString(cours.getColumnIndex("sub_description")));
data.add(datum);
Log.d("testt", datum.toString());
adapter.notifyDataSetChanged();
} while (cours.moveToNext());
}
the problem now it will add 5 entries to the listview with the same values which are the last row selected form the database which is not what. any idea how to fix this ?
EDIT.
after experimenting with it i found that i was overwriting the object datum which end up having the save value for all the entries. the fix was as easy as moving the intializition line for datum into the loop. here is the final code
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
String[] from = new String[] { "rowid", "col_1" };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
Cursor cours = MainActivity.mydb.query("sub_menu", null, "cat_id = "
+ menuid + " AND sub_flag = 1", null, null, null, null);
if (cours.moveToFirst()) {
do {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("rowid",
cours.getString(cours.getColumnIndex("sub_label")));
datum.put("col_1", cours.getString(cours
.getColumnIndex("sub_description")));
data.add(datum);
} while (cours.moveToNext());
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, from, to);
itemList.setAdapter(adapter);
make custom ListView and use CursorAdapter
Here is a good example will help you.

How to retrieve an embedded list of object of Entity?

I have a simple problem storing and retrieving an embedded collection of entity to mongo. I have checked theses question :
how to serialize class? and Mongodb saves list of object
what I understand is to save a list objects the class of that objects must extends ReflactionDBObject. This worked for saving the object, by retrieving it with the embedded collection does not work.
here a simple test show that retrieving embedded entities does not work !
#Test
public void whatWasStoredAsEmbeddedCollectionIsRetrieved2() {
BasicDBObject country = new BasicDBObject();
country.put("name", "Bulgaria");
List<City> cities = Lists.newArrayList(new City("Tarnovo"));
country.put("listOfCities", cities);
DBCollection collection = db().get().getCollection("test_Collection");
collection.save(country);
DBCursor object = collection.find(new BasicDBObject().append("name", "Bulgaria"));
DBObject returnedCity = object.next();
DBObject embeddedCities = (DBObject) returnedCity.get("listOfCities");
System.out.println(embeddedCities);
}
Here is the City Class
class City extends ReflectionDBObject {
String name;
City() {
}
City(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof City)) return false;
City city = (City) o;
if (name != null ? !name.equals(city.name) : city.name != null) return false;
return true;
}
#Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
#Override
public String toString() {
return "City{" +
"name='" + name + '\'' +
'}';
}
}
The out put of the System.out.println statement is [ { "_id" : null }]
Now how can get back the embedded object and the embedded list in it ?
If you do not have a requirement to define your own class City, you can define subdocuments using the BasicDBObjects. I only added the 'name' field to the citySubDoc1 and citySubDoc2, but of course, you can add more fields to these subdocuments.
// Define subdocuments
BasicDBObject citySubDoc1 = new BasicDBObject();
citySubDoc1.put("name", "Tarnovo");
BasicDBObject citySubDoc2 = new BasicDBObject();
citySubDoc2.put("name", "Sofia");
// add to list
List<DBObject> cities = new ArrayList <DBObject>();
cities.add(citySubDoc1);
cities.add(citySubDoc2);
country.put("listOfCities", cities);
collection.save(country);
// Specify query condition
BasicDBObject criteriaQuery = new BasicDBObject();
criteriaQuery.put("name", "Bulgaria");
// Perform the read
DBCursor cursor = collection.find(criteriaQuery);
// Loop through the results
try {
while (cursor.hasNext()) {
List myReturnedListOfCities = (List) cursor.next().get("listOfCities");
System.out.println(myReturnedListOfCities);
}
} finally {
cursor.close();
}

CheckedTextView Behaving Erratically

Has anyone else had a problem with CheckedTextView showing multiple checked items when only 1 is checked? When a CheckedTexView item is clicked, the response from the OnClickListener is to check the entries before and after the clicked item.
Here's the code:
mFriendDoneButton = (Button) findViewById(R.id.doneAddAFriendButton);
mListView = (ListView)findViewById(R.id.contactList);
populateContactList();
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mListView.setItemsCanFocus(false);
mListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int arg2, long arg3) {
int selectedPosition = arg2;
CheckedTextView textView = (CheckedTextView)view.findViewById(R.id.friendEntryText);
String mtext = textView.getText().toString();
Log.i("AddAFriendActivity", "Click on position "+selectedPosition);
Toast t = new Toast(AddAFriendActivity.this);
t = Toast.makeText(AddAFriendActivity.this, "Clicked on " + arg2+mtext+arg3, Toast.LENGTH_LONG);
t.show();
}
});
private void populateContactList() {
// Build adapter with contact entries
Cursor cursor = getContacts();
String[] fields = new String[] {
ContactsContract.Data.DISPLAY_NAME
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.friend_entry, cursor, fields, new int[] {R.id.friendEntryText});
mListView.setAdapter(adapter);
}
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
String selection = null;
String[] selectionArgs = null;
String sortOrder = null;
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
The XML is as follows:
Found the problem... textView needs to be declared as a field, otherwise the managedQuery results cycle through the onClickListener.