So I have a ListView and a custom adapter for it
I am adding valued to the database and then repopulating the list
so I added items in the following way : q, w,e,r,t,y,u,i,o,p
the listview populated as follows : q,w,e,r,t,y,q,q,q
This is the custom adapter
public class TestListAdapter extends BaseAdapter {
private static ArrayList<FlashCard> flashCardItems;
private LayoutInflater mInflater;
private Context context;
public TestListAdapter(Context context, ArrayList<FlashCard> results) {
this.context = context;
flashCardItems = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return flashCardItems.size();
}
public Object getItem(int position) {
return flashCardItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.flashcard, null);
holder = new ViewHolder();
holder.flipper = (ViewFlipper) convertView.findViewById(R.id.flashcard);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.flipper.addView(FlashCard.createQuestionCard(context,flashCardItems.get(position).getQuestion()));
return convertView;
}
static class ViewHolder {
ViewFlipper flipper;
}
}
This is the Database Handler
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "mySchoolDB";
// Flashcards table name
private static final String TABLE_FLASHCARDS = "flashcards";
// Flashcards Table Columns names
private static final String KEY_ID = "id";
private static final String QUESTION = "question";
private static final String ANSWER = "answer";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FLASHCARDS_TABLE = "CREATE TABLE " + TABLE_FLASHCARDS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + QUESTION + " TEXT,"
+ ANSWER + " TEXT" + ")";
db.execSQL(CREATE_FLASHCARDS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FLASHCARDS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new Flashcard
public void addFlashcard(FlashCard flashcard) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(QUESTION, flashcard.getQuestion()); // flashcard Name
values.put(ANSWER, flashcard.getAnswer()); // flashcard Phone
// Inserting Row
db.insert(TABLE_FLASHCARDS, null, values);
db.close(); // Closing database connection
}
// Getting single FlashCard
public FlashCard getFlashcard(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_FLASHCARDS, new String[] { KEY_ID,
QUESTION, ANSWER }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
FlashCard flashcard= new FlashCard(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
cursor.close();
db.close();
// return FlashCard
return flashcard;
}
// Getting All Flashcards
public ArrayList<FlashCard> getAllFlashcards() {
ArrayList<FlashCard> FlashcardList = new ArrayList<FlashCard>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_FLASHCARDS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FlashCard flashcard = new FlashCard(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2));
// Adding Flashcard to list
FlashcardList.add(flashcard);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return Flashcard list
return FlashcardList;
}
// Updating single Flashcard
public int updateFlashcard(FlashCard flashcard) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(QUESTION, flashcard.getQuestion());
values.put(ANSWER, flashcard.getAnswer());
db.close();
// updating row
return db.update(TABLE_FLASHCARDS, values, KEY_ID + " = ?",
new String[] { String.valueOf(flashcard.getID()) });
}
// Deleting single Flashcard
public void deleteFlashcard(FlashCard flashcard) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_FLASHCARDS, KEY_ID + " = ?",
new String[] { String.valueOf(flashcard.getID()) });
db.close();
}
// Getting Flashcards Count
public int getFlashcardsCount() {
String countQuery = "SELECT * FROM " + TABLE_FLASHCARDS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
public void deleteAllFlashCards(){
SQLiteDatabase sdb= this.getWritableDatabase();
sdb.delete(TABLE_FLASHCARDS, null, null);
sdb.close();
}
}
and this is the listview
public class TestList extends ListView
{
private Context context;
private ArrayList<FlashCard> stringArray = new ArrayList<FlashCard>();
public TestList(Context context) {
super(context);
this.context = context;
setResults();
}
public void setResults() {
DatabaseHandler db = new DatabaseHandler(context);
stringArray = db.getAllFlashcards();
setAdapter(new TestListAdapter(context, stringArray));
}
public TestList(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void addFlashCardDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Add flashcard");
final EditText question = new EditText(context);
question.setHint("Question");
final EditText answer = new EditText(context);
answer.setHint("Answer");
LinearLayout qa = new LinearLayout(context);
qa.setOrientation(LinearLayout.VERTICAL);
qa.addView(question);
qa.addView(answer);
builder.setView(qa);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FlashCard f = new FlashCard(question.getText().toString(), answer.getText().toString());
DatabaseHandler db = new DatabaseHandler(context);
db.addFlashcard(f);
setResults();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
addView() isn't replacing the view that currently exists. When the convertView comes back to be recycled, 'q' already exists inside the ViewFlipper, and you want q to go away and be replaced by 'u'
holder.flipper.addView(FlashCard.createQuestionCard(context,flashCardItems.get(position).getQuestion()));
Try setting the view inside the view flipper to the new value instead of using addView().
Example:
TextView text = (TextView) ViewFlipper.findViewById(R.id.textView);
text.setText(flashCardItems.get(position).getQuestion());
the problem is coming from the ViewFlipper you're using in your adapter.
List views in android use view recycling (which is what the convertView is for in getView) but due to how you're handling them every time a view gets recycled you add another view to the flipper, what you need to do is add the view when convertView is null and then modify the view in the flipper to represent your data, not sure how the question card view works so I'm just guessing there.
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.flashcard, null);
holder = new ViewHolder();
holder.flipper = (ViewFlipper) convertView.findViewById(R.id.flashcard);
holder.card = FlashCard.createQuestionCard(context,flashCardItems.get(position).getQuestion());
holder.filpper.addView(holder.card);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.card.setQuestion(flashCardItems.get(position).getQuestion());
return convertView;
}
obviously you'll have to adjust your view holder and add a card field with the proper type and add a setQuestion method to the questionCard view but you get the idea.
Related
Good Day Guys..Need some help here..i got troubled from deleting the selected row in my list view..i want to use an alert dialog for confirmation to delete the selected row..and to edit also..i am a beginner and i have tried searching for answers to this problem and also tried relating it to other problems but i still didn't get it...
My DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper implements Filterable{
// private static final String COLUMN_NAME="ageing_column";
private static final String DATABASE_NAME=" EXPIRATIONMONITORING.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ContractClass.NewInfo.TABLE_NAME+"("+ ContractClass.NewInfo.ITEM_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ContractClass.NewInfo.DESCRIPTION+" TEXT, "+
ContractClass.NewInfo.CATEGORY+" TEXT,"+ ContractClass.NewInfo.MONTHONE+" TEXT, "+ ContractClass.NewInfo.REMIND_AT+" TEXT, "+ ContractClass.NewInfo.QTY+" TEXT, "+
ContractClass.NewInfo.LOCATION+" TEXT );";
private SQLiteDatabase sqLiteDatabase;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//this.context1=context;
Log.e("DATABASE OPERATIONS", "Database created / opened....");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created....");
}
public void addInformations(String description, String category, String monthOne,String quantity,String remind, String location, SQLiteDatabase db)
{
ContentValues contentValues=new ContentValues();
contentValues.put(ContractClass.NewInfo.LOCATION,location);
contentValues.put(ContractClass.NewInfo.DESCRIPTION,description);
contentValues.put(ContractClass.NewInfo.CATEGORY,category);
contentValues.put(ContractClass.NewInfo.MONTHONE,monthOne);
contentValues.put(ContractClass.NewInfo.REMIND_AT,remind);
contentValues.put(ContractClass.NewInfo.QTY,quantity);
db.insert(ContractClass.NewInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted");
db.close();
}
public Cursor getInformations(SQLiteDatabase db)
{
Cursor cursor;
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
cursor=db.query(ContractClass.NewInfo.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor getContact(String location,SQLiteDatabase sqLiteDatabase)
{
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
String selection = ContractClass.NewInfo.LOCATION+" LIKE? ";
String [] sargs={location};
Cursor cursor=sqLiteDatabase.query(ContractClass.NewInfo.TABLE_NAME,projections,selection,sargs,null,null,null);
return cursor;
}
public String[] SelectAllData()
{
try
{
String arrData[]=null;
SQLiteDatabase db;
db=this.getReadableDatabase();
String strSQL=" SELECT "+ ContractClass.NewInfo.LOCATION+" FROM "+ ContractClass.NewInfo.TABLE_NAME;
Cursor cursor =db.rawQuery(strSQL,null);
if(cursor !=null)
{
if(cursor.moveToFirst())
{
arrData=new String[cursor.getCount()];
int i=0;
do
{
arrData[i]=cursor.getString(0);
i++;
}while(cursor.moveToNext());
}
}
cursor.close();
return arrData;
}catch(Exception e){
return null;
}
}
public void delete_byID(int id){
sqLiteDatabase.delete(ContractClass.NewInfo.TABLE_NAME, ContractClass.NewInfo.ITEM_ID + "=" + id, null);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public Filter getFilter() {
return null;
}
}
THis is My MAin Class..
public class ViewListsActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
SQLiteDatabase sqLiteDatabase;
ListDataAdapter listDataAdapter;
ListView listView;
Cursor cursor;
EditText delete_txt;
String deletetxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_lists_activity);
listView = (ListView) findViewById(R.id.search_listView);
listDataAdapter = new
ListDataAdapter(getApplicationContext(),R.layout.row_layout);
databaseHelper = new DatabaseHelper(getApplicationContext());
databaseHelper = new DatabaseHelper(this);
delete_txt = (EditText) findViewById(R.id.delete_text);
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
listView.setAdapter(listDataAdapter);
if (cursor.moveToFirst()) {
do {
String description, category, month1,remind,qty,location;
description = cursor.getString(0);
category = cursor.getString(1);
month1 = cursor.getString(2);
qty=cursor.getString(3);
remind=cursor.getString(4);
location = cursor.getString(5);
DataProvider dataProvider = new DataProvider(description,
category, month1,qty,remind,location);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemLongClickListener(new
AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View
view, int position, long id) {
return false;
}
});
}
public void ToSearchBtn(View view)
{
Intent intent=new Intent(this,ThirdActivitySearchAllData.class);
startActivity(intent);
}
public void ToAddNewItemBtn(View view)
{
Intent intent=new Intent(this,SecondActivitySaveData.class);
startActivity(intent);
}
}
My List Adapter Class
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView DESCRIPTION,CATEGORY,MONTH1,QTY,REMIND,LOCATION;
}
public void add(Object object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row =convertView;
LayoutHandler layoutHandler;
if(row==null)
{
LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler=new LayoutHandler();
layoutHandler.DESCRIPTION= (TextView) row.findViewById(R.id.text_description);
layoutHandler.CATEGORY= (TextView) row.findViewById(R.id.text_category);
layoutHandler.MONTH1= (TextView) row.findViewById(R.id.text_monthOne);
layoutHandler.REMIND= (TextView) row.findViewById(R.id.text_remind);
layoutHandler.QTY= (TextView) row.findViewById(R.id.text_qty);
layoutHandler.LOCATION= (TextView) row.findViewById(R.id.text_location);
row.setTag(layoutHandler);
}else
{
layoutHandler=(LayoutHandler)row.getTag();
}
DataProvider dataProvider= (DataProvider) this.getItem(position);
layoutHandler.DESCRIPTION.setText(dataProvider.getDescription());
layoutHandler.CATEGORY.setText(dataProvider.getCategory());
layoutHandler.MONTH1.setText(dataProvider.getMonthOne());
layoutHandler.REMIND.setText(dataProvider.getRemindAt());
layoutHandler.QTY.setText(dataProvider.getQuantity());
layoutHandler.LOCATION.setText(dataProvider.getLocation());
return row;
}
}
You can use ALERT DIALOG for showing confirmation popup, with YES/NO option both for delete and edit, and based on options selected in ALERT DIALOG you can perform further operations
In the below link you can find the sample code
How do I display an alert dialog on Android?
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;
}
I am working on a contact book like application.I have a database and,I want to display the data in ListView. Can anybody tell me how to achieve this? Below is what I have tried so far,
public class Contacts {
private int id;
private String name;
private String phone_number;
private String email;
public Contacts()
{
}
public Contacts(int id, String name, String phone_number, String email)
{
this.id = id;
this.name = name;
this.phone_number = phone_number;
this.email = email;
}
public Contacts(String name, String phone_number, String email)
{
this.name = name;
this.phone_number = phone_number;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "ContactsManager";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_EMAIL = "email";
public DatabaseHandler(Context context) {
super( context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT," + KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
public void insertContact(Contacts contacts)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, contacts.getName()); // Contact Name
cv.put(KEY_PH_NO, contacts.getPhone_number()); // Contact Phone
cv.put(KEY_EMAIL, contacts.getEmail()); //Contact Email
// Inserting Row
db.insert(TABLE_CONTACTS, null, cv);
db.close();
}
// Getting All Contacts
public List<Contacts> getAllContacts()
{
List<Contacts> contactList = new ArrayList<Contacts>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
Contacts contact = new Contacts();
//contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhone_number(cursor.getString(2));
contact.setEmail(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
}
while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
public class View_data extends ListActivity {
DatabaseHandler db = new DatabaseHandler(this);
Cursor c ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
db.getWritableDatabase();
List<Contacts> values = db.getAllContacts();
ArrayAdapter<Contacts> adapter = new ArrayAdapter<Contacts>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_data, menu);
return true;
}
}
In View_data class i tried to display the data but couldn't do it.
Any Suggestion will be highly appreciated.
You have to pass the context ,your list item layout and cursor in the Custom adapter.........
final CustomAdapter adapter = new CustomAdapter(MainActivity.this,
R.layout.listitem, cursor);
list.setAdapter(adapter);
then this is how CustomAdapter class is implemented in which you have to override your bindView method. This will look complex until you study it and then try to do it yourself.
public class CustomAdapter extends CursorAdapter {
// Cursor cursor;
Context context;
public CustomAdapter(Context context, int RId, Cursor cursor) {
super(context, cursor);
// this.cursor = cursor;
this.context = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView team1 = (TextView) view.findViewById(R.id.listitem_team1);
team1.setText(cursor.getString(10));
TextView team2 = (TextView) view.findViewById(R.id.listitem_team2);
team2.setText(cursor.getString(11));
TextView date = (TextView) view.findViewById(R.id.listitem_date);
date.setText(cursor.getString(3));
TextView city = (TextView) view.findViewById(R.id.listitem_city);
city.setText(cursor.getString(2));
TextView time = (TextView) view.findViewById(R.id.listitem_time);
time.setText(cursor.getString(4));
TextView ground = (TextView) view.findViewById(R.id.listitem_ground);
date.setText(cursor.getString(1));}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
return v;
}
}
you can also refer to this link http://dj-android.blogspot.in/2012/10/android-show-data-from-sqlite-db-into.html
You have to pass the data to the UserAdapter.The code
List<DataProvider> data = userDbHelper.getInformation(sqLiteDatabase); is used to retrive data from SQL database which are applied to the variable data. Try this method.
List<DataProvider> data = userDbHelper.getInformation(sqLiteDatabase);
UsersAdapter adapter = new UsersAdapter(this, (ArrayList<DataProvider>) data);
list.setAdapter(adapter);
Then UserAdapter class implentation is given below which extends the ArrayAdapter..
public class UsersAdapter extends ArrayAdapter<DataProvider> {
private static class ViewHolder {
TextView id;
TextView name;
TextView number;
}
public UsersAdapter(Context context, ArrayList<DataProvider> users) {
super(context, R.layout.new_layout, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
// User user = getItem(position);
DataProvider dataProvider = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.new_layout, parent, false);
viewHolder.id = (TextView)convertView.findViewById(R.id.textId);
viewHolder.name = (TextView) convertView.findViewById(R.id.textname);
viewHolder.number = (TextView) convertView.findViewById(R.id.textnumber);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data from the data object via the viewHolder object
// into the template view.
viewHolder.id.setText(dataProvider.getId());
viewHolder.name.setText(dataProvider.getName());
viewHolder.number.setText(dataProvider.getMob());
// Return the completed view to render on screen
return convertView;
}
}
The above code is UserAdapter which extends the ArrayAdapter.Try this method you will get the solution.
You can also refer this link https://github.com/codepath/android_guides/wiki/using-an-arrayadapter-with-listview
I am trying to get a list of names with total amounts from a sqlite db.
It is working in a way that shows a list of all the transactions with the
correct combined total. I also have a table in the same db that has usernames
& phone numbers, but I don't think that would be too useful for this activity.
Also, how do I use the onListItemClick to send the next activity something
that I can use to pull only names from the User the person selected? The ID
is being sent, but I don't know how to use it.
ie:
trans table:
Justin 25
Justin 25
Justin 25
Sophia 80
Hoped results:
Justin 75
Sophia 80
Actual results:
Justin 75
Justin 75
Justin 75
Sophia 80
ListActivity that populates the list (with cursor and TextView link)
public class Totals extends ListActivity {
PaymentHelper helper;
Cursor model = null;
PaymentAdapter adapter = null;
UserHelper uhelp;
Cursor umodel = null;
public final static String ID_EXTRA = "com.curtis.bookkeeping._ID";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_person);
helper = new PaymentHelper(this);
model = helper.getAll();
startManagingCursor(model);
adapter = new PaymentAdapter(model);
setListAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i = new Intent(Totals.this, Detail.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public class PaymentAdapter extends CursorAdapter {
PaymentAdapter(Cursor c) {
super(Totals.this, c, FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public void bindView(View row, Context context, Cursor c) {
PaymentHolder holder = (PaymentHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.person_row, parent, false);
PaymentHolder holder = new PaymentHolder(row);
row.setTag(holder);
return row;
}
}
static class PaymentHolder {
private TextView name_line = null;
private TextView amount_line = null;
PaymentHolder(View row) {
name_line = (TextView)row.findViewById(R.id.name_row);
amount_line = (TextView)row.findViewById(R.id.amount_row);
}
void populateFrom(Cursor c, PaymentHelper helper) {
name_line.setText(helper.getName(c));
amount_line.setText(Integer.toString(helper.sumPerson(c, helper.getName(c))));
}
}
}
SQLiteOpenHelper code to retrieve info
public class PaymentHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "bookkeeping.db";
private static final int SCHEMA_VERSION = 1;
SQLiteDatabase db;
public PaymentHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db1) {
db = db1;
String sql = "CREATE TABLE IF NOT EXISTS trans (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, date TEXT, amount INT, note TEXT)";
//execute the sql statement
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String name, String date, int amount, String note){
Log.e(name, date + " " + amount);
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("date", date);
cv.put("amount", amount);
cv.put("note", note);
Log.e("Almost", "there");
db.insert("trans", "abc", cv);
Log.e("successfully", "inserted");
}
public Cursor getAll(){
String sql = "SELECT * FROM trans ORDER BY name";
Cursor cursor = getReadableDatabase().rawQuery(sql, null);
return cursor;
}
public Cursor getAllNames(){
String sql = "SELECT * FROM users";
Cursor cursor = getReadableDatabase().rawQuery(sql, null);
return cursor;
}
public String getName(Cursor c){
return c.getString(c.getColumnIndex("name"));
}
public String getDate(Cursor c){
return c.getString(c.getColumnIndex("date"));
}
public int getAmount(Cursor c){
return c.getInt(c.getColumnIndex("amount"));
}
public String getNote(Cursor c){
return c.getString(c.getColumnIndex("note"));
}
public void delete(String id){
String[] args = {id};
getWritableDatabase().delete("trans", "_id=?", args);
}
public Cursor getById(String id){
String[] args = {id};
String sql = "SELECT * FROM trans WHERE _id=?";
Cursor cursor = getReadableDatabase().rawQuery(sql, args);
return cursor;
}
public void update(String id, String name, String date, int amount, String note){
String[] args = {id};
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("date", date);
cv.put("amount", amount);
cv.put("note", note);
getWritableDatabase().update("trans", cv, "_ID=?", args);
}
public int sumPerson(Cursor c, String name){
int total = 0;
// add up totals
String sql = "SELECT amount FROM trans WHERE name=?";
String[] aname = new String[]{name};
getReadableDatabase().rawQuery(sql,aname);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(name.equals(getName(c))){
total += c.getInt(c.getColumnIndex("amount"));
}
}
return total;
}
}
This is the activity that is receiving the ID from Totals:
I would like it to show only one user (which they selected
from the totals page) with all of their transactions.
public class Detail extends ListActivity {
PaymentHelper helper;
Cursor model = null;
PaymentAdapter adapter = null;
public final static String ID_EXTRA = "com.curtis.bookkeeping._ID";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
helper = new PaymentHelper(this);
model = helper.getAll();
startManagingCursor(model);
adapter = new PaymentAdapter(model);
setListAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.details_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.totals:
startActivity(new Intent(this, Totals.class));
break;
case R.id.users:
startActivity(new Intent(this, Users.class));
break;
case R.id.home:
startActivity(new Intent(this, MainMenu.class));
break;
}
return true;
}
#Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i = new Intent(Detail.this, DeletePayment.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public class PaymentAdapter extends CursorAdapter {
PaymentAdapter(Cursor c) {
super(Detail.this, c, FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public void bindView(View row, Context context, Cursor c) {
PaymentHolder holder = (PaymentHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
PaymentHolder holder = new PaymentHolder(row);
row.setTag(holder);
return row;
}
}
static class PaymentHolder {
private TextView name_line = null;
private TextView date_line = null;
private TextView amount_line = null;
private TextView note_line = null;
PaymentHolder(View row) {
name_line = (TextView)row.findViewById(R.id.name_line);
amount_line = (TextView)row.findViewById(R.id.amount_line);
date_line = (TextView)row.findViewById(R.id.date_line);
note_line = (TextView)row.findViewById(R.id.note_line);
}
void populateFrom(Cursor c, PaymentHelper helper) {
Log.e(helper.getName(c), Integer.toString(helper.getAmount(c)));
name_line.setText(helper.getName(c));
date_line.setText(helper.getDate(c));
amount_line.setText(Integer.toString(helper.getAmount(c)));
note_line.setText(helper.getNote(c));
}
}
}
I know this is long...but help would be awesome!
I feel like the "PaymentAdapter" needs to be modified to only
read two names if there is only two names. Should I be utilizing
the "UserHelper" db helper to populate this? but when I do, it only
runs one cursor through, and gets a nullpointerexception error because
it is not moving one of the cursors. Should I be making a PaymentAdapter
within PaymentAdapter to generate use of another cursor?
The following SQL query will give you the desired result:
SELECT name, SUM(amount)
FROM trans
GROUP BY name
I want to delete selected item from listview and Database.
I have write code for List-view and Database insertion.
But problem is with deletion i am using OnItemClick Listener for deletion of particular item.
And for deletion of item i pass Position variable to database delete method.
It work but when you delete upper item of list and than you try to delete lower item it wont delete.
May be because I am passing position variable to database delete method.and in database i am checking it with primary key ID and after deletion of upper item Id of lower item does not change so this problem occurs
suggest me some good solution
Here is code fragment code
public void onStart() {
super.onStart();
initfrag();}
private void initfrag() {
// TODO Auto-generated method stub
dh = new com.myapp.database.DatabaseHelper(getActivity());
nameArray = new ArrayList<String>();
db = new com.myapp.database.DatabaseHelper(getActivity());
list = (ListView)getView().findViewById(R.id.fevlist);
adapter=new ListAdapter(getActivity(), nameArray);
Log.d("Reading: ", "Reading all contacts..");
List<Fevorites> contacts = db.getAllContacts();
for (Fevorites cn : contacts) {
s = "Name: " + cn.getID() + " ,Phone: " + cn.getPhoneNumber()+"\n";
nameArray.add(s);
list.setAdapter(adapter);
}
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
// TODO Auto-generated method stu
nameArray.remove(position);
Toast t = Toast.makeText(getActivity(), nameArray.get(position), Toast.LENGTH_SHORT);
t.show();
// dh.Deleteitem();
adapter.notifyDataSetChanged();
adapter=new ListAdapter(getActivity(), nameArray);
list.setAdapter(adapter);
}
});
}
Here is Fevorites
public class Fevorites {
//private variables
int _id;
String _name;
String _phone_number;
// Empty constructor
public Fevorites(){
}
// constructor
public Fevorites(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Fevorites(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
Databasehelper class
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME , null,DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ARTIST + " TEXT,"
+ KEY_SONG + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void addContact( ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ARTIST, "XYZ "); // Contact Name
values.put(KEY_SONG, "XYZ testing "); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public void Deleteitem(String string)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM favorite WHERE id="+string;
db.execSQL(query);
}
// Getting All Contacts
public List<Fevorites> getAllContacts() {
List<Fevorites> contactList = new ArrayList<Fevorites>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Fevorites contact = new Fevorites();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
Fevorites getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_SONG, KEY_ARTIST }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Fevorites contact = new Fevorites(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
Here is Custom List adaptor class
*List adapter class *
public class ListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> name;
private static LayoutInflater inflater=null;
public ListAdapter(Activity a, ArrayList<String> nameArray) {
activity = a;
name = nameArray;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return name.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.fevorites_list, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.list_item_entry_title);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name.get(position));
return vi;
}
}
Normally , you retreive a List of some kind of Objects ( let's say in your case : List of favorites ) , then you pass it to your adapter to display it in a ListView . so your CustomAdapter will be like this :
public class ListAdapter extends BaseAdapter {
private Context context;
private ArrayList<Favorites> items;
private LayoutInflater inflater=null;
public ListAdapter(Context context, ArrayList<Favorites> items) {
this.context = context;
this.items = items;
inflater = LayoutInflater.from(context);
}
public int getCount() {
return items.size();
}
public Favorites getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return items.get(position).getId();
}
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.fevorites_list, parent, false);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.list_item_entry_title);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(items.get(position).getName());
return vi;
}
}
and then , instanciate the adapter and pass it to your listView like this :
//retreive the list of contacts
List<Fevorites> contacts = db.getAllContacts();
ListAdapter adapter = new ListAdapter(ActivityName.this , contacts);
list.setAdapter(adapter);
NB : replace the ActivityName by the name of your activity