I want to add SQLite database value to ListView if record exists, but I'm only getting text from EditText.
Here's what I'm doing
Code from databaseHelper Class
public String ifExistIn(String stationName) {
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
try {
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null));
return stationName;
}
}
Code from activity class
public View.OnClickListener searchStation = new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
String searchString= searchText.getText().toString();
dbHelper.ifExistIn(searchString);
list.add(searchString);
arrayAdapter= new ArrayAdapter<String>(SearchAndReview.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
};
Probably a few mistakes here but from what I can see you can try this:
public String ifExistIn(String stationName) {
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null);
c.moveToFirst();
return c.getString(c.getColumnIndex("stationName"));
}
You have to get the result of the Cursor and interpret it then return it AS String stationName.
And this:
public View.OnClickListener searchStation = new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
String searchString= searchText.getText().toString();
String usethis = dbHelper.ifExistIn(searchString);
list.add(usethis);
arrayAdapter= new ArrayAdapter<String>(SearchAndReview.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
};
You're getting searchString and putting it into your list and not doing anything with the result of your query. You need to assign the result of your query somewhere then use it. Or actually just directly use it in the insert like:
list.add(dbHelper.ifExistsIn(searchString);
Change your method like this:
public String ifExistIn(String stationName){
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
try{
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null))
return c.getString(c.getColumnIndex("columnName"));
}
}
You need to extract data from cursor object. Now you are returning a same value which you are passing.
Related
Main:
ColegiListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ColegDataEditActivity.class);
intent.putExtra("Id", Integer.parseInt(Long.toString(id)));
Log.i("Id",id+"");
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(MainActivity.this).toBundle());
}
});
DATABASE HELPER:
public Cursor getSpecificData(int id){
SQLiteDatabase db = this. getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM "+ TableName + " WHERE ID ="+id, null);
return data;
}
SECOND ACTIVITY:
Intent intent = getIntent();
int id =intent.getIntExtra("Id",0);
Cursor data = mDatabase.getSpecificData(id);
Hi! I am a beginner with SQL and I don't know what I did wrong. I have a database with multiple columns and I need to get some data from it so then I can put those values in some TextViews. The problem is that the data I need needs to be a single row with the specific id from an item from a ListView (yeah, I now about row id, I solved that problem). Any ideas why isn't it working?
Your Database Helper
public Cursor getSpecificData(int id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM "+ TableName + " WHERE ID = "+id;
Cursor res = db.rawQuery(query, null);
return res;
}
In Activity make a setViewsfunction
public void setViews() {
Cursor cursor = mDatabase.getSpecificData(id);
try {
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
textview1.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_1_NAME)));
textview2.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_2_NAME)));
//and so on
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
I am quite new Android Development and figured I should start by trying to create a simple ToDo List App using SQLite. I have all of the basic functionality in place: adding, updating, and deleting tasks. However, I am adding, updating, and deleting by the title of the task, rather than by the ID. This creates problems with duplicate tasks (e.g. tasks of the same name are deleted simultaneously). After much internet search, I still cannot find a way to do this. I would appreciate any help offered!
Here's my code:
public class TaskDbHelper extends SQLiteOpenHelper {
public TaskDbHelper(Context context) {
super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " ( " +
TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TaskContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL, " +
TaskContract.TaskEntry.COL_TASK_DATE + " DATE);";
sqLiteDatabase.execSQL(createTable);
}
}
Activity where tasks are shown
public class ShowTaskActivity extends AppCompatActivity {
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
mHelper = new TaskDbHelper(this);
mTaskListView = (ListView) findViewById(R.id.list_todo);
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase sqLiteDatabase = mHelper.getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(
TaskContract.TaskEntry.TABLE, // Name of the table to be queried
new String[]{ // Which columns are returned
TaskContract.TaskEntry._ID,
TaskContract.TaskEntry.COL_TASK_TITLE,
TaskContract.TaskEntry.COL_TASK_DATE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int index = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(index));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
task, // What view to use for the items
R.id.task_title, // Where to put the string of data
taskList); // Where to get the data
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
sqLiteDatabase.close();
}
// TODO: Change to delete by ID, not name
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = taskTextView.getText().toString();
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
TaskContract.TaskEntry.TABLE, // Where to delete
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?", // Boolean check
new String[]{task}); // What to delete
sqLiteDatabase.close();
updateUI();
}
}
Task adding Code
public void addTask(String task, String date) {
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
contentValues.put(TaskContract.TaskEntry.COL_TASK_DATE, date);
sqLiteDatabase.insertWithOnConflict(
TaskContract.TaskEntry.TABLE,
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE);
sqLiteDatabase.close();
}
String rowId; //Set your row id here
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
TaskContract.TaskEntry.TABLE, // Where to delete
KEY_ID+" = ?",
new String[]{rowId}); // What to delete
sqLiteDatabase.close();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",new String[]{Long.toString(id)} );
db.close();
You can try this method to delete By id
public void deleteData(String tableName, Integer id) {
try {
if (mWritableDB != null) {
mWritableDB.execSQL("delete from " + tableName + " Where id = " + id);
}
} catch (Exception _exception) {
_exception.printStackTrace();
}
}
Long time lurker - first post:
Problem: When I click an imagebutton (basically just checkboxes) they will update my database row correctly and change the image to the proper boolean. However when I click them again - it does not re-update and gives off the same message.
What I think the problem is: I am rather new to Android but I'm pretty sure while my database is updating correctly my bindview variables are not?
My Cursor Adapter BindView:
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
final String id = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_ID));
final String name2 = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_NAME));
final String gift = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_GIFT));
final String specs = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_SPECIFICS));
final String store = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_STORE));
final String url = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_URL));
final String status = cursor.getString(cursor.getColumnIndex(DBHELPER.WISHLIST_COLUMN_STATUS));
ImageButton checkBoxImage = (ImageButton) view.findViewById(R.id.ID_ROW_CHECKBOX);
if(status.equals("true"))
{
checkBoxImage.setImageResource(R.drawable.icon_yes);
} else {
checkBoxImage.setImageResource(R.drawable.icon_no);
}
checkBoxImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(status.equals("true"))
{
ContentValues values = new ContentValues();
values.put(DBHELPER.WISHLIST_COLUMN_NAME, name2);
values.put(DBHELPER.WISHLIST_COLUMN_GIFT, gift);
values.put(DBHELPER.WISHLIST_COLUMN_SPECIFICS, specs);
values.put(DBHELPER.WISHLIST_COLUMN_STORE, store);
values.put(DBHELPER.WISHLIST_COLUMN_URL, url);
values.put(DBHELPER.WISHLIST_COLUMN_STATUS, "false");
DBHELPER dbhelper = new DBHELPER(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
db.update(DBHELPER.WISHLIST_TABLE_NAME, values,"_ID " + "='" + id + "'", null);
Message.message(context, "FALSE UPDATED");
ImageButton checkBoxImage = (ImageButton) v.findViewById(R.id.ID_ROW_CHECKBOX);
checkBoxImage.setImageResource(R.drawable.icon_no);
db.close();
} else {
DBHELPER dbhelper = new DBHELPER(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHELPER.WISHLIST_COLUMN_NAME, name2);
values.put(DBHELPER.WISHLIST_COLUMN_GIFT, gift);
values.put(DBHELPER.WISHLIST_COLUMN_SPECIFICS, specs);
values.put(DBHELPER.WISHLIST_COLUMN_STORE, store);
values.put(DBHELPER.WISHLIST_COLUMN_URL, url);
values.put(DBHELPER.WISHLIST_COLUMN_STATUS, "true");
ImageButton checkBoxImage = (ImageButton) v.findViewById(R.id.ID_ROW_CHECKBOX);
checkBoxImage.setImageResource(R.drawable.icon_yes);
System.out.println("BEFORE : " + status);
db.update(DBHELPER.WISHLIST_TABLE_NAME, values,"_ID " + "='" + id + "'", null);
Message.message(context, "TRUE UPDATED");
db.close();
}
}
});
What I have tried: So I click an image and it'll go from "checked" to "unchecked" or visa versa however only allows it once unless I reload the list.
What I've tried: Requery kept coming up but that is now considered outdated and to be avoided. I saw a few posts talking about swapping out the query for a new one but I kept getting a null error so I am unsure if that is the answer and I am just misunderstanding something or what.
Thanks, appreciate you guys.
if statement inside of OnClickListener is not checking with the latest value of status column. You need to read it again inside of OnClickListener. Change code like this:
checkBoxImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHELPER dbhelper = new DBHELPER(context);
SQLiteDatabase db = dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
String[] columns = new String[]{DBHELPER.WISHLIST_COLUMN_NAME, DBHELPER.WISHLIST_COLUMN_GIFT, DBHELPER.WISHLIST_COLUMN_SPECIFICS, DBHELPER.WISHLIST_COLUMN_STORE, DBHELPER.WISHLIST_COLUMN_URL, DBHELPER.WISHLIST_COLUMN_STATUS};
Cursor cursor2 = db.query(DBHELPER.WISHLIST_TABLE_NAME, columns, null, null, null, null, null);
String status2 = cursor2.getString(cursor2.getColumnIndex(DBHELPER.WISHLIST_COLUMN_STATUS));
if("true".equals(status2)) {
values.put(DBHELPER.WISHLIST_COLUMN_NAME, name2);
values.put(DBHELPER.WISHLIST_COLUMN_GIFT, gift);
values.put(DBHELPER.WISHLIST_COLUMN_SPECIFICS, specs);
values.put(DBHELPER.WISHLIST_COLUMN_STORE, store);
values.put(DBHELPER.WISHLIST_COLUMN_URL, url);
values.put(DBHELPER.WISHLIST_COLUMN_STATUS, "false");
db.update(DBHELPER.WISHLIST_TABLE_NAME, values,"_ID " + "='" + id + "'", null);
Message.message(context, "FALSE UPDATED");
ImageButton checkBoxImage = (ImageButton) v.findViewById(R.id.ID_ROW_CHECKBOX);
checkBoxImage.setImageResource(R.drawable.icon_no);
} else {
values.put(DBHELPER.WISHLIST_COLUMN_NAME, name2);
values.put(DBHELPER.WISHLIST_COLUMN_GIFT, gift);
values.put(DBHELPER.WISHLIST_COLUMN_SPECIFICS, specs);
values.put(DBHELPER.WISHLIST_COLUMN_STORE, store);
values.put(DBHELPER.WISHLIST_COLUMN_URL, url);
values.put(DBHELPER.WISHLIST_COLUMN_STATUS, "true");
ImageButton checkBoxImage = (ImageButton) v.findViewById(R.id.ID_ROW_CHECKBOX);
checkBoxImage.setImageResource(R.drawable.icon_yes);
System.out.println("BEFORE : " + status2);
db.update(DBHELPER.WISHLIST_TABLE_NAME, values,"_ID " + "='" + id + "'", null);
Message.message(context, "TRUE UPDATED");
}
db.close();
}
});
The following code should be placed inside of the onClick method:
if(status.equals("true"))
{
checkBoxImage.setImageResource(R.drawable.icon_yes);
} else {
checkBoxImage.setImageResource(R.drawable.icon_no);
}
By the way, your code should be cleaner. The declaration of values must be outside the if statement
I have some sort of an issue and I'd really appreciate it, if
you could help me.
Problem: I want to take Data from a SQLite Database and display it in
a Listview or a Gridview, either way.
I watched a tutorial and tried to follow the rules and the idea behind it,
with copying the source code and changing the code piece by piece for my
own purpose. Strangely, the code I'm having issues with works in the tutorial
code, and also in another class in my project, but refuses to work in the
recent file..
So, this is the oncreate of the working file:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_list);
mem_op = new Member_Operations(this);
mem_op.open();
List values = mem_op.getAllMembers();
et = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
gv = (GridView) findViewById(R.id.gv);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
gv.setAdapter(adapter);
} // oncreate
and this is the related super-class:
public class Member_Operations {
public DBHelper_Members db_helper;
private SQLiteDatabase database;
private String [] MEMBER_TABLE_COLUMNS = { db_helper.MEMBERS_COLUMN_ID,db_helper.MEMBERS_COLUMN_NAME,db_helper.MEMBERS_COLUMN_PERMISSION};
public Member_Operations(Context context)
{
db_helper = new DBHelper_Members(context);
}
public void open() throws SQLException{
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Member addMember(String name, String permission){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.MEMBERS_COLUMN_NAME, name);
contentValues.put(db_helper.MEMBERS_COLUMN_PERMISSION,permission);
long MemID = database.insert(db_helper.MEMBER_TABLE, null, contentValues);
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,db_helper.MEMBERS_COLUMN_ID + " = " +
+ MemID, null,null,null,null);
cursor.moveToFirst();
Member newComment = parseMember(cursor);
cursor.close();
return newComment;
}
public void deleteMember(Member mem){
long id = mem.getID();
SQLiteDatabase db = db_helper.getWritableDatabase();
db.delete(db_helper.MEMBER_TABLE, db_helper.MEMBERS_COLUMN_ID + " = " + id,
null);
}
public List getAllMembers(){
List members = new ArrayList();
Cursor cursor = database.query(db_helper.MEMBER_TABLE,
MEMBER_TABLE_COLUMNS,null,null,null,null,null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Member member = parseMember(cursor);
members.add(member);
cursor.moveToNext();
}
cursor.close();
return members;
}
private Member parseMember(Cursor cursor){
Member member = new Member();
member.setID(cursor.getInt(0));
member.setName(cursor.getString(1));
member.setPermission(cursor.getString(2));
return member;
}
This is the one refusing to work:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kal_op = new Kalender_Operations(this);
kal_op.open();
List values = kal_op.getAllDays();
ArrayAdapter<Date> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, values);
// here i tried, unlike the first one, to add the Type(Date).
// But either way it doesn't work.
GridView gv = (GridView) findViewById(R.id.gv);
ListActivity la = new ListActivity();
la.setListAdapter(adapter);
}
And its super-class:
public class Kalender_Operations {
SQLiteDatabase database;
DBHelper db_helper;
String [] DATES_TABLE_COLUMNS = { db_helper.JANUARY_COLUMN_ID,
db_helper.JANUARY_COLUMN_DAY,db_helper.JANUARY_COLUMN_EVENT};
public Kalender_Operations(Context context)
{
db_helper = new DBHelper(context);
}
public void open() throws SQLException {
database = db_helper.getWritableDatabase();
}
public void close() {
db_helper.close();
}
public Date addDate (String day, String event){
ContentValues contentValues = new ContentValues();
contentValues.put(db_helper.JANUARY_COLUMN_DAY, day);
contentValues.put(db_helper.JANUARY_COLUMN_EVENT, event);
long DateID = database.insert(db_helper.JANUARY_TABLE,null,contentValues);
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, db_helper.JANUARY_COLUMN_ID
+ " = " + DateID,null,null,null,null);
cursor.moveToFirst();
Date newComment = parseDate(cursor);
cursor.close();
return newComment;
}
public void showDetails(int i, Context context){
Intent intent = new Intent(context, Test_Intent.class);
intent.putExtra("Position", i);
intent.putExtra("Month", db_helper.JANUARY_TABLE);
intent.putExtra("Year", db_helper.JANUARY_YEAR);
context.startActivity(intent);
}
public List getAllDays(){
List Dates = new ArrayList();
Cursor cursor = database.query(db_helper.JANUARY_TABLE,
DATES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Date date = parseDate(cursor);
Dates.add(date);
cursor.moveToNext();
}
cursor.close();
return Dates;
}
public Date parseDate(Cursor cursor){
Date date = new Date();
date.setID(cursor.getInt(0));
date.setDay(cursor.getString(1));
date.setEvent(cursor.getString(2));
return date;
}
}
Please help me. I really want to continue learning, but I spent a lot of time now trying to figure out why one works, the other one doesn't..
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);
}