Refreshing my ListView within my Cursor Adapter? - java

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

Related

How do I delete by ID in SQLite?

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();
}
}

Copy and display data from one sqlite table to another at runtime

I am trying to make an android application that allows the user to create a custom workout list from an already existing list of workouts. I decided to create an sqlite database to accomplish this task. In my database handler class "DBHandles.java" I have created and populated "Table_Workouts" with all the available workouts in the application. Also in "DBHandles.java" I have created another empty table "Table_User_List" for the purpose of holding specific entries from the "Table_Workouts" table that the user selects. "Table_User_List" needs to be populated at runtime.
public class DBhandles extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Workouts.db";
public static final String TABLE_WORKOUTS = "Workouts";
public static final String TABLE_USER_LIST = "UserWorkouts";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_LINK = "link";
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_WORKOUTS_TABLE = "CREATE TABLE " +
TABLE_WORKOUTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
String CREATE_USER_TABLE ="CREATE TABLE " +
TABLE_USER_LIST + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
db.execSQL(CREATE_WORKOUTS_TABLE);
db.execSQL(CREATE_USER_TABLE);
db.execSQL("INSERT INTO " + TABLE_WORKOUTS + "(name, description, link) VALUES ('Shoulder Press', 'Shoulder PRess description', 'https://www.youtube.com/watch?v=qEwKCR5JCog')");
public void addWorkout(Workout workout) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, workout.getWorkoutName());
values.put(COLUMN_DESCRIPTION, workout.getDescription());
values.put(COLUMN_LINK, workout.getLink());
db.insert(TABLE_USER_LIST, null, values);
} catch (Exception e){
Log.d(TAG, "Error while trying to add");
}
finally{
db.endTransaction();
}
//db.close();
}
public Workout findWorkout(String Workoutname) {
String query = "SELECT * FROM " + TABLE_WORKOUTS
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
workout.setID(Integer.parseInt(cursor.getString(0)));
workout.setWorkoutName(cursor.getString(1));
workout.setDescription((cursor.getString(2)));
workout.setLink(cursor.getString(3));
cursor.close();
} else {
workout = null;
}
db.close();
return workout;
}
public boolean deleteWorkout(String Workoutname) {
boolean result = false;
String query = " SELECT * FROM " + TABLE_USER_LIST
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
workout.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_WORKOUTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(workout.getID()) });
cursor.close();
result = true;
}
db.close();
return result;
}
public ArrayList getAllWorkoutNames (){
return genericGetSQL(TABLE_WORKOUTS, COLUMN_NAME);
}
public ArrayList genericGetSQL(String whichTable, String whichColumn){
ArrayList<String> wrkArray = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(whichTable, new String[]{whichColumn}, null,null, null, null,null);
String fieldToAdd = null;
if(cursor.moveToFirst()){
while(cursor.isAfterLast()==false){
fieldToAdd = cursor.getString(0);
wrkArray.add(fieldToAdd);
cursor.moveToNext();
}
cursor.close();
}
return wrkArray;
}
As you can see I am returning an Arraylist from the DBHandles.class to display the name column of the "Table_Workouts" table. This ArrayList is accessed in my "DisplayAllWorkouts.java" class. The "DiplayAllWorkouts.java" class generates a tablerow for each entry in the "Table_Workouts" table and displays the name column to the user.
public class DisplayAllWorkouts extends AppCompatActivity implements YourListFrag.OnFragmentInteractionListener {
DBhandles db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displayworkoutlist);
yourListFrag = new YourListFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.LinLayDisplayYourList, yourListFrag, "ARG_PARAM1").
commit();
context = this;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText = {"NAME ", " ADD "};
for (String c : headerText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setTextSize(18);
tv.setPadding(5, 5, 5, 5);
tv.setText(c);
rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);
db = yourListFrag.getDb();//new DBhandles(this, null, null, 1);
final ArrayList<String> arrNames = db.getAllWorkoutNames();
final ArrayList<String> arrDesc = db.getAllWorkoutDescription();
final ArrayList<String> arrLink = db.getAllWorkoutsLink();
for (int i = 0; i < arrNames.size(); i++) {
TableRow row = new TableRow(this);
final CheckBox AddBox = new CheckBox(this);
AddBox.setText("ADD");
final TextView nametv = new TextView(this);
//final TextView desctv = new TextView(this);
//final TextView linktv = new TextView(this);
nametv.setTextSize(30);
// desctv.setTextSize(30);
nametv.setText(arrNames.get(i));
//desctv.setText(arrDesc.get(i));
//linktv.setText(arrLink.get(i));
text = nametv.getText().toString();
row.addView(nametv);
row.addView(AddBox);
AddBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
// if(AddBox.isChecked()){
Workout wrk = (db.findWorkout(text));
db.addWorkout(wrk);
yourListFrag.refresh();
// yourListFrag.refresh();
// yourListFrag.refresh(text);
// }
// else{
// db.deleteWorkout(text);
//yourListFrag.delete(nametv.getText().toString());
// yourListFrag.refresh();
// }
}
});
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DisplayAllWorkouts.this, DisplaySingleWorkout.class);
i.putExtra("itemName", nametv.getText());
i.putStringArrayListExtra("everydesc", arrDesc);
i.putStringArrayListExtra("everyname", arrNames);
i.putStringArrayListExtra("everylink",arrLink);
startActivity(i);
}
});
tableLayout.addView(row);
}
}
#Override
public void onFragmentInteraction(int position) {
}
}
My problem is as follows. I want to be able to click on a table row displayed in the "DisplayAllWorkouts.java" class and have the corresponding row in "Table_Workouts" table be copied to the "Table_User_List" table. Once the row is copied I want the name column of "Table_User_List" displayed in "YourListFrag.java" class and inflated in the "DisplayAllWorkouts.java" class.
public class YourListFrag extends Fragment {
private ArrayAdapter<String> arrayAdapter;
private ListView lstView;
public ArrayList<String> holdNamesFromDB;
final DBhandles db = new DBhandles(getContext(), null, null, 1);
public DBhandles getDb(){
return this.db;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_list, container, false);
lstView = (ListView)rootView.findViewById(R.id.lstView);
holdNamesFromDB = db.getAllUserWorkouts();
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, holdNamesFromDB);
lstView.setAdapter(arrayAdapter);
public void refresh(){//String text){
//arrayAdapter.add(text);
// db.getAllUserWorkouts();
// arrayAdapter.notifyDataSetChanged();
holdNamesFromDB = db.getAllUserWorkouts();
//arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, db.getAllUserWorkouts());
arrayAdapter.notifyDataSetChanged();
// arrayAdapter.notifyDataSetChanged();
//
}
I need the fragment to refresh its view everytime a new entry is added to the "Table_User_List" so the user can see every entry of the name column of "Table_User_List" in real time. I put logs in my program and the the flow seemed to successfully reach all the appropriate method calls without throwing an error or crashing. However, my program does not display the entries from Table_User_List in the "YourListFrag.java" class. I don't know if their is a problem copying the row from one sqlite table to the other, displaying and refershing the name column in the fragment or inflating the fragment into "DisplayAllWorkouts.java" class. I have been struggling with this problem for awhile now and I finally decided to reach out to the community that has always been there for me. I have referenced the following sqlite copy data from one table to another
and i can't tell if this approach actually works in my program because nothing is displayed in the fragment. Thank you for your time and effort. I apologize for the lines of code i commented out and posted. I have been trying everything i could think of.

Android why does my checkDB keep giving false?

I'm trying to create a button that switches to one of 2 activities based on whether a database exists. I've made a databasecheckhelper but for some reason it keeps giving out false, even though the database exists.
code on clicking the button:
public void open_my_training(View view) {
Intent intent;
boolean databaseExists = checkDatabase.checkDB(this);
if(databaseExists){
intent = new Intent(this, a.class);
}else{
intent = new Intent(this, b.class);
}
startActivity(intent);
}
the helper
public class checkDatabase {
public static boolean checkDB(Context context) {
File dbFile = context.getDatabasePath("database.db");
return dbFile.exists();
}
}
Can anyone tell me what i'm doing wrong?
edit:
since the code seems to be fine i'll add my code for creating the database:
public void save_training(View view) {
CheckBox box1 = (CheckBox) findViewById(R.id.box1);
CheckBox box2 = (CheckBox) findViewById(R.id.box2);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
String spinner1 = spinner1.getSelectedItem().toString();
createDatabase();
addTraining(box1.isChecked(), box2.isChecked(), spinner1);
}
private void createDatabase() {
try {
trainingDB = this.openOrCreateDatabase("database.sqlite", MODE_PRIVATE, null);
trainingDB.execSQL("CREATE TABLE IF NOT EXISTS table1" + "(id integer primary key," +
"box1 boolean, box2 boolean, + "spinner1 VARCHAR);");
}
private void addTraining(boolean box1Checked, boolean box2Checked, String spinner1) {
trainingDB.execSQL("INSERT INTO table1 (box1, box2, spinner1) VALUES ('"+ box1Checked + "', '" +
box2Checked + "', '" + spinner1 + "');");
}
Replace
File dbFile = context.getDatabasePath("database.sqlite");
instead of
File dbFile = context.getDatabasePath("database.db");

Adding SQLite database value to ListView

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.

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