ListView.getItemAtPosition always return 0 - java

I am creating a contact application that works with SQLite database and I face a problem when I try to pass the id of the contact to another intent to use it in a query.
Here is my code :
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView contactsList;
DbContact dbContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsList = findViewById(R.id.contactList);
dbContact = new DbContact(this);
contactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, update_contact.class);
Contact selected_contact =(Contact) contactsList.getItemAtPosition(i);
Toast.makeText(MainActivity.this, "ths position is " +selected_contact.getId(), Toast.LENGTH_SHORT).show();
/*intent.putExtra("id", selected_contact.getId());
startActivity(intent);*/
}
});
}
}
update_contact.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_contact);
int id = getIntent().getIntExtra("id",0);
db = new DbContact(this);
editName = (EditText) findViewById(R.id.editName);
editPhone = (EditText) findViewById(R.id.editPhone);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
Contact contact = db.getContactById(id);
editName.setText(contact.getName());
editPhone.setText(contact.getPhone());
}
BdContact :
public DbContact(#Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String create_table = "create table "+TABLE_CONTACTS+"("+KEY_ID+" int primary key AUTOINCREMENT, "+KEY_NAME+" varchar(30), "+KEY_PHONE+" varchar(30))";
sqLiteDatabase.execSQL(create_table);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String delete_table = "DROP TABLE IF EXISTS "+TABLE_CONTACTS;
sqLiteDatabase.execSQL(delete_table);
onCreate(sqLiteDatabase);
}
public void addContact(Contact contact){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PHONE, contact.getPhone());
db.insert(TABLE_CONTACTS, null, values);
}
public ArrayList<Contact> getAllContacts(){
ArrayList<Contact> contacts = new ArrayList<>();
String selectAll_query = "select * from "+ TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectAll_query, null);
if(cursor.moveToFirst()){
do{
int id = cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAME));
String phone = cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHONE));
Contact contact = new Contact(id,name, phone);
contacts.add(contact);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return contacts;
}
public Contact getContactById(int id_contact){
Contact contact = null;
SQLiteDatabase db = this.getReadableDatabase();
String select_query = "select * from "+TABLE_CONTACTS+" where id = " + id_contact;
Cursor cursor = db.rawQuery(select_query, null);
if(cursor.moveToFirst()){
int id = cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAME));
String phone = cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHONE));
contact = new Contact(id, name, phone);
}
return contact;
}
I think that the problem is in the database because I suspect the id didn't auto-incremented
Thank you guys for helping me solve this issue

Have you added the position?
listView.getItemAtPosition(position)

Related

cannot populate my activity (DrinkActivity) from SQLite database

I don't know what am I missing that I cannot populate my DrinkActivity from my Database!
here is my SQLiteOpenHelper class :
public class StarbuzzDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "starbuzz"; // the name of our database
private static final int DB_VERSION = 2; // the version of the database
StarbuzzDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
updateMyDatabase(db, 0, DB_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
updateMyDatabase(db, oldVersion, newVersion);
}
private static void insertDrink(SQLiteDatabase db, String name, String description,
int resourceId) {
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name);
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceId);
db.insert("DRINK", null, drinkValues);
}
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 1) {
db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte);
insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam",
R.drawable.cappuccino);
insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter);
}
if (oldVersion < 2) {
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC;");
}
}
}
and the other activity (DrinkCategoryActivity) which leads to DrinkActivity is here :
public class DrinkCategoryActivity extends AppCompatActivity {
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_category);
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
ListView listDrinks = findViewById(R.id.list_drinks);
try {
db = starbuzzDatabaseHelper.getReadableDatabase();
cursor = db.query("DRINK",
new String[]{"_id", "NAME"},
null, null, null, null, null);
SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"NAME"},
new int[]{android.R.id.text1},
0);
listDrinks.setAdapter(listAdapter);
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> listDrinks,
View itemView,
int position,
long id) {
//Pass the drink the user clicks on to DrinkActivity
Intent intent = new Intent(DrinkCategoryActivity.this,
DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINK_ID, (int) id);
startActivity(intent);
}
};
listDrinks.setOnItemClickListener(itemClickListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
cursor.close();
db.close();
}
}
and finally here is DrinkActivity :
public class DrinkActivity extends Activity {
public static final String EXTRA_DRINK_ID = "drinkId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
int drinkId = Objects.requireNonNull(getIntent().getExtras()).getInt("EXTRA_DRINK_ID");
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
try {
SQLiteDatabase db = starbuzzDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query ("DRINK",
new String[] {"NAME", "DESCRIPTION", "IMAGE_RESOURCE_ID"},
"_id = ?",
new String[] {Integer.toString(drinkId)},
null, null,null);
if (cursor.moveToFirst()) {
//Get the drink details from the cursor
String nameText = cursor.getString(0);
String descriptionText = cursor.getString(1);
int photoId = cursor.getInt(2);
//Populate the drink name
TextView name = findViewById(R.id.name1);
name.setText(nameText);
//Populate the drink description
TextView description = findViewById(R.id.description1);
description.setText(descriptionText);
//Populate the drink image
ImageView photo = findViewById(R.id.photo1);
photo.setImageResource(photoId);
photo.setContentDescription(nameText);
}
cursor.close();
db.close();
} catch (SQLException e) {
Toast.makeText(this, "Database unavailable", Toast.LENGTH_LONG).show();
}
}
}
First off the DATABASE_NAME should be name.db, you are missing the extention of the file.
Reference: https://developer.android.com/training/data-storage/sqlite
Another important thing is how to retrieve data from the intent, you should not use:
getIntent().getExtras()).getInt("EXTRA_DRINK_ID")
Instead, once you have the intent, you can directly extract the data in this way:
Intent intent = getIntent();
int extraId = intent.getExtraInt(DrinkActivity.EXTRA_DRINK_ID);

android custom layout for listview of sqlite database

i need to make custom layout for my list view where data source is a sqlite database
when i run this code my output Thus shows (name next to phone) but i need to display output like this (phone under
name)
this is my code
here public class MainActivity extends AppCompatActivity {
AlertDialog.Builder builder;
List<Todo> todos;
MyDataBase db = new MyDataBase(this);
String m,m1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.editText);
final EditText editText1 = (EditText) findViewById(R.id.editText2);
Button button = (Button) findViewById(R.id.button);
ListView listView = (ListView) findViewById(R.id.listView);
todos = db.getallcontacts();
final ArrayAdapter adapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,todos);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m = editText.getText().toString();
m1 = editText1.getText().toString();
db.AddnewContact(new Todo(m, m1));
adapter.add(new Todo(m, m1));
Toast.makeText(getApplicationContext(), "contact saved", Toast.LENGTH_LONG).show();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long rowId) {
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setMessage("you need to delete this contact");
adb.setPositiveButton("delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Todo td = todos.get(position);
db.deleteContact(td);
adapter.remove(td);
}
});
adb.show();
adapter.notifyDataSetChanged();
}
});
listView.setAdapter(adapter);
}
my database calss
here public class MyDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
final String KEY_NAME = "name";
final String KEY_PH_NO = "phone_number";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void AddnewContact (Todo todo)// this method to add new contact
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME,todo.getName());
values.put(KEY_PH_NO, todo.getPhoneNumber());
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
public Todo 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);
cursor.moveToFirst();
Todo contact = new Todo(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
public List<Todo> getallcontacts()
{
List<Todo> contactList = new ArrayList<Todo>();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Todo contact = new Todo();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
public void deleteContact(Todo contact) {
int id = contact.getID();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID
+ " = " + id, null);
db.close();
}
public Cursor fetchAllCountries() {
SQLiteDatabase database = this.getWritableDatabase();
Cursor mCursor = database.query(TABLE_CONTACTS, new String[] {KEY_ID,
KEY_NAME,KEY_PH_NO},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
my todo calss
`enter public class Todo {
//private variables
int _id;
String _name;
String _phone_number;
// Empty constructor
public Todo(){
}
// constructor
public Todo(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Todo(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
#Override
public String toString() {
return _name+" "+_phone_number;
}
}
`

getDatabase called recursively sqlite insert and getReadableDatabase()

I just started with my first App and I am trying to create a table settings, which should contain an entry PIN. after that I want to run the method getPIN() to get the value of this setting.
The problem is, that I get always the error "getDatabase called recursively". As I just started with this, I have no idea how to fix it. I've seen a lot of used to have the same problem, but the solutions doesn't work for me.
Could you please help me to understand what I'm doing wrong.
The contacts table was part of a tutorial I followed before, that´s the reason it's still in there.
Thank you.
This is my Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION =3;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = " contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null ," +
"name text not null, email text not null, pass text not null);";
private static final String TABLE_SETTINGS = "create table settings (id integer primary key not null ," +
"setting text not null, value integer not null);";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null,DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db){
String ssetting = "PIN";
db.execSQL(TABLE_CREATE);
db.execSQL(TABLE_SETTINGS);
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "Select * from settings";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put("id",count);
values.put("setting", ssetting);
values.put("value", 0);
db.insert("settings", null, values);
db.close();
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
String query = "DROP TABLE IF EXISTS"+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
public int insertContact(Contact c){
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "Select * from contacts";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID,count);
values.put(COLUMN_NAME, c.getName());
values.put(COLUMN_EMAIL, c.getEmail());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
return 0;
}
public String searchPass(String uname)
{
db = this.getReadableDatabase();
String query = "select name, pass from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a,b;
b="not found";
if (cursor.moveToFirst()){
do {
a = cursor.getString(0);
b = cursor.getString(1);
if (a.equals(uname)) {
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
db.close();
return b;
}
public int getPIN()
{
db = this.getReadableDatabase();
int pin=1;
String query = "select id, setting, value from settings where setting='PIN'";
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
pin = cursor.getInt(2);
break;
}
while(cursor.moveToNext());
}
db.close();
return pin;
}
}
and the MainActivity
public class MainActivity extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int pin = helper.getPIN();
if (pin==0){
Intent i = new Intent(MainActivity.this, Loginpin.class);
startActivity(i);
}
if (pin==1) {
Intent i = new Intent(MainActivity.this, Setuppin.class);
startActivity(i);
}
//pin = helper.getPIN();
}
public void b_newOnClick(View v) {
if (v.getId() == R.id.blogin)
{
EditText user = (EditText) findViewById(R.id.tfuser);
String su = user.getText().toString();
EditText pass = (EditText) findViewById(R.id.tf_pw);
String spass = pass.getText().toString();
String password = helper.searchPass(spass);
if(spass.equals(password))
{
Intent i = new Intent(MainActivity.this, Welcome.class);
i.putExtra("username", su);
startActivity(i);
}
else{
Toast.makeText(MainActivity.this, "Password incorrect", Toast.LENGTH_LONG).show();
}
}
}
public void onSignClick(View v) {
if (v.getId() == R.id.bsign) {
Intent i = new Intent(MainActivity.this, SignUp.class);
startActivity(i);
}
}
}
Thank you so much.
regards, S
Kilimanscharo
Don't call getWritableDatabase() or getReadableDatabase() from your SQLiteOpenHelper lifecycle methods such as onCreate() or onUpgrade() that are in turn triggered by a call to get...Database(). Instead, use the SQLiteDatabase object that is given as a parameter to these methods.
Specifically, remove this line from your onCreate():
db=this.getWritableDatabase();

ANDROID SQLITE DATABASE insert [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
the database class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name, String phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
the activity class
public class MainActivity extends AppCompatActivity {
Button login;
EditText student_id;
EditText password;
TextView message;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);
login = (Button) findViewById(R.id.button);
student_id = (EditText) findViewById(R.id.student_id);
password = (EditText) findViewById(R.id.password);
message=(TextView)findViewById(R.id.logResult);
message.setText("");
db.insertContact("jon","9595749944","r#hotmail.com","a","usa");
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pass = password.getText().toString();
int id = Integer.parseInt(student_id.getText().toString());
int result= db.numberOfRows();
if (result == 1) {
message.setText("Invalid User");
} else {
message.setText("valid User" );
}
}
});
}
But,When the button is pressed the insertion in not occur and app close
where is the problem?? help?????????????? I want to insert data in database when the app is created how?
your call is outside of the onclick , first try:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.insertContact("jon","9595749944","r#hotmail.com","a","usa");
}
});

Android: How to display string on textview from console

I'm trying to display string on the textview. I'm succesfully able to print it on the console from database, but I'm not able to figure out how to print all the strings on different different textviews. Here is my code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText search;
Button insert;
TextView txt1, txt2, txt3, txt4, txt5;
DatabaseHandler db;
List<History> history;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHandler(this);
search = (EditText) findViewById(R.id.search_word);
insert = (Button) findViewById(R.id.insert);
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
txt3 = (TextView) findViewById(R.id.txt3);
txt4 = (TextView) findViewById(R.id.txt4);
txt5 = (TextView) findViewById(R.id.txt5);
insert.setOnClickListener(this);
history = db.getAllHistory();
}
public void onClick(View v) {
db.addHistory(new History(search.getText().toString(), null));
Toast.makeText(getApplicationContext(),
"Inserted: " + search.getText().toString(), Toast.LENGTH_LONG)
.show();
}
#Override
protected void onStart() {
super.onStart();
List<History> history = db.getAllHistory();
for (History cn : history) {
String log = "Search Strings: " + cn.getName();
Log.d("Search Strings: ", log);
}
}
}
This is my activity in which I'm bringing my all database value on onStart() function. Now here I have to set all the data coming from database on the textview. Here is my DabaseHandler class in which I'm taking out each row.
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "historyManager";
private static final String TABLE_HISTORY = "histories";
private static final String KEY_NAME = "history";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "("
+ KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_HISTORY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
void addHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
db.insert(TABLE_HISTORY, null, values);
db.close();
}
History getHistory(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HISTORY, new String[] { KEY_NAME },
"=?", new String[] { String.valueOf(id) }, null, null, null,
null);
if (cursor != null)
cursor.moveToFirst();
History history = new History(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return history;
}
public List<History> getAllHistory() {
List<History> historyList = new ArrayList<History>();
String selectQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
History contact = new History();
contact.setName(cursor.getString(0));
historyList.add(contact);
} while (cursor.moveToNext());
}
return historyList;
}
public int updateHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
return db.update(TABLE_HISTORY, values, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
}
public void deleteHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HISTORY, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
db.close();
}
public int getHistoryCount() {
String countQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
Please help in getting data printed on the textview. On the Log.d I can see all my data coming, one after another. But I'm not able to print all the data.
It's answer for "Thank You for that. Can you tell me how to set the data which I have printed in MainActivity on onStart() method (Log.d("")). If you can give me the code for that, that will be much easier for me."
try this:
List<String> listNames = new ArrayList<String>();//global variable
List<History> history = db.getAllHistory();
for (History cn : history) {
listNames.add(cn.getName());
}
or, if have in History field date try is, after easy will sort:
Map<String, Date> historyMap = new HashMap<String, Date>();
List<History> history = db.getAllHistory();
for (History cn : history) {
historyMap.put(cn.getName, cn.getDate);
}
You need make ListView in which will show your data from DB.Because you have many items datas getting from db.
I suggest to the next version:
In xml file you creat:
<ListView
android:id="#+id/list_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...>
You need create Adapter for your list with next xml resource:
<TextView
android:id="#+id/text_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
In java code:
in onCreate:
ListView list = (ListView) findViewById(R.id.list);
OurAdapter adapter = new OurAdapter(..., List<String> yourListWithName);
list.setAdapter(adapter);
if you want a more detailed description of the code tell me.
For add last item in top you need next, create spec. internal class :
class Holder implements Comparable<Holder> {
String key;
Double value;
public int compareTo(Holder another) {
return another.value.compareTo(value);
}
}
and use him how:
List<this.Holder> listSortforLastInTop = new ArrayList<this.Holder>();
and
for(...){
Holder holder = new Holder();
holder.key=...;
older.value=..;
listSortforLastInTop.add(holder);
}

Categories

Resources