Dynamically Button Text? - android

Top rows of three buttons shows the top three values of the database but from the next rows again top three values were shown in the three buttons ?
public class ButtonTest extends Activity {
/** Called when the activity is first created. */
NoteHelper helper = null;
Cursor ourCursor = null;
NoteAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
ListView list = (ListView) findViewById(R.id.list);
helper = new NoteHelper(this);
ourCursor = helper.getAll();
startManagingCursor(ourCursor);
adapter = new NoteAdapter(ourCursor);
list.setAdapter(adapter);
}
catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE :" + e.toString());
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
helper.close();
}
class NoteAdapter extends CursorAdapter {
NoteAdapter(Cursor c) {
super(ButtonTest.this, c);
}
#Override
public void bindView(View row, Context ctxt, Cursor c) {
NoteHolder holder = (NoteHolder) row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
NoteHolder holder = new NoteHolder(row);
row.setTag(holder);
return (row);
}
}
My NoteHolder Class Is
static class NoteHolder {
private Button b1 = null;
private Button b2 = null;
private Button b3 = null;
NoteHolder(View row) {
b1 = (Button) row.findViewById(R.id.one);
b2 = (Button) row.findViewById(R.id.two);
b3 = (Button) row.findViewById(R.id.three);
}
void populateFrom(Cursor c, NoteHelper helper) {
if (!c.moveToFirst()) return;
b1.setText(helper.getNote(c));
c.moveToNext();
b2.setText(helper.getNote(c));
c.moveToNext();
b3.setText(helper.getNote(c));
}
}
My SQLiteHelper Class is
class NoteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "note.db";
private static final int SCHEMA_VERSION = 1;
public SQLiteDatabase dbSqlite;
public NoteHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Notes (_id INTEGER PRIMARY KEY AUTOINCREMENT,note TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getAll() {
return (getReadableDatabase().rawQuery("SELECT _id,note From Notes",
null));
}
public String getNote(Cursor c) {
return(c.getString(1));
}
public Cursor getById(String id) {
return (getReadableDatabase().rawQuery(
"SELECT _id,note From Notes", null));
}
}
}
My main.xml is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:padding="6dip"
android:background="#1F8B26">
<ListView android:layout_height="wrap_content" android:id="#+id/list"
android:layout_width="fill_parent"></ListView>

First I want to say is that Gridview will be more suitable in your case
second you are getting multiple rows because cursor adapter will create those many view that it has rows and for each row you are again reading rows in populateFrom() method so that your rows are being repeated.
Instead of Cursor adapter use Base adapter
Solution
1) first create arraylist from your cursor
2) after getting arraylist create a object of NoteAdapter which is below
3) set adapter in gridview
private class NoteAdapter extends BaseAdapter implements OnClickListener {
ArrayList<Note> arrNote;
LayoutInflater inflater;
public NoteAdapter(ArrayList<Note> arr) {
this.arrNote = arr;
inflater = ExploreDestination.this.getLayoutInflater();
}
#Override
public int getCount() {
return arrNote.size();
}
#Override
public Object getItem(int index) {
return arrNote.get(index);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(int position, View v, ViewGroup arg2) {
v = inflater.inflate(R.layout.Notebutton, null);
v.setTag(arrNote.get(position));
((Button)v).setText(arrNote.get(position).getTitle());
v.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
//do your work
}
}

Related

The first row of my SQLite Database is not getting fetched and displayed in my RecyclerView

This is my dbmanager class:
public class dbmanager extends SQLiteOpenHelper {
String sgpa_table="create table Sgpa (sname text, semester text, sgpa int,percent int, schemes int, primary key(sname,semester,schemes))";
public dbmanager(#Nullable Context context) {
super(context, "Student", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sgpa_table);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor fetch_data1() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select*FROM Sgpa" ;
Cursor cursor = db.rawQuery(query,null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
}
This is my Adapter class:
public class adapter_sgpa extends RecyclerView.Adapter<adapter_sgpa.Viewholder> {
ArrayList<POJO> sgpaArrayList;
public adapter_sgpa(ArrayList<POJO> sgpaArrayList) {
this.sgpaArrayList = sgpaArrayList;
}
#NonNull
#Override
public adapter_sgpa.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listitem = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_sgpa, parent, false);
return new Viewholder(listitem);
}
#Override
public void onBindViewHolder(#NonNull adapter_sgpa.Viewholder holder, int position) {
POJO sgpa= sgpaArrayList.get(position);
holder.sname.setText(sgpa.getSname());
holder.semester.setText(sgpa.getSemester());
holder.sgpa.setText(Integer.toString(sgpa.getSgpa()));
holder.percent.setText(Integer.toString(sgpa.getPercent()));
holder.schemes.setText(Integer.toString(sgpa.getSchemes()));
}
#Override
public int getItemCount() {
return sgpaArrayList.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView sname, semester, sgpa, percent, schemes;
//ImageButton btndelete1;
public Viewholder(#NonNull View itemView) {
super(itemView);
sname = (TextView) itemView.findViewById(R.id.textView2);
semester = (TextView) itemView.findViewById(R.id.semester);
sgpa = (TextView) itemView.findViewById(R.id.textV);
percent = (TextView) itemView.findViewById(R.id.textVw);
schemes = (TextView) itemView.findViewById(R.id.scheme1);
// btndelete1 = (ImageButton) itemView.findViewById(R.id.btndelete1);
}
}
}
This is sgpa_frag which is like my main class:
public class sgpa_frag extends Fragment {
//View view;
RecyclerView recyclerview;
adapter_sgpa ac;
TextView else2;
ArrayList<POJO> sgpaArrayList;
public sgpa_frag() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sgpa_frag, container, false);
recyclerview= (RecyclerView) view.findViewById(R.id.rc1);
else2=(TextView)view.findViewById(R.id.else2);
sgpaArrayList= new ArrayList<>();
ac= new adapter_sgpa(sgpaArrayList);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.VERTICAL,true));
recyclerview.setAdapter(ac);
Fetchdata1();
return view;
}
private void Fetchdata1()
{
dbmanager db= new dbmanager(getContext());
Cursor cursor= db.fetch_data1();
if (cursor!= null){
cursor.moveToFirst();
while (cursor.moveToNext()){
//ModelDetail cd= new ModelDetail(cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4));
POJO pj= new POJO();
pj.setSname(cursor.getString(0));
pj.setSemester(cursor.getString(1));
pj.setSgpa(cursor.getInt(2));
pj.setPercent(cursor.getInt(3));
pj.setSchemes(cursor.getInt(4));
sgpaArrayList.add(pj);
}
ac= new adapter_sgpa(sgpaArrayList);
recyclerview.setAdapter(ac);
}
else{
else2.setVisibility(View.VISIBLE);
}
}
}
The first row of my SQLite Database is not getting fetched and displayed in my RecyclerView.
The other rows are getting displayed but only the first one is not getting displayed.
Can someone point me out where I am going wrong?
From this part of your code in Fetchdata1():
if (cursor!= null){
cursor.moveToFirst();
while (cursor.moveToNext()){
..................................
remove cursor.moveToFirst();
because cursor.moveToNext() will advance the cursor's index to the 2nd row and the 1st row will not be added to the list.
Also inside fetch_data1() inside dbmanager remove this:
if (cursor != null) {
cursor.moveToFirst();
}

using loader to automatically update listview when a change happens to a database table

in my Application i have an Activity that has a ListView and a button. i am using loader to automatically loading data to listview from my table in the database.and i am using the button to change the table rows.
i want the loader to automatically load the data from table when a change happens to the table.
right now my code loads the data into listview but it doesn't update it when table changes after that.
here are my classes :
item
public class Item {
public int id;
public String name;
}
MainActivity :
public class MainActivity extends Activity implements
LoaderManager.LoaderCallbacks<List<Item>> {
ItemAdapter adapter;
List<Item> items;
Button button;
TextView tv;
ListView listview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
button = (Button) findViewById(R.id.button);
listview = (ListView) findViewById(R.id.listview);
items = new ArrayList<Item>();
adapter = new ItemAdapter(this, items);
listview.setAdapter(adapter);
getLoaderManager().initLoader(0, savedInstanceState, this).forceLoad();
}
//button code for changing db
public void change(View view) {
ItemHelper helper = new ItemHelper(this);
Item item = new Item();
item.name = "Samsung P6800";
helper.insert(item);
}
#Override
public Loader<List<Item>> onCreateLoader(int id, Bundle args) {
final ItemHelper helper = new ItemHelper(getApplicationContext());
return new AsyncTaskLoader<List<Item>>(MainActivity.this) {
#Override
public List<Item> loadInBackground() {
return helper.read();
}
};
}
#Override
public void onLoadFinished(Loader<List<Item>> loader, List<Item> data) {
adapter.addAll(data);
adapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(Loader<List<Item>> loader) {
adapter.clear();
adapter.notifyDataSetChanged();
}
ItemHelper
public class ItemHelper {
public static final String DB_NAME = "Test";
private static Context m_context;
private static SQLiteDatabase m_db;
private static DatabaseHelper m_helper;
String[] columns = { "id", "name" };
public ItemHelper(Context context) {
m_context = context;
m_helper = new DatabaseHelper(m_context, DB_NAME, null, 1);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public void insert(Item item) {
m_db = m_helper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("name", item.name);
m_db.insert("item", null, initialValues);
m_db.close();
}
public List<Item> read() {
List<Item> items = new ArrayList<Item>();
m_db = m_helper.getReadableDatabase();
Cursor cursor = m_db.query("item", columns, null, null, null, null,
null);
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
item.name = cursor.getString(cursor
.getColumnIndexOrThrow("name"));
items.add(item);
} while (cursor.moveToNext());
}
m_db.close();
return items;
}
}
ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> {
private Context context;
private List<Item> items;
private LayoutInflater vi;
public ItemAdapter(Context context, int resource) {
super(context, resource);
// TODO Auto-generated constructor stub
}
public ItemAdapter(Context context, List<Item> items) {
super(context, 0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Item item = items.get(position);
if (item != null) {
view = vi.inflate(R.layout.item_info, parent, false); // custom xml
// for
// desired
// view
TextView tv1 = (TextView) view.findViewById(R.id.tvID);
tv1.setText(""+item.id);
TextView tv2 = (TextView) view.findViewById(R.id.tvName);
tv2.setText(item.name);
}
return view;
}
#Override
public Item getItem(int position) {
return items.get(position);
}
}
how can i do it ? ( i don't want to use content providers )
finally i used ContentProviders to solve this issue.
i created a method inside my database helper class that returns a Cursor according to it's parameters,
and used it inside ContentProvider to get Data.
public Cursor getCursor(int status, boolean isAccepted) {
m_db = m_helper.getReadableDatabase();
String sql = "SELECT id as _id , rid , isaccepted , status FROM torder";
Cursor cursor = m_db.rawQuery(sql, null);
return cursor;
}
also in helper when i insert data to db i notify the content provider :
public void notifyProvider(int status) {
ContentValues values = new ContentValues();
values.put("status", status);
Uri uri = m_context.getContentResolver().insert(
OrderProvider.CONTENT_URI, values);
}
public void insert(Order order) {
int flag = (order.isAccepted()) ? 1 : 0;
String[] args = { String.valueOf(order.getId()),
String.valueOf(order.getR_id()), String.valueOf(flag),
String.valueOf(order.getStatus()) };
m_db.execSQL(
"INSERT OR REPLACE INTO torder(id,rid,isaccepted,status) VALUES(?,?,?,?)",
args);
// save to orderdetails
List<OrderDetails> orderDetailsList = order.getOrders();
OrderDetailsHelper helper = OrderDetailsHelper.getInstance(m_context);
helper.open();
helper.insertAll(orderDetailsList);
helper.close();
notifyProvider(1);
}
Change your change method:
public void change(View view) {
ItemHelper helper = new ItemHelper(this);
Item item = new Item();
item.name = "Samsung P6800";
helper.insert(item);
getLoaderManager().restartLoader(0, null, this);
}

Updating SQL row with OnItemLongClick doesn't work

Can anybody please have a look at my code and tell me where I am wrong? I don't get errors, unfortunately the row that is long pressed and new value is provided is not being updated unless I specify exact row number. I need to be able to update the row that is clicked. I tried everything and up to today I didn't manage to get any help. I am beginner in Android development.
Here is the code of MyDB:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
db.beginTransaction();
db.setTransactionSuccessful();
db.endTransaction();
return db.update(Constants.TABLE_NAME , newValue , Constants.KEY_ID + "= ?" ,
new String[]{ Double.valueOf(rowId).toString() })>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the code with the dialog, where I should update the row:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
private long rowId;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
long rowId = adapter.getItemId(position); //Will return the clicked item
saveItToDB(rowId);
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
// public void notifyDataSetChanged();
dismiss();
try {
saveItToDB(rowId);
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB(long rowId) {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), rowId);
dba.close();
((TextView) editText).setText("");
}
}
And here is the Diary Adapter:
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
i found first problem at your DB class
update this method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
To
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, new String[]{Constants.TITLE_NAME ,Constants.CONTENT_NAME}, null,
null, null, null, null);
return c;
}

How to update row that is clicked?

After a long time I figured out that changing argument from 0 to different number allows me to update row with corresponding id to this number:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
In above code I changed 0 to 2 and I was able to update content of row no 2. Here is full class code:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
Now, what do I need to do in order to tell it that I want to update row that is clicked, not row number 2? Any help would be appreciated.
Here is MyDB code:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the Adapter:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Implement getItemId(int position) in your adapter. In your onListItemClick method, call this method with the given position.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long itemId = adapter.getItemId(position);
saveItToDB(itemId);
}
private void saveItToDB(long itemId) {
String text = editText.getText().toString();
editText.setText("");
dba.open();
dba.updateDiaryEntry(text, itemId);
dba.close();
}

How can I get an item in a specific row in a list from a database?

I have been searching through a lot of questions but they don't ask or answer what I'm looking for, so here is what I'm trying to do.
So far I have an project in witch I added a pre populated database, with a table that contains 6 columns of data, the main xml just displays the list view, I'm using a Adapter, Cursor, SQLiteHelper etc. all works fine and displays my custom itemlist.xml all good, now in every item of the list I display only 3 things (second, fourth and fifth column data) of each record (they all contain 6 coluns like I mention before), I want to be able with a onclickitemlistener to display in a toast the data from the third column for that item, how do I accomplish that? I'm able to get the list item id displayed, so can someone help me here, Thanks
here is som code:
Code from y main activity
public class DBlistActivity extends Activity {
private mediosHelper dbmediosHelper = null;
private Cursor ourCursor = null;
FancyAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView myListView = (ListView) findViewById(R.id.mylistView);
dbmediosHelper = new mediosHelper(this);
try {
dbmediosHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbmediosHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
try {
ourCursor = dbmediosHelper.getCursor();
startManagingCursor(ourCursor);
}catch(SQLException sqle){
throw sqle;
}
adapter = new FancyAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
class FancyAdapter extends CursorAdapter {
FancyAdapter(Cursor c) {
super (DBlistActivity.this, c);
}
public void bindView(View row, Context ctxt, Cursor c) {
ViewHolder holder = (ViewHolder) row.getTag();
holder.populateForm(c, dbmediosHelper);
}
public View newView(Context ctxt, Cursor c, ViewGroup parent){
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.listitem, parent, false);
ViewHolder holder = new ViewHolder(row);
row.setTag(holder);
return(row);
}
}
class ViewHolder{
public TextView nombre=null;
public TextView estado=null;
public TextView ciudad=null;
ViewHolder (View row){
nombre = (TextView) row.findViewById(R.id.medioName);
estado = (TextView) row.findViewById(R.id.medioEstado);
ciudad = (TextView) row.findViewById(R.id.medioCiudad);
}
void populateForm(Cursor c, mediosHelper r){
nombre.setText(r.getName(c));
estado.setText(r.getEstado(c));
ciudad.setText(r.getCiudad(c));
}
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Toast.makeText(getApplicationContext(), String.valueOf(id), Toast.LENGTH_SHORT) .show();
}
};
And from my mediosHelper
public Cursor getCursor() {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
String[] asColumsToReturn = new String[] { COLUMN_ID, COLUMN_CODE, COLUMN_NAME, COLUMN_URL, COLUMN_ESTADO, COLUMN_CIUDAD};
Cursor mCursor = queryBuilder.query(myDataBase, asColumsToReturn, null, null, null, null, null);
return mCursor;
}
public CharSequence getId(Cursor c) {
return (c.getString(0));
}
public CharSequence getCode(Cursor c) {
return (c.getString(1));
}
public String getName(Cursor c){
return(c.getString(2));
}
public String getUrl(Cursor c) {
return (c.getString(3));
}
public String getEstado(Cursor c) {
return (c.getString(4));
}
public String getCiudad(Cursor c) {
return (c.getString(5));
}
you need to get the cursor you used to fill the adapter. once you have that move it to the position you get in the onItemClickedCallback with c.moveToPosition(position). Than you have access to all columns (cursor.getColumnIndex("_id"))
EDIT:
class MyActivity extends Activity implements OnItemClickListener{
FancyAdapter adapter = null;
...
adapter = new FancyAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(this);
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
Cursor c = adapter.getCursor();
c.moveToPosition(position);
int id = c.getInt(c.getColumnIndex("_id");
}
}

Categories

Resources