i need to add my EditText details to My TextView using ActionBar and AlertDialog.
here some images to make clearView of my app,my detials are enterd in EditText
now by clicking ActionBar will popup an AlertDialog with NegativeButton and PositiveButton;now by clicking PositiveButton,i want the detial to be Stored in DataBase and TextView
but when i clicked PositiveButton Nothing Happens here!
i show my code ,that i tried below
public class MainActivity extends AppCompatActivity {
EditText firstName;
EditText lastName;
EditText mobile;
EditText password;
EditText email;
TextView textView;
List<AccountsModel>list=new ArrayList<AccountsModel>();
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper =new DatabaseHelper(this);
firstName=(EditText)findViewById(R.id.edt_firstname);
lastName=(EditText)findViewById(R.id.edt_lastname);
mobile=(EditText)findViewById(R.id.edt_mobile);
password=(EditText)findViewById(R.id.edt_password);
email=(EditText)findViewById(R.id.edt_email);
textView=(TextView)findViewById(R.id.lst_view);
AccountsModel accountsModel=new AccountsModel();
accountsModel.firstName="Rahul";
accountsModel.lastName="uday";
accountsModel.mobile="9941677745";
accountsModel.passWord="1234";
accountsModel.emailId="rahul.uday";
databaseHelper.addAccountDetials(accountsModel);
list =databaseHelper.getAllAccountList();
print(list);
}
private void print(List<AccountsModel>list)
{
String value ="";
for (AccountsModel accountsModel : list)
{
value = value+"firstName: "+accountsModel.firstName+", lastName: "+accountsModel.lastName+", mobile: "+accountsModel.mobile+", passWord: "+accountsModel.passWord+", emailId: "+accountsModel.emailId+"\n";
}
textView.setText(value);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_add) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("ADD DATA TO LIST");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
textView.setText(" ");
AccountsModel accountsModel = new AccountsModel();
accountsModel.firstName = firstName.getText().toString();
accountsModel.lastName = lastName.getText().toString();
accountsModel.mobile = mobile.getText().toString();
accountsModel.passWord = password.getText().toString();
accountsModel.emailId = email.getText().toString();
databaseHelper.addAccountDetials(accountsModel);
list = databaseHelper.getAllAccountList();
}
}).setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static String dataBaseName = "Login.db";
private static final int dataBaseVersion = 1;
private static final String tableName = "Accounts";
private static String Key_Id = "id";
private static String Key_FirstName = "firstname";
private static String Key_LastName = "lastname";
private static String Key_Password = "password";
private static String Key_Mobile = "mobile";
private static String Key_Email = "email";
public static String tag = "tag";
private static final String createTableAccounts = "CREATE TABLE " + tableName + "( " + Key_Id + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Key_FirstName + " TEXT, " + Key_LastName + " TEXT, " + Key_Password + " TEXT, " + Key_Mobile + " TEXT, " + Key_Email + " TEXT );";
public DatabaseHelper(Context context) {
super(context, dataBaseName, null, dataBaseVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createTableAccounts);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + createTableAccounts);
onCreate(db);
}
public long addAccountDetials(AccountsModel accounts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Key_FirstName, accounts.firstName);
values.put(Key_LastName, accounts.lastName);
values.put(Key_Password, accounts.passWord);
values.put(Key_Mobile, accounts.mobile);
values.put(Key_Email, accounts.emailId);
long insert = db.insert(tableName, null, values);
return insert;
}
public int updateEntry(AccountsModel accounts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Key_FirstName, accounts.firstName);
values.put(Key_LastName, accounts.lastName);
values.put(Key_Password, accounts.passWord);
values.put(Key_Mobile, accounts.mobile);
values.put(Key_Email, accounts.emailId);
return db.update(tableName, values, Key_Id + "=?", new String[]{String.valueOf(accounts.id)});
}
public void deleteEntry(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(tableName, Key_Id + " = ?", new String[]{String.valueOf(id)});
}
public AccountsModel getAccounts(long id) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "Select * FROM " + tableName + " WHERE " + Key_Id + " = " + id;
Log.d(tag, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
AccountsModel accountsModel = new AccountsModel();
accountsModel.id = c.getString(c.getColumnIndex(Key_Id));
accountsModel.firstName = c.getString(c.getColumnIndex(Key_FirstName));
accountsModel.lastName = c.getString(c.getColumnIndex(Key_LastName));
accountsModel.mobile = c.getString(c.getColumnIndex(Key_Mobile));
accountsModel.passWord = c.getString(c.getColumnIndex(Key_Password));
accountsModel.emailId = c.getString(c.getColumnIndex(Key_Email));
return accountsModel;
}
public List<AccountsModel> getAllAccountList() {
List<AccountsModel> accountsModelArrayList = new ArrayList<AccountsModel>();
String selectQuery = "SELECT * FROM " + tableName;
Log.d(tag, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
AccountsModel accountsModel = new AccountsModel();
accountsModel.id = cursor.getString(cursor.getColumnIndex(Key_Id));
accountsModel.firstName = cursor.getString(cursor.getColumnIndex(Key_FirstName));
accountsModel.lastName = cursor.getString(cursor.getColumnIndex(Key_LastName));
accountsModel.mobile = cursor.getString(cursor.getColumnIndex(Key_Mobile));
accountsModel.passWord = cursor.getString(cursor.getColumnIndex(Key_Password));
accountsModel.emailId = cursor.getString(cursor.getColumnIndex(Key_Email));
accountsModelArrayList.add(accountsModel);
} while (cursor.moveToNext());
}
return accountsModelArrayList;
}}
AccountsModel.java
public class AccountsModel {
String id;
String firstName;
String lastName;
String mobile;
String passWord;
String emailId;
public AccountsModel(String firstName,String lastName,String mobile,String passWord,String emailId)
{
this.id=id;
this.firstName=firstName;
this.lastName=lastName;
this.mobile=mobile;
this.passWord=passWord;
this.emailId=emailId;
}
public AccountsModel()
{
}}
Nothing happened because this condition is false always :
if (dialog == findViewById(R.id.action_add))
Remove it and run your app again
Related
I spend much time on SQLite and I have a problem in deleting an item if it exist!
I'm working in Bookmark App that save links from webview into listview using SQLite, my problem is can't check if the item is exist > don't create a link.
this is my BookmarksDatabase used for sqlite:
public class BookmarksDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "bookmarks.db";
private static final String TABLE_NAME = "bookmarks_data";
private static final String COL1 = "ID";
private static final String COL2 = "ITEM1";
private static final String COL3 = "ITEM2";
public BookmarksDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " ITEM1 TEXT, " + " ITEM2 TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item1, String item2) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item1);
contentValues.put(COL3, item2);
long result = db.insert(TABLE_NAME, null, contentValues);
// if date as inserted incorrectly it will return -1
return result != -1;
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}
public ArrayList<Bookmarks> getAllData() {
ArrayList<Bookmarks> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
while (data.moveToNext()) {
int id = data.getInt(0);
String title = data.getString(1);
String link = data.getString(2);
Bookmarks bookmarks = new Bookmarks(id, title, link);
arrayList.add(bookmarks);
}
return arrayList;
}
public int deleteSpecificContents(int id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, COL1 + "=?", new String[]{Integer.toString(id)});
}
}
this is my code used in MainActivity to fetch items on listview
/*---------------- Bookmark Tab, sqlite databases integrated ---------------*/
private void showBookmarksScreen() {
// initialize a dialog in the main activity
final Dialog bookmarksScreen = new Dialog(this);
bookmarksScreen.requestWindowFeature(Window.FEATURE_NO_TITLE);
bookmarksScreen.setContentView(R.layout.activity_bookmark);
bookmarksScreen.setCancelable(true);
final ListView listView = bookmarksScreen.findViewById(R.id.bookmark_list);
RelativeLayout bookmarkEmpty = bookmarksScreen.findViewById(R.id.bookmark_empty);
// create an array and call bookmark
// database to retrive data then
// fetch it into list view
arrayList = new ArrayList<>();
arrayList = bookmarkDB.getAllData();
// get all data from sqlite database
Cursor data = bookmarkDB.getListContents();
// check if no bookmarks
// then show view that inform
// user that there is no bookmarks
if(data.getCount() == 0 ) {
bookmarkEmpty.setVisibility(View.VISIBLE);
}
bookmarkListAdpater = new BookmarkListAdpater(this, arrayList);
listView.setAdapter(bookmarkListAdpater);
bookmarkListAdpater.notifyDataSetChanged();
// load link on item click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView link = view.findViewById(R.id.list_link);
String convertedLink = link.getText().toString();
webView.loadUrl(convertedLink);
bookmarksScreen.dismiss();
}
});
// ask user to delete bookmark on item long click
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
// initialize a dialog in the main activity
final Dialog deleteDialog = new Dialog(MainActivity.this);
deleteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
deleteDialog.setContentView(R.layout.activity_confirm);
// confirm message or dialog can't be
// canceled so we set it to false
deleteDialog.setCancelable(false);
TextView deleteMessage = deleteDialog.findViewById(R.id.confirm_text);
TextView deleteConfirm = deleteDialog.findViewById(R.id.confirm_allow);
TextView deleteCancel = deleteDialog.findViewById(R.id.confirm_deny);
deleteMessage.setText(getString(R.string.delete_bookmark));
// confirm button
deleteConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor data = bookmarkDB.getListContents();
int i = 0;
while(data.moveToNext()){
if(i == position){
break;
}
i++;
}
bookmarkDB.deleteSpecificContents(data.getInt(0));
deleteDialog.dismiss();
bookmarksScreen.dismiss();
customToast(getString(R.string.bookmark_deleted), 0);
}
});
// confirm cancel
deleteCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteDialog.dismiss();
}
});
deleteDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
deleteDialog.show();
return true;
}
});
bookmarksScreen.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
bookmarksScreen.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
bookmarksScreen.show();
}
My Model
public class Bookmarks {
int id;
String title, link;
public Bookmarks(int id, String title, String link) {
this.id = id;
this.title = title;
this.link = link;
}
public Bookmarks() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
any ideas? thanks.
Try using below to delete item from DB
bookmarkDB.deleteSpecificContents(arrayList.get(position).getId(0));
If you want to check item exists or not before adding then add below code in your BookmarksDatabase
public boolean isExists(String link) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COL3 + "='" + link + "'", null);
return cursor.getCount() > 0;
}
And then check
if(bookmarkDB.isExists(link))
//Already Exist
else
//Not Exist, add now
With the same logic you're using:
SQLiteDatabase db = new DatabaseManager(context).getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + ID_KEY + " = ?";
Cursor cursor = db.rawQuery(query, new String[]{Integer.toString(id)});
if(cursor.moveToFirst()){
db.delete(TABLE_NAME, ID_KEY + " = ?", new String[]{Integer.toString(id)});
}
cursor.close();
db.close();
Another possibility is changing the method return type to boolean and verifying the return count from the delete command:
public boolean deleteSpecificContents(int id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, COL1 + "=?", new String[]{Integer.toString(id)}) > 0;
}
I have a SQLdatabase and I want to delete entries that are displayed in a list view using a button that is next to each entry on the list view. But currently it is not letting me delete.
This problem is located in the selectionargs variable as shown below. If I put a number e.g. 1, into the selectionargs manually it will work, but I have been trying to do it through the a variable that represents each entry. This does not result in an error but just goes straight to the toast message cannot delete. ac.ID refers to the adapter class and the ID of the list item entries.
Bookmark class:
public class Bookmark extends AppCompatActivity {
myAdapter myAdapter;
DBManager db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookmark);
db = new DBManager(this);
onLoadAttraction();
// onLoadTransport();
}
public void onLoadAttraction() {
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
Cursor cursor = db.Query("BookmarkAttraction",null, null, null, DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
cursor.getString(cursor.getColumnIndex(DBManager.ColType))
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, cursor.getString(cursor.getColumnIndex(DBManager.ColOpening))
, cursor.getString(cursor.getColumnIndex(DBManager.ColClosing))
, cursor.getString(cursor.getColumnIndex(DBManager.ColNearbyStop))
,null,null,null, null, null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ListView ls = (ListView) findViewById(R.id.listView);
ls.setAdapter(myAdapter);
}
public void onLoadTransport(){
ArrayList<Adapter> listData = new ArrayList<Adapter>();
listData.clear();
Cursor cursor = db.Query("BookmarkTransport",null, null, null, DBManager.ColId);
if (cursor.moveToFirst()) {
do {
listData.add(new Adapter(
cursor.getString(cursor.getColumnIndex(DBManager.ColType))
, cursor.getString(cursor.getColumnIndex(DBManager.ColName))
, cursor.getString(cursor.getColumnIndex(DBManager.ColLocation))
, null
, null
, null
,cursor.getString(cursor.getColumnIndex(DBManager.ColTime))
,cursor.getString(cursor.getColumnIndex(DBManager.ColNextStop))
, cursor.getString(cursor.getColumnIndex(DBManager.ColPhoneNumber))
,null,null));
} while (cursor.moveToNext());
}
myAdapter = new myAdapter(listData);
ListView ls = (ListView) findViewById(R.id.listView);
ls.setAdapter(myAdapter);
}
class myAdapter extends BaseAdapter {
public ArrayList<Adapter> listItem;
Adapter ac;
public myAdapter(ArrayList<Adapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater myInflator = getLayoutInflater();
final View myView = myInflator.inflate(R.layout.list_bookmark, null);
ac = listItem.get(position);
TextView Type = (TextView) myView.findViewById(R.id.BMType);
Type.setText(ac.Type);
TextView Name = (TextView) myView.findViewById(R.id.BMName);
Name.setText(ac.Name);
TextView Location = (TextView) myView.findViewById(R.id.BMLocation);
Location.setText(ac.Location);
TextView Opening = (TextView) myView.findViewById(R.id.BMOpen);
Opening.setText(ac.Opening);
TextView Closing = (TextView) myView.findViewById(R.id.BMClose);
Closing.setText(ac.Closing);
TextView NearbyStop1 = (TextView) myView.findViewById(R.id.BMNearbyStop);
NearbyStop1.setText(ac.NearbyStop);
Button buttonDelete = (Button)myView.findViewById(R.id.buttonDelete);
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] selectionArgs = {ac.ID};
int count = db.Delete("BookmarkAttraction","ID=? ",selectionArgs);
if (count > 0) {
onLoadAttraction();
Toast.makeText(getApplicationContext(),"Data deleted", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Cannnot delete", Toast.LENGTH_LONG).show();
}
}
});
return myView;
}
}
}
DBManager class:
public class DBManager {
private SQLiteDatabase sqlDB;
static final String ColId = "ID";
static final String DBName = "InternalDB";
static final String TableName = "BookmarkAttraction";
static final String TableName2 = "BookmarkTransport";
static final String TableName3 = "Itinerary";
static final String ColItineraryName = "ItineraryName";
static final String ColDate = "Date";
static final String ColType = "Type";
static final String ColName = "Name";
static final String ColLocation = "Location";
static final String ColOpening = "OpeningTime";
static final String ColClosing = "ClosingTime";
static final String ColNearbyStop = "NerbyStop1";
static final String ColTime = "Time";
static final String ColNextStop = "NextStop";
static final String ColPhoneNumber = "PhoneNumber";
static final int DBVersion = 1;
static final String CreateTable = "CREATE TABLE IF NOT EXISTS " + TableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColType+ " TEXT," +
ColName+ " TEXT," + ColLocation+ " TEXT," + ColOpening+ " TEXT," +ColClosing+ " TEXT," + ColNearbyStop+ " TEXT);";
static final String CreateTabe2 = "CREATE TABLE IF NOT EXISTS " +TableName2 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ ColType + " TEXT,"
+ ColName + " TEXT,"
+ ColLocation + " TEXT,"
+ ColTime+ " TEXT,"
+ ColNextStop + " TEXT,"
+ ColPhoneNumber + " TEXT);";
static final String CreateTable3 = "CREATE TABLE IF NOT EXISTS " + TableName3 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColItineraryName + " TEXT,"
+ ColDate + " TEXT," + ColName + " TEXT," + ColLocation + " TEXT," + ColTime + " TEXT);";
static class DBHelper extends SQLiteOpenHelper{
Context context;
DBHelper(Context context){
super(context, DBName, null, DBVersion);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
Toast.makeText(context,DBName,Toast.LENGTH_LONG).show();
db.execSQL(CreateTable);
Toast.makeText(context,"Table is created ", Toast.LENGTH_LONG).show();
db.execSQL(CreateTabe2);
Toast.makeText(context,"Transport table created", Toast.LENGTH_LONG).show();
db.execSQL(CreateTable3);
Toast.makeText(context,"Itin table created", Toast.LENGTH_LONG).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TableName);
db.execSQL("DROP TABLE IF EXISTS" + TableName2);
db.execSQL("DROP TABLE IF EXISTS" + TableName3);
onCreate(db);
}
}
public DBManager(Context context){
DBHelper db = new DBHelper(context);
sqlDB = db.getWritableDatabase();
}
public long Insert(String tablename,ContentValues values){
long ID = sqlDB.insert(tablename,"",values);
return ID;
}
public Cursor Query(String tablename, String [] projection, String selection, String [] selectionArgs, String sortOrder){
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tablename);
Cursor cursor = qb.query(sqlDB,projection, selection, selectionArgs,null,null,sortOrder);
return cursor;
}
public int Delete(String tablename,String selection, String[] selectionArgs){
int count = sqlDB.delete(tablename,selection,selectionArgs);
return count;
}
}
Adapter class:
public class Adapter {
public String ID;
public String Type;
public String Name;
public String Location;
public String Opening;
public String Closing;
public String NearbyStop;
public String Time;
public String NextStop;
public String PhoneNumber;
public String Latitude;
public String Longitude;
public Adapter(String type, String name, String location, String opening, String closing,
String nearbyStop, String time, String nextStop, String phoneNumber, String Latitude,
String Longitude) {
this.Type = type;
this.Name = name;
this.Location = location;
this.Opening = opening;
this.Closing = closing;
this.NearbyStop = nearbyStop;
this.Time = time;
this.NextStop = nextStop;
this.PhoneNumber = phoneNumber;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
}
The code for the delete button is in my bookmark class with the DBManager holding the actual delete code. If anyone can help with this it would be greatly appreciated.
Remove the ac field of your myAdapter class, and use it as a method variable inside the getView method.
Then use the ListView.setOnItemClickListener method to add an on click listener with positional awareness. (do this only once after you set the adapter) This way you can do listItem.get(position) to get the item in that position.
I am developing an app for listing details in database. The listing is not working. but it is showing in log as fine. Why my recyclerview listling is not working. when i am using bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()) it shows error.
My codes are shown below.
SpeedDialViewActivity.java
public class SpeedDialViewActivity extends AppCompatActivity {
private List<Bean> beanList = new ArrayList<>();
private RecyclerView recyclerView;
private ViewAdapter mAdapter;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_dial_view);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new ViewAdapter(beanList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareData();
}
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
//Cursor cursor = (Cursor) handler.getAllContacts();
//Bean bean1;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
// bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()); // Error occurring
// beanList.add(bean1);
}
}
}
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "speeddial";
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_SPEED_DIAL = "speed_dial_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_SPEED_DIAL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
void addContact(Bean bean) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, bean.getName()); // Contact Name
values.put(KEY_PH_NO, bean.getNumber()); // Contact Phone
values.put(KEY_PH_NO, bean.getSpeeddial()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
Bean getBean(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Bean bean = new Bean(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return bean;
}
public List<Bean> getAllContacts() {
List<Bean> contactList = new ArrayList<Bean>();
// 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 {
Bean contact = new Bean();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
ViewAdapter.java
public class ViewAdapter extends RecyclerView.Adapter<ViewAdapter.MyViewHolder> {
private List<Bean> beanList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, number, speeddial_number;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
number = (TextView) view.findViewById(R.id.number);
speeddial_number = (TextView) view.findViewById(R.id.speeddialNumber);
}
}
public ViewAdapter(List<Bean> beanList){
this.beanList = beanList;
}
#Override
public ViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.speeddial_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewAdapter.MyViewHolder holder, int position) {
Bean bean = beanList.get(position);
holder.name.setText(bean.getName());
holder.number.setText(bean.getNumber());
holder.speeddial_number.setText(bean.getSpeeddial());
}
#Override
public int getItemCount() {
return beanList.size();
}
}
Bean.java
public class Bean{
private int id;
private String name;
private String number;
private String speeddial;
public Bean(int id, String name, String number, String speeddial) {
this.id=id;
this.name=name;
this.number=number;
this.speeddial=speeddial;
}
public Bean(String name, String number, String speeddial) {
this.name=name;
this.number=number;
this.speeddial=speeddial;
}
public Bean() {
}
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 getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getSpeeddial() {
return speeddial;
}
public void setSpeeddial(String speeddial) {
this.speeddial = speeddial;
}
}
The error is java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.appname/com.app.appname}: java.util.ConcurrentModificationException
Please help me
You are not adding the contacts you are fetching in the list and not doing notify data set changed. Change your onPrepare() method as follows
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
this.beanList.addAll(beanList);
mAdapter.notifyDatasetChanged();
}
pass the same list in prepareData(beanList) and add items in this list. And change your method to something likeprepareData(List<Bean> beanList>).after successfully adding, simply call mAdapter.notifyDataSetChanged() method so your adapter could know that some items have been added into the list.
You have not mention android:name in application tag in manifest file.
So you simple use context object or use SpeedDialViewActivity.this
DatabaseHandler handler = new DatabaseHandler(mContext);
or
DatabaseHandler handler = new DatabaseHandler(SpeedDialViewActivity.this);
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(SpeedDialViewActivity.this);
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
//Cursor cursor = (Cursor) handler.getAllContacts();
//Bean bean1;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
// bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()); // Error occurring
// beanList.add(bean1);
}
}
Im trying to update a users current credits, but I don't want to replace the value, just add on a selected amount from the spinner and add it on to the the users current credits? Thank you.
My database code?
package com.example.parkangel;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " INTEGER NOT NULL, " + KEY_CREDITS + "
INTEGER NOT NULL);");
ContentValues values = new ContentValues();
values.put(KEY_PFNAME, "Tutku");
values.put(KEY_PSNAME, "Erbil");
values.put(KEY_CARD, "12345677");
values.put(KEY_CREDITS, 5);
db.insert(DATABASE_TABLE, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname) + " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
public void upDateUser(String money) {
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, money);
ourDatabase.update(DATABASE_TABLE, cvUpdate, null, null);
}
}
Class that needs to perform the actoin:
package com.example.parkangel;
public class Balance extends Activity implements OnClickListener{
Button add;
TextView display;
Spinner spinner3;
Integer[] money = new Integer[] {1, 2, 5, 10};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
//db.addUser();
db.close();
tv.setText(data);
ArrayAdapter<Integer> adapter3 = new ArrayAdapter<Integer>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
add.setOnClickListener(this);
//add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
switch (arg0.getId()){
case R.id.topup:
boolean work = true;
try{
String money = spinner3.getContext().toString();
UDbHelper ud = new UDbHelper(this);
ud.open();
ud.upDateUser(money);
ud.close();
}catch (Exception e){
work = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Unable To TopUp!");
TextView dg = new TextView(this);
dg.setText(error);
d.setContentView(dg);
d.show();
}finally{
if(work){
Dialog d = new Dialog(this);
d.setTitle("You Have ToppedUp!");
TextView dg = new TextView(this);
dg.setText("TopUp Successful");
d.setContentView(dg);
d.show();
}
}
break;
}
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
First of all you should have an ID that will let you find the user you are interested in. That do a select to get the current value that is stored in database. Parse the value to integer and add "new" money. And finally, update the value in database.
public void upDateUser(String ID, String money) {
String query = "Select money from TABLE_NAME where ID = " + ID;
SQLiteDatabase db = this.getWriteableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int oldMoney = 0;
if (cursor.moveToFirst()) {
oldMoney = Integer.parseInt(cursor.getString(0)); //Cause we get only from money column
}
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, oldMoney + money);
String filter = "UID" + "=" + ID;
db.update(DATABASE_TABLE, cvUpdate, filter, null);
}
Of course you have to check if cursor returns exactly one row and do some other checks.
I'm trying to add site details to a database and then after I insert a row, output the result to a TextView. The record is being inserted into the database because it's being shown in a TextView, however I can only insert one record and I'm not sure why. I'm been using the tutorial here and modifying it to meet my needs.
Here is my DBAdapter:
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String username,
String password, int port) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_PORT, port);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, String port) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
// newValues.put(KEY_PASSWORD, password);
// newValues.put(KEY_PORT, port);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
I'm querying the database here:
public class FTPConnector extends Activity {
DBAdapter myDb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.ftp);
status = (TextView) findViewById(R.id.status);
editAddress = (EditText) findViewById(R.id.editAddress);
editUser = (EditText) findViewById(R.id.editUsername);
editPassword = (EditText) findViewById(R.id.editPassword);
addsiteBtn = (Button) findViewById(R.id.addsiteBtn);
addsiteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
siteManager();
}
});
openDb();
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
//Where the insertRecord() happens
public void siteManager() {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.site_manager, null);
final EditText tmpname = (EditText) view
.findViewById(R.id.dialogsitename);
final EditText tmpaddress = (EditText) view
.findViewById(R.id.dialogaddress);
final EditText tmpuser = (EditText) view
.findViewById(R.id.dialogusername);
final EditText tmppass = (EditText) view
.findViewById(R.id.dialogpassword);
final EditText tmpport = (EditText) view.findViewById(R.id.dialogport);
final TextView tmpsites = (TextView) view.findViewById(R.id.textView6);
final CheckBox tmppassive = (CheckBox) view
.findViewById(R.id.dialogpassive);
final Button tmpclose = (Button) view.findViewById(R.id.closeBtn);
final Button tmptestBtn = (Button) view.findViewById(R.id.testBtn);
final Button tmpsavetsite = (Button) view.findViewById(R.id.saveSite);
customDialog.setView(tmpclose);
customDialog.setView(tmptestBtn);
customDialog.setView(tmpname);
customDialog.setView(tmpaddress);
customDialog.setView(tmpuser);
customDialog.setView(tmppass);
customDialog.setView(tmpport);
customDialog.setView(tmppassive);
customDialog.setView(tmpsavetsite);
customDialog.setView(tmpsites);
tmpclose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
tmptestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
_passive = false;
if (tmppassive.isChecked()) {
_passive = true;
}
boolean status = ftpConnect(_address, _user, _pass, _port);
if (status == true) {
Toast.makeText(FTPConnector.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(FTPConnector.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
tmpsavetsite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tmpsites.setText("");
String msg = "!";
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
long newId = myDb.insertRow(_name, _address, _user, _pass, 21);
Cursor c = myDb.getAllRows();
if (c.moveToFirst()) {
int id = c.getInt(0);
String _name = c.getString(1);
String _address = c.getString(2);
String _user = c.getString(3);
String _pass = c.getString(4);
int _port = c.getInt(5);
msg += "id=" + id + "\n";
msg += ", name=" + _name + "\n";
msg += ", address=" + _address + "\n";
msg += ", username=" + _user + "\n";
msg += ", password=" + _pass + "\n";
msg += ", port=" + _port + "\n";
while (c.moveToNext());
}
c.close();
// displayText(msg);
tmpsites.setText(msg);
}
});
customDialog.setView(view);
customDialog.show();
}
Why can't I add more than one record?
In here :
while (c.moveToNext()); //<<<
currently you are not using any loop like do-while for iterating through cursor(you forget to add do block with while). get all data from cursor as using for loop:
//more to the first row
c.moveToFirst();
//iterate over rows
for (int i = 0; i < c.getCount(); i++) {
// get all data here from current row..
//move to the next row
c.moveToNext();
}
//close the cursor
c.close();
and using do-while you can get all values from current row as:
c.moveToFirst(); //more to the first row
do {
// get all data here from current row..
} while (c.moveToNext());