how to open item in search listview - java

Hi I have a search list in which I want to click on any item. By clicking a particular position, item on that position should open. I have done the following :
public List<DBSearch> searchByName(String name){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from biography where name like '%" + name + "%'", null);
List<DBSearch> dbsearch = new ArrayList<>();
while (cursor.moveToNext()){
DBSearch sea = new DBSearch();
sea.setId(cursor.getLong(0));
sea.setName(cursor.getString(1));
sea.setImage(cursor.getBlob(2));
sea.setComment(cursor.getString(3));
dbsearch.add(sea);
}
cursor.close();
db.close();
return dbsearch;
}
and this is my activity :
private void search(String name) {
persons = (ArrayList<DBSearch>) databaseAdapter.searchByName(name);
SearchAdapter personListAdapter = new SearchAdapter(persons, this);
personListView.setAdapter(personListAdapter);
personListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Intent i = new Intent(getBaseContext(),AWDetailsActivity.class);
String my_id = persons.get(position).getId("id").toString();
i.putExtra("id", my_id);
startActivity(i);
}
}
);
}
Thank you very much.

Related

cursor adapter getview problem at position 0

I'm working o a calendar app with events and I save them in MyDatabaseHelpe, the events are shown in a listview by day, my problem is that in onitemclicked, I want the data of the event to be shown in an AlertDialog, I use a CursorAdapter class and when i am trying to show the data, the data that are position 0, arent shown and show the data that are in position 1.
I've tried many approches of the way the position could fit in function, and i search many StackOverFlows(and more sites) subjects to find a solution.
**The delete row function works perfectly without problem.
Any ideas or approches would be helpuful!!
`
Method for listview onitemclicked
`private void DialogClickedItemAndDelete()
{
monthListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View view1 = getLayoutInflater().inflate(R.layout.show_event_from_listview, null);
Object listItem = monthListView.getItemAtPosition(position).toString();
EventCursorAdapter EC = new EventCursorAdapter(MainActivity.this, myDB.readAllData());
Cursor cursor = EC.getCursor();
cursor.moveToPosition(position);
View view2 = EC.getView(position,view1,parent);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(view2).
setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String id_row = hourAdapter.getItem(position).getEvents().get(0).getId();
myDB.deleteOneRow(id_row);
AllEventsList.reloadActivity(MainActivity.this);
}
}).setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
AllEventsList.reloadActivity(MainActivity.this);
}
});
builder.show();
}
});
}
`
``
``
#CursorAdapter Class
package com.example.calendarcapital;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class EventCursorAdapter extends CursorAdapter {
public EventCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
c.moveToFirst();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.show_event_from_listview, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView id_lv_tv = (TextView) view.findViewById(R.id.id_lv_tv);
TextView title_lv_tv = (TextView) view.findViewById(R.id.title_lv_tv);
TextView comment_lv_tv = (TextView) view.findViewById(R.id.comment_lv_tv);
TextView date_lv_tv = (TextView) view.findViewById(R.id.date_lv_tv);
TextView time_lv_tv = (TextView) view.findViewById(R.id.time_lv_tv);
String id_row = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("event_title"));
String comment = cursor.getString(cursor.getColumnIndexOrThrow("event_comment"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("event_date"));
String time = cursor.getString(cursor.getColumnIndexOrThrow("event_time"));
id_lv_tv.setText(id_row);
title_lv_tv.setText(title);
comment_lv_tv.setText(comment);
date_lv_tv.setText(date);
time_lv_tv.setText(time);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
}
#MyDatabaseHelper Class
public class MyDatabaseHelper extends SQLiteOpenHelper {
private Context context;
private static final String DATABASE_NAME = "CalendarCapital.db";
private static final int DATABASE_VERSION =1;
private static final String TABLE_NAME ="my_events_db";
public static final String COLUMN_ID ="_id";
private static final String COLUMN_TITLE = "event_title";
private static final String COLUMN_COMMENT = "event_comment";
private static final String COLUMN_DATE = "event_date";
private static final String COLUMN_TIME = "event_time";
MyDatabaseHelper(#Nullable Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TITLE + " TEXT, " +
COLUMN_COMMENT + " TEXT, " +
COLUMN_DATE + " TEXT, " +
COLUMN_TIME + " TEXT);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addEvent(String title, String comment, LocalDate date, LocalTime time)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITLE, title);
cv.put(COLUMN_COMMENT, comment);
cv.put(COLUMN_DATE, String.valueOf(date));
cv.put(COLUMN_TIME, String.valueOf(time));
long result = db.insert(TABLE_NAME, null, cv);
if (result== -1)
{
Toast.makeText(context, "Data Failed", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "Data Added Successfully", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if (db != null)
{
cursor = db.rawQuery(query, null);
}
return cursor;
}
void updateData(String row_id, String title, String comments, String date, String time)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITLE,title);
cv.put(COLUMN_COMMENT,comments);
cv.put(COLUMN_DATE, String.valueOf(date));
cv.put(COLUMN_TIME, String.valueOf(time));
long result = db.update(TABLE_NAME,cv,"_id=?",new String[]{row_id});
if (result == -1)
{
Toast.makeText(context, "Failed to Update", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "Successfully Update", Toast.LENGTH_SHORT).show();
}
}
void deleteOneRow(String row_id)
{
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_NAME, "_id=?", new String[]{row_id});
if (result == -1)
{
Toast.makeText(context, "Failed to Delete.", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(context, "Deleted Successfully.", Toast.LENGTH_SHORT).show();
}
}
void deleteAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME);
}
}
Another approch I tried is this
View view2 = EC.getView(position,view1,parent);
View view3 = monthListView.getChildAt(position - monthListView.getFirstVisiblePosition());
View view4 = EC.newView(EC.mContext,EC.mCursor,parent);
View view5=hourAdapter.getView(position,view1,parent);
UPDATE: 27/12/2022
I noticed that my problem is maybe because i sort my list.
private void setMonthAdapter() {
hourAdapter = new HourAdapter(getApplicationContext(), AllEventsList.hourEventListFromDatabase(getApplicationContext(), myDB));
hourAdapter.sort((o1, o2) -> o1.events.get(0).getDate().compareTo(o2.events.get(0).getDate()));
hourAdapter.sort((o1, o2) -> o1.events.get(0).getTime().compareTo(o2.events.get(0).getTime()));
monthListView.setAdapter(hourAdapter);
}
I can retrieve the values but with the wrong order, in my listview my events are sorted by time and date, when i click item in position 0 it show me the item in position 1 and versa.
**SOLUTION: **
The problem was that after sorting list i didn't called notifyDataChanged();
Furthermore I made in my CursorAdapter Class a method to retrieve fields via cursor.
So in cursor adapter i made this:
public View setAllFields(View view,String id, String title, String comment, String date, String time)
{
TextView id_lv_tv = (TextView) view.findViewById(R.id.id_lv_tv);
TextView title_lv_tv = (TextView) view.findViewById(R.id.title_lv_tv);
TextView comment_lv_tv = (TextView) view.findViewById(R.id.comment_lv_tv);
TextView date_lv_tv = (TextView) view.findViewById(R.id.date_lv_tv);
TextView time_lv_tv = (TextView) view.findViewById(R.id.time_lv_tv);
id_lv_tv.setText(id);
title_lv_tv.setText(title);
comment_lv_tv.setText(comment);
date_lv_tv.setText(date);
time_lv_tv.setText(time);
return view;
}
And my main onitemclick now is like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
View view1 = getLayoutInflater().inflate(R.layout.show_event_from_listview, null);
// private ArrayList MlaDats = new ArrayList();
HourEvent myEvent = (HourEvent) monthListView.getAdapter().getItem(position);
String myEventId= myEvent.getEvents().get(0).getId();
String myTitle = myEvent.getEvents().get(0).getName();
String myComment = myEvent.getEvents().get(0).getComment();
String myDate = String.valueOf(myEvent.getEvents().get(0).getDate());
String myTime = String.valueOf(myEvent.getEvents().get(0).getTime());
View viewFinal;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
viewFinal = CA.setAllFields(view1,myEventId,myTitle,myComment,myDate,myTime);
// viewFinal = SD.getView(position, view1, parent);
builder.setView(viewFinal).
CLOSED
I'm working o a calendar app with events and I save them in MyDatabaseHelpe, the events are shown in a listview by day, my problem is that in onitemclicked, I want the data of the event to be shown in an AlertDialog, I use a CursorAdapter class and when i am trying to show the data, the data that are in position 0, arent shown and show the data that are in position 1.
cursor adapter getview problem at position 0
I've tried many approches of the way the position could fit in function, and i search many StackOverFlows(and more sites) subjects to find a solution.
**The delete row function works perfectly without problem.
Any ideas or approches would be helpuful!!
**SOLUTION: **
The problem was that after sorting list i didn't called notifyDataChanged();
Furthermore I made in my CursorAdapter Class a method to retrieve fields via cursor.
So in cursor adapter i made this:
public View setAllFields(View view,String id, String title, String comment, String date, String time)
{
TextView id_lv_tv = (TextView) view.findViewById(R.id.id_lv_tv);
TextView title_lv_tv = (TextView) view.findViewById(R.id.title_lv_tv);
TextView comment_lv_tv = (TextView) view.findViewById(R.id.comment_lv_tv);
TextView date_lv_tv = (TextView) view.findViewById(R.id.date_lv_tv);
TextView time_lv_tv = (TextView) view.findViewById(R.id.time_lv_tv);
id_lv_tv.setText(id);
title_lv_tv.setText(title);
comment_lv_tv.setText(comment);
date_lv_tv.setText(date);
time_lv_tv.setText(time);
return view;
}
And my main onitemclick now is like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { View view1 = getLayoutInflater().inflate(R.layout.show_event_from_listview, null); // private ArrayList MlaDats = new ArrayList(); HourEvent myEvent = (HourEvent) monthListView.getAdapter().getItem(position);
String myEventId= myEvent.getEvents().get(0).getId();
String myTitle = myEvent.getEvents().get(0).getName();
String myComment = myEvent.getEvents().get(0).getComment();
String myDate = String.valueOf(myEvent.getEvents().get(0).getDate());
String myTime = String.valueOf(myEvent.getEvents().get(0).getTime());
View viewFinal;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
viewFinal = CA.setAllFields(view1,myEventId,myTitle,myComment,myDate,myTime);
// viewFinal = SD.getView(position, view1, parent);
builder.setView(viewFinal).

How implementation SQLite Join using spinner at Android Studio to get id from tables

I've created 2 tables within an SQLite database, stok and sales
at DatabaseHelper.java
Create table stok
String tbStok = "CREATE TABLE stok(id_stok INTEGER PRIMARY KEY AUTOINCREMENT, waktu_stok DATETIME, id_sales INTEGER, stok INTEGER, FOREIGN KEY id_sales REFERENCES sales(id_sales)";
Create table sales
String tbSales = "CREATE TABLE sales(id_sales INTEGER PRIMARY KEY AUTOINCREMENT, nama VARCHAR, kodesales VARCHAR, username VARCHAR, password VARCHAR, level INTEGER)";
Create List Data from SQLite
public List<String> getSpinnerSales(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + "sales";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0));
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
Display on Spinner
private void loadSpinnerSales() {
// database handler
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getSpinnerSales();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spsales.setAdapter(dataAdapter);
}
Test if spinner selected
spsales.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String label = parent.getItemAtPosition(position).toString();
Log.d("label:", label);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
I need id_sales to put values and save to other tables SQLite, but the spinner must display the name of sales.
the best way is to use custom adapter then
you can pass List of objects (in your case is"list of sales id and name" )to the adapter not just a List of strings,
then on item selected you will get the selected object
then you can get whatever you need id or name
you can follow this link to make custom adapter
https://abhiandroid.com/ui/custom-spinner-examples.html
I Solve this problems with edited the code
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(0)+cursor.getString(1));
} while (cursor.moveToNext());
}
And at spinner on item selected manipulate with substring
spsupir.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String label = parent.getItemAtPosition(position).toString();
String ids = String.valueOf(label).substring(0,1);
Log.d("label:", ids);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Code edited
String label = parent.getItemAtPosition(position).toString();
String ids = String.valueOf(label).substring(0,1);
Log.d("label:", ids);
Another Solve Problems
Step 1 Create the model class
public class Sales {
String id_sales,nama;
public Sales(String id_sales, String nama) {
this.id_sales = id_sales;
this.nama = nama;
}
public String getId_sales() {
return id_sales;
}
public void setId_sales(String id_sales) {
this.id_sales = id_sales;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
#Override
public String toString() {
return nama;
}
}
Step 2 Put all data from SQLite table sales
//Data spinner supir
public ArrayList<Sales> getSpinnerSales(){
ArrayList<Sales> salesList = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + "sales";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
salesList.add(new Sales(cursor.getString(0), cursor.getString(1)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return salesList;
}
Step 3 Generate void to consume data from sqlite aa Activity
private void loadSpinnerSales() {
// database handler
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
ArrayList<Sales> salesList = db.getSpinnerSales();
ArrayAdapter<Sales> adapter = new ArrayAdapter<Sales>(this, android.R.layout.simple_spinner_dropdown_item, salesList);
spsales.setAdapter(adapter);
}
Step 4 Load method at OnCreate
spsales = (Spinner) findViewById(R.id.spSales);
loadSpinnerSales();
spsales.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Sales sales = (Sales) parent.getSelectedItem();
Toast.makeText(getApplicationContext(),sales.getId_sales(),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

How to delete ListViews items by their ID in sqlite database

I followed the tutorial here : Tutorial todo APP and I would like to customize the code nad build training app. My first change is to delete things by their ID in database ( in the example they are being deleted by names ). Here is my current code responsible for deleting items:
// FUNCTION for DELETING EXERCISE
public void deleteExercise(View view) {
final View parent = (View) view.getParent();
AlertDialog dialog = new AlertDialog.Builder(this)
.setMessage("Are you sure, you want to delete exercise?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView exerciseTextView = (TextView) parent.findViewById(R.id.exercise_name);
String exercise = String.valueOf(exerciseTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(ExerciseContract.ExerciseEntry.TABLE,
ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME + " = ?",
new String[]{exercise});
db.close();
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
// UPDATING USER INTERFACE AFTER CHANGES IN DB
private void updateUI() {
ArrayList<String> exerciseList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] projection = {
ExerciseContract.ExerciseEntry._ID,
ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME,
//ExerciseContract.ExerciseEntry.COL_EXERCISE_DESCRIPTION
};
Cursor cursor = db.query(
ExerciseContract.ExerciseEntry.TABLE, //tablica do zapytań
projection, //zwracane kolumny
null, //columny dla WHERE
null, //wartosci dla WHERE
null,//nie grupuj wierszy
null,//nie filtruj grup
null); //porządek sortowania
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(ExerciseContract.ExerciseEntry.COL_EXERCISE_NAME);
exerciseList.add(cursor.getString(idx));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
R.layout.item_workout,
R.id.exercise_name,
exerciseList);
mWorkoutListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(exerciseList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
What would be the simplest way to do that?
You're not returning the id anywhere, I'd personally recommend a custom adapter. But for a quick way i think the easiest thing to do is delete it when the users click an item in the list view.
Set the lists views onItemClickListener.
mTaskListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tasks task =(Tasks) mTaskListView.getItemAtPosition(position);
deleteTask(task.getId());
}
});
For the delete tasks pass in the _id of the clicked item.
public void deleteTask(long id) {
//TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
//String task = String.valueOf(taskTextView.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(TaskContract.TaskEntry.TABLE, TaskContract.TaskEntry._ID + " = ?", new String[]{String.valueOf(id)});
db.close();
updateUI();
}
In the UpdateUI section change this while loop to also retrieve _id.
while (cursor.moveToNext()) {
int title = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
int _id = cursor.getColumnIndex(TaskContract.TaskEntry._ID);
Tasks tasks = new Tasks();
tasks.setId(cursor.getInt(_id));
tasks.setTitle(cursor.getString(title));
taskList.add(tasks);
}
Lastly create a model for your tasks.
package com.aziflaj.todolist.db;
public class Tasks {
String title;
int id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString()
{
return getTitle();
}
}
Also remember to remove the button from the LayoutFile. You could show a dialog before deleting, but this was a quick solution. Ideally i'd recommended creating your own custom adapter. You'll probably have to do that if you wish to keep the button in and delete it that way.
Custom Adapter for List View
Create on common method inside your database helper class.
public boolean deleteRowData(String tableName, String selection, String[] selectionArgs) {
open();
sqLiteDb.delete(tableName, selection, selectionArgs);
close();
return true;
}
// ---opens the database---
public NotesData open() throws SQLException {
DatabaseHelper dbHelper = new DatabaseHelper(context);
sqLiteDb = dbHelper.getWritableDatabase();
sqLiteDb = dbHelper.getReadableDatabase();
if (!sqLiteDb.isReadOnly()) {
// Enable foreign key constraints
sqLiteDb.execSQL("PRAGMA foreign_keys = ON;");
}
return this;
}
// ---closes the database---
public void close() {
if (sqLiteDb != null && sqLiteDb.isOpen()) {
sqLiteDb.close();
}
}
Now onClick of listView Item do this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showDeleteAlertDialog(position); // Common method for delete alert dialog
}
});
private void showDeleteAlertDialog(int arrayPosition) {
//delete data from
String title = getResources().getString(R.string.warning);
String message = getResources().getString(R.string.warning_for_delete);
final android.app.Dialog dialog = new Dialog(YourActivity.this, R.style.DialogTheme); //this is a reference to the style above
dialog.setContentView(R.layout.custom_dialog); //I saved the xml file above as custom_dialog.xml
dialog.setCancelable(true);
//to set the message
TextView sub_message = (TextView) dialog.findViewById(R.id.tv_Message);
TextView dialogTitle = (TextView) dialog.findViewById(R.id.tv_Title);
Button btn_Negative = (Button) dialog.findViewById(R.id.btn_Negative);
Button btn_Positive = (Button) dialog.findViewById(R.id.btn_Positive);
btn_Negative.setText("Cancel");
btn_Positive.setText("Delete");
sub_message.setText("Are you sure you want to delete this>");
dialogTitle.setText(title);
//add some action to the buttons
btn_Positive.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String selection = YourColumnName + " LIKE ?";
final String[] selectionArgs = {myArrayList.get(arrayPosition).getID()};
mHelper.deleteRowData(YourTableNAME, selection, selectionArgs);
// Now just remove that array position from your arraylist (from activity & adapter arralist too).
myArrayList.remove(arrayPosition);
yourAdapter.yourArrayList.remove(arrayPosition);
notifyDataSetChanged();
}
});
btn_Negative.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}

Display data from SQLite database into ListView in Android

Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this.
Here's my code getClientNames in DatabaseHelper class:
public Cursor getSitesByClientname(String id) {
String[] args={id};
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
String results = "";
/*int count = myCursor.getCount();
String[] results = new String[count + 1];
int i = 0;*/
if (myCursor != null) {
if(myCursor.getCount() > 0)
{
for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
{
results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename"));
}
}
}
return results;
}
One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.
Here's the ClientSites class where I want to display the data:
public class ClientSites extends Activity {
//public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
private Cursor ourCursor = null;
private Adapter adapter=null;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
//dbHelper.createDatabase();
dbHelper.openDataBase();
ourCursor = dbHelper.getSitesByClientname(uID);
Log.e("ALERT", uID.toString());
startManagingCursor(ourCursor);
Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id)
{
Intent i=new Intent(ClientSites.this, InspectionPoints.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
};
class Adapter extends CursorAdapter {
#SuppressWarnings("deprecation")
Adapter(Cursor c) {
super(ClientSites.this, c);
}
//#Override
public void bindView(View row, Context ctxt,
Cursor c) {
Holder holder=(Holder)row.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Holder holder=new Holder(row);
row.setTag(holder);
return(row);
}
}
static class Holder {
private TextView name=null;
Holder(View row) {
name=(TextView)row.findViewById(R.id.ingredientText);
}
void populateFrom(Cursor c, DBUserAdapter r) {
name.setText(r.getName(c));
}
}
}
Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong.
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
dbHelper.openDataBase();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//ourCursor = dbHelper.getSitesByClientname(uID);
//Log.e("ALERT", uID.toString());
//startManagingCursor(ourCursor);
//Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!!
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
I Created a Listview from a database. Here is the code I used for my app
Here is part of the database handler. It will return a List of Categories for my listview. It can return a list of Strings if that is what you need.
public List<Category> getAllCategorys() {
ArrayList<Category> categoryList = new ArrayList<Category>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
try{
if (cursor.moveToFirst()) {
do {
Category category = new Category();
category.setID(Integer.parseInt(cursor.getString(0)));
category.setCategory(cursor.getString(1));
// Adding category to list
categoryList.add(category);
} while (cursor.moveToNext());
}
}finally{
cursor.close();
}
db.close();
// return category list
return categoryList;
Here is how I fill the ListView by calling the database.
int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();
category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{
category_data[i] = cn.getCategory(); // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);
EDIT: Here is something that should work for you
public List<String> getSitesByClientname(String id) {
String[] args={id};
ArrayList<String> result = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
try{
if (myCursor.moveToFirst()){
do{
result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
}while(myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
return result;
}
Use it like this
List<String> sites_data = dbHelper.getSitesByClientname(uID);
result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{
result_data[i] = s; // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);
If you want to return the Cursor from dbHelper you can do something like this...
public Cursor getSitesByClientname(String id) {
String[] args={id};
return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
}
I'd also take some time to read the listview tutorial

Android SimpleCursorTreeAdapter Child Click

I have an expandable list using a simplecursortreeadapter
How would I integrate an onclicklistener or any way to change the
Below is my script so far. I was trying to use the onclicklistener at the bottom of this post, but I cannot figure out how to change it from a listview to expandable listview listener for the children.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cattest);
SQLiteDatabase checkDB = null;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor groupCursor = checkDB.rawQuery("SELECT * FROM countries", null);
MySimpleCursorTreeAdapter mscta = new MySimpleCursorTreeAdapter(
this,
groupCursor,
R.layout.employee_list_item,
new String[] {"country"},
new int[] {R.id.country},
R.layout.employee_list_item,
new String[] {"employee"},
new int[] {R.id.lastName});
setListAdapter(mscta);
checkDB.close();
}
class MySimpleCursorTreeAdapter extends SimpleCursorTreeAdapter{
public MySimpleCursorTreeAdapter(Context context, Cursor cursor,
int groupLayout, String[] groupFrom, int[] groupTo,
int childLayout, String[] childFrom, int[] childTo) {
super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom,
childTo);
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
String countryID = Integer.toString(groupCursor.getInt(0));
SQLiteDatabase checkDB = null;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor value = checkDB.rawQuery("SELECT * FROM employee WHERE _id='"+ countryID +"'", null);
String test = "";
if(value.moveToFirst())
test = value.getInt(0) + ": " + value.getString(1);
while(value.moveToNext()){
test += ";" + value.getInt(0) + ": " + value.getString(1);
}
return value;
}
}
Tried implementing this
questionList = (ListView) findViewById (R.id.list);
sample(typedText);
questionList.setOnItemClickListener(
new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Intent intent = new Intent(All.this, com.second.app.Second.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
//Cursor cursor = (Cursor) adapter.getItem(position);
//intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
}
);
EDIT:
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
// use groupPosition and childPosition to locate the current item in the adapter
Intent intent = new Intent(Categories.this, com.second.app.Second.class);
Cursor cursor = (Cursor) mscta.getItem(childPosition);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
//Cursor cursor = (Cursor) adapter.getItem(position);
//intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
return true;
}
At the moment the getChild(childPosition); is outputting the error
The method getItem(int) is undefined for the type
Categories.MySimpleCursorTreeAdapter
Look into the setOnChildClickListener method: http://developer.android.com/reference/android/widget/ExpandableListView.html#setOnChildClickListener(android.widget.ExpandableListView.OnChildClickListener)

Categories

Resources