how to display sqllite inserting data using recyclerview in android studio - android

I am new to android.
When I insert data it works properly. but while I click the button for displaying the inserted data using recyclerview it makes following error message: Sqlite Insert and View has stopped.
Error message is like:
at
com.example.sqliteinsertandview.MainActivity.ShowData(MainActivity.java:56)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
MainActivity code:
public class MainActivity extends AppCompatActivity {
private EditText nameEt, ageEt;
private Button insertBtn;
String name, age;
DatabaseHelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
insertData();
}
private void insertData() {
insertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEt.getText().toString();
age = ageEt.getText().toString();
long id = helper.insertData(name, age);
Toast.makeText(MainActivity.this, "Your id" + id, Toast.LENGTH_SHORT).show();
}
});
}
private void init() {
nameEt = findViewById(R.id.nameEt);
ageEt = findViewById(R.id.ageEt);
insertBtn = findViewById(R.id.insertBtn);
helper = new DatabaseHelper(this);
}
public void ShowData(View view) {
startActivity(new Intent(this, ShowActivity.class));
}
}
ShowActivity Code:
public class ShowActivity extends AppCompatActivity {
RecyclerView recyclerView;
UserAdapter adapter;
List<User> users;
DatabaseHelper helper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
init();
getData();
}
private void getData(){
Cursor cursor = helper.showData();
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(helper.COL_ID));
String name = cursor.getString(cursor.getColumnIndex(helper.COL_NAME));
String age = cursor.getString(cursor.getColumnIndex(helper.COL_AGE));
users.add(new User(id,name,age));
adapter.notifyDataSetChanged();
}
}
private void init(){
recyclerView = findViewById(R.id.userRecyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
users = new ArrayList<>();
helper = new DatabaseHelper(this);
adapter = new UserAdapter(users);
recyclerView.setAdapter(adapter);
}
DatabaseHelper code:
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "User.db";
private static String TABLE_NAME = "User";
public static String COL_ID = "Id";
public static String COL_NAME = "Name";
public static String COL_AGE = "Age";
private static int VERSION = 1;
private static String createTable = "create table "+TABLE_NAME+"(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age TEXT)";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
long insertData(String name, String age){
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME,name);
contentValues.put(COL_AGE,age);
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
long id = sqLiteDatabase.insert(TABLE_NAME,null,contentValues);
sqLiteDatabase.close();
return id;
}
public Cursor showData(){
String show_all = " select* From "+TABLE_NAME;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(show_all,null);
return cursor;
}
}

You didn't add ShowActivity class in AndroidManifest.xml file. Add this inside application tag
<activity android:name=".ShowActivity"/>

Related

Data repeating on restarting App in Android Database

I am facing this problem whenever i run the app 1st time data in database remain single time but when i close the App and restart again data goes twice(means two same row in table).Similarly for 3rd, 4th time and so on. How do i get rid of this problem? I even put datas.clear in DataList.java but don't whether i have add the datas.clear() line in correct place or not.
PLz help if there is any other problem in my code.
MainActivity.java code
public class MainActivity extends AppCompatActivity {
Button listButton, addButton;
DatabaseHelper df;
private final static String TAG = "TestActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
df = new DatabaseHelper(this);
addButton = (Button) findViewById(R.id.addbutton);
uploadList();
}
public void uploadList(){
DatabaseHelper df=new DatabaseHelper(this);
df.open();
try{
InputStream im=getResources().getAssets().open("testdata.csv");
BufferedReader br=new BufferedReader(new InputStreamReader(im));
String data=br.readLine();
while(data != null){
String t[]=data.split(",");
Product p=new Product();
p.setFirst(t[0]);
p.setSec(t[1]);
p.setThird(t[2]);
df.insert(p);
data=br.readLine();
}
}catch(Exception e){
}
}
}
DatabaseHelper.java code
public class DatabaseHelper extends SQLiteOpenHelper{
private static final String FIRST="Name";
private static final String SECOND="Issn";
private static final String THIRD="ImpactFactor";
private static final String DATABASE="journal2016";
private static final String TABLENAME="journal";
private static final int VERSION=1;
SQLiteDatabase sd;
public void open(){
sd=getWritableDatabase();
}
public void close(){
sd.close();
}
public DatabaseHelper(Context context) {
super(context, DATABASE, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME );
sqLiteDatabase.execSQL("CREATE TABLE " + TABLENAME + " ( NAME TEXT, ISSN TEXT, IMPACTFACTOR REAL)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME );
}
public long insert(Product p){
ContentValues cv=new ContentValues();
cv.put(FIRST, p.getFirst());
cv.put(SECOND, p.getSec());
cv.put(THIRD, p.getThird());
return sd.insertWithOnConflict(TABLENAME, null, cv,SQLiteDatabase.CONFLICT_REPLACE);
}
public List<Product> getAllProduct(){
ArrayList<Product> list=new ArrayList<Product>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c=db.rawQuery("SELECT * FROM " + TABLENAME, null);
while(c.moveToNext()){
Product p=new Product();
p.setFirst(c.getString(0));
p.setSec(c.getString(1));
p.setThird(c.getString(2));
list.add(p);
}
db.close();
return list;
}
}
DataList.java code
public class DataList extends Activity{
List<Product> datas = new ArrayList<Product>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
datas.clear();
DatabaseHelper d=new DatabaseHelper(this);
d.open();
datas = d.getAllProduct();
ListView lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, datas));
}
}
Product.java
public class Product {
private String first;
private String second;
private String third;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSec() {
return second;
}
public void setSec(String sec) {
this.second = sec;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
#Override
public String toString() {
return first + second + third;
}
}
Remove this line from your onCreate() method:
df = new DatabaseHelper(this);
as no need of it because you are create object of your DatabaseHelper class inside uploadList() method.
And also you are calling uploadList() method inside onCreate() thats why every time you launch the app, the onCreate() method executes and you uploadList() also execute. Try to put its calling statement in an onClickListener so it happens when you click a button or your choice of stuff.

Get data from setOnItemClickListener and pass another activity

I have a listview and a SQL database. In my SQL database, there is a title and a content field. I display titles on a listview. Now this is what I'm trying to achieve: When I click the title, this should pass me to another activity and in this activity I want to see relative content in edittext. And sorry for my poor English.
This is my code.
DB CLASS.
public class NoteAlDatabase extends SQLiteOpenHelper {
private static final String VERITABANI_ISMI = "veritabanim2.db";
private static final int VERITABANI_VERSION = 1;
private static final String TABLO_ISMI = "noteAlTablosu";
public static final String ID = "_id";
public static final String NOTEBASLIK= "noteTitle";
public static final String NOTEICERIK = "noteContent";
final Context c;
private SQLiteDatabase db;
public NoteAlDatabase(Context context) {
super(context, VERITABANI_ISMI, null, VERITABANI_VERSION);
this.c = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String tablo_olustur = "CREATE TABLE " + TABLO_ISMI +
" ("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
NOTEBASLIK + " TEXT, " +
NOTEICERIK + " TEXT);";
db.execSQL(tablo_olustur);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + TABLO_ISMI);
onCreate(db);
}
public NoteAlDatabase abrirBaseDeDatos() throws SQLException {
NoteAlDatabase noteAlDatabase = new NoteAlDatabase(c);
noteAlDatabase.getWritableDatabase();
return this;
}
public long addReminder(NoteAlModel noteAl) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ID, noteAl.getNoteAlID());
cv.put(NOTEBASLIK, noteAl.getNoteAlBaslik());
cv.put(NOTEICERIK, noteAl.getNoteAlIcerik());
// tarih'te eklenecek /long cinsinden
long id = db.insert(TABLO_ISMI,null,cv);
db.close();
return id;
}
public List<NoteAlModel> AllData() {
SQLiteDatabase db = this.getReadableDatabase();
String[] sutunlar = new String[]{ID,NOTEBASLIK,NOTEICERIK};
Cursor c =db.query(TABLO_ISMI, sutunlar,null,null,null,null,null);
int idsirano = c.getColumnIndex(ID);
int basliksirano = c.getColumnIndex(NOTEBASLIK);
int iceriksirano = c.getColumnIndex(NOTEICERIK);
List<NoteAlModel> liste = new ArrayList<NoteAlModel>();
for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
NoteAlModel noteAlModel = new NoteAlModel();
noteAlModel.setNoteAlID(c.getString(idsirano));
noteAlModel.setNoteAlBaslik(c.getString(basliksirano));
noteAlModel.setNoteAlIcerik(c.getString(iceriksirano));
liste.add(noteAlModel);
}
db.close();
return liste;
}
public void Sil(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLO_ISMI, null, null);
}
ListViewActivity:
public class NoteListele extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_listele);
Button btn = (Button) findViewById(R.id.btnYeniNotKaydet);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NoteListele.this, NoteAlActivity.class);
startActivity(intent);
}
});
try {
displayListview();
} catch (Exception e) {
Toast.makeText(NoteListele.this, "Listelenecek veri bulunmamakta", Toast.LENGTH_SHORT).show();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
public void displayListview() {
NoteAlDatabase db = new NoteAlDatabase(getApplicationContext());
List<NoteAlModel> liste = new ArrayList<NoteAlModel>();
liste = db.AllData();
ArrayAdapter arrayAdapter = new ArrayAdapter<NoteAlModel>(this, android.R.layout.simple_list_item_1, liste);
listView.setAdapter(arrayAdapter);
}
public void deleteAllData(View view) {
NoteAlDatabase db = new NoteAlDatabase(getApplicationContext());
db.Sil();
//displayListview();
}
GETSET Model:
public class NoteAlModel {
private String noteAlID;
private String noteAlBaslik;
private String noteAlIcerik;
public NoteAlModel() {
}
public NoteAlModel(String noteAlID, String noteAlBaslik, String noteAlIcerik) {
this.noteAlID = noteAlID;
this.noteAlBaslik = noteAlBaslik;
this.noteAlIcerik = noteAlIcerik;
}
public NoteAlModel(String noteAlBaslik, String noteAlIcerik) {
this.noteAlBaslik = noteAlBaslik;
this.noteAlIcerik = noteAlIcerik;
}
public String getNoteAlID() {
return noteAlID;
}
public void setNoteAlID(String noteAlID) {
this.noteAlID = noteAlID;
}
public String getNoteAlBaslik() {
return noteAlBaslik;
}
public void setNoteAlBaslik(String noteAlBaslik) {
this.noteAlBaslik = noteAlBaslik;
}
public String getNoteAlIcerik() {
return noteAlIcerik;
}
public void setNoteAlIcerik(String noteAlIcerik) {
this.noteAlIcerik = noteAlIcerik;
}
logcat
03-06 20:16:46.095 4886-4886/reminderplus.reminder2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: reminderplus.reminder2, PID: 4886
java.lang.NoSuchMethodError: No virtual method AllData()Landroid/database/Cursor; in class Lreminderplus/reminder2/veritabani/NoteAlDatabase; or its super classes (declaration of 'reminderplus.reminder2.veritabani.NoteAlDatabase' appears in /data/data/reminderplus.reminder2/files/instant-run/dex/slice-slice_9_4376acd355cb0a9e536cff445d1b4b60f3d0940d-classes.dex)
at reminderplus.reminder2.noteal.NoteListele.onCreate(NoteListele.java:46)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
You have not to convert your Cursor into List<NoteAlModel>. You can use Cursor with SimpleCursorAdapter.
In this case your AllData Method will look like:
public Cursor AllData() {
SQLiteDatabase db = this.getReadableDatabase();
String[] sutunlar = new String[]{ID,NOTEBASLIK,NOTEICERIK};
Cursor c = db.query(TABLO_ISMI, sutunlar,null,null,null,null,null);
db.close();
return c;
}
Then you create a SimpleCursorAdapter and set it to your ListView
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
db.AllData(),
new String[] { NoteAlDatabase.NOTEBASLIK },
new int[] { android.R.id.text1 });
listView.setAdapter(scAdapter);
After that you have a ListView with your "titles" and now let's manage your setOnItemClickListener to open a "content" in new activtiy.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String content = ((SimpleCursorAdapter)parent.getAdapter()).
getCursor().getString(NoteAlDatabase.NOTEICERIK);
Intent intent = new Intent(getApplicationContext(), ContentActivity.class);
intent.putExtra("PARAM", content);
startActivity(intent);
}
});
And now you can obtain the content in ContentActivity's onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
//...
String content = getIntent().getExtras().getString("PARAM", "");
// show content in some `TextView`
}

recyclerView doesn't show the 'real' data for my list items

I have implemented a recyclerView and a SQLite database to save/retrieve data for the recylerview, but the data I get on the recyclerView is not the data that should show. The recyclerView worked as it should without the SQLite db.
When the plus sign is clicked, a dialog will popup with editext fields, where the user can type the information:
Here is the DialogFragment class where the user shall write their information:
public class DialogAdd extends DialogFragment {
private Button okButton;
private EditText name, quantity, location, normalPrice, offerPrice;
private List<ShopListItem> shopListItem;
private Context context;
DatabaseHelper dbHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DatabaseHelper(getContext());
shopListItem = new ArrayList<>();
context = getActivity();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.add_productdialog,container, false);
getDialog().setCanceledOnTouchOutside(false);
getDialog().setTitle("Add to shoplist");
name = (EditText) rootView.findViewById(R.id.dialog_productname);
quantity = (EditText) rootView.findViewById(R.id.dialog_qantity);
location = (EditText) rootView.findViewById(R.id.dialog_location);
normalPrice = (EditText) rootView.findViewById(R.id.dialog_normalPrice);
offerPrice = (EditText) rootView.findViewById(R.id.dialog_offerPrice);
okButton = (Button) rootView.findViewById(R.id.dialog_okButton);
okButton.getBackground().setColorFilter(Color.parseColor("#2fbd4b"), PorterDuff.Mode.MULTIPLY);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (name.getText().toString().isEmpty()) {
Toast.makeText(context, "You must add a name", Toast.LENGTH_LONG).show();
} else {
dbHelper.insertData(name.toString() ,quantity.toString(),location.toString(),normalPrice.toString(),offerPrice.toString());
getDialog().dismiss();
}
}
});
return rootView;
}
This is the mainActivity class where I create the recylerview, adapters and Database:
public class MainActivity extends AppCompatActivity{
private ImageButton addbutton;
private DialogAdd dialogAdd;
public static RecyclerView recyclerView;
private List<ShopListItem> shopListItems;
private SQLiteDatabase db;
private Cursor cursor;
private DatabaseHelper databaseHelper;
private ShoplistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppinglist_mainactivity);
databaseHelper = new DatabaseHelper(this);
addbutton = (ImageButton) findViewById(R.id.addbtn);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogAdd = new DialogAdd();
dialogAdd.show(getSupportFragmentManager(), "addDialog");
}
});
//RecyclerView
recyclerView = (RecyclerView)findViewById(R.id.rv_shoppinglist);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(App.getAppContex());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
initializeData();
adapter = new ShoplistAdapter(shopListItems);
recyclerView.setAdapter(adapter);
}
private void initializeData(){
shopListItems = new ArrayList<>();
Cursor resultset = databaseHelper.getAllData();
if (resultset.moveToFirst()){
while(!resultset.isAfterLast()){
shopListItems.add(new ShopListItem(resultset.getString(1), resultset.getString(2), resultset.getString(3), resultset.getString(4), resultset.getString(5)));
resultset.moveToNext();
}
}
resultset.close();
shopListItems.add(new ShopListItem("Potato", "2 KG", "MALL", "7 kr", ""));
}
This class is where the database is defined:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="dbshoplist.db";
public static final String TABLE_NAME ="product_table";
public static final String COL_ID = "ID";
public static final String COL_NAME ="NAME";
public static final String COL_QTY ="QUANTITY";
public static final String COL_LOCATION ="LOCATION";
public static final String COL_PRICE1 ="PRICE1";
public static final String COL_PRICE2 ="PRICE2";
/*
This constructor creates the database
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,QUANTITY TEXT,LOCATION TEXT,PRICE1 TEXT,PRICE2 TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String qty, String location, String price1, String price2){
SQLiteDatabase db = this.getWritableDatabase();
// content value is a row, and we fill it with the put();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_QTY, qty);
contentValues.put(COL_LOCATION, location);
contentValues.put(COL_PRICE1, price1);
contentValues.put(COL_PRICE2, price2);
long result = db.insert(TABLE_NAME, null,contentValues);
if(result == -1) {
return false;
}else{
return true;
}
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursorResults = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return cursorResults;
}
My recyclerView adapter class:
public class ShoplistAdapter extends RecyclerView.Adapter<ShoplistAdapter.ViewHolder>{
List<ShopListItem> shopListItems;
public ShoplistAdapter(List<ShopListItem> shopListItems) {
this.shopListItems = shopListItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View shoplist_itemView = inflater.inflate(R.layout.shop_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(shoplist_itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.location.setText(shopListItems.get(position).location.toString());
holder.normalPrice.setText(shopListItems.get(position).normalprice.toString());
holder.offerPrice.setText(shopListItems.get(position).offerprice.toString());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(shopListItems.get(position).quantity + " " + shopListItems.get(position).name);
holder.productname.setText(stringBuilder);
if(!shopListItems.get(position).offerprice.toString().isEmpty()){
holder.normalPrice.setPaintFlags(holder.normalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
if(shopListItems.get(position).normalprice.isEmpty()){
holder.normalPrice.setVisibility(View.GONE);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
holder.productname.setPaintFlags(holder.productname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.productname.setTextColor(Color.parseColor("#40000000"));
}else{
holder.productname.setPaintFlags(0 | Paint.ANTI_ALIAS_FLAG);
holder.productname.setTextColor(Color.BLACK);
}
}
});
}
#Override
public int getItemCount() {
return shopListItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private CheckBox checkBox;
private TextView productname, quantity, location, normalPrice, offerPrice;
private ImageButton edit_icon, delete_icon;
public ViewHolder(View itemView) {
super(itemView);
productname = (TextView)itemView.findViewById(R.id.product_name);
location = (TextView)itemView.findViewById(R.id.product_location);
normalPrice = (TextView)itemView.findViewById(R.id.product_price);
offerPrice = (TextView)itemView.findViewById(R.id.product_offer_price);
edit_icon = (ImageButton)itemView.findViewById(R.id.editShopItem_Icon);
delete_icon = (ImageButton)itemView.findViewById(R.id.shopitem_delete_icon);
checkBox = (CheckBox) itemView.findViewById(R.id.bought_checkbox);
}
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
This is happening because you're calling the toString() method of fields of the ShopListItem object: shopListItems.get(position).location.toString().
Instead, create getter methods for the fields of your ShopListItem class, e.g.
public getLocation() {
return location;
}
and just call these to get the data.

Populating Listview from Database Only Works Once

I'm trying to update a listview with user entries into two text inputs. Once the save button is clicked, the user's entry should appear. Based on my code, the listview updates the first time I fill out the two text inputs and I hit save, but the second time I hit save, the listview does not update. Here's my code:
Home.java
public class Home extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
EditText inputOne;
EditText inputTwo;
MyDBHandler dbHandler;
Button saveButton;
MyCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
inputOne = (EditText) findViewById(R.id.inputOne);
inputTwo = (EditText) findViewById(R.id.inputTwo);
dbHandler = new MyDBHandler(this, null, null, 1);
saveButton = (Button) findViewById(R.id.saveButton);
MyDBHandler myDBHandler = new MyDBHandler(this);
Cursor c = myDBHandler.getCursor();
cursorAdapter = new MyCursorAdapter(this,c,1);
ListView notes = (ListView) findViewById(R.id.notes);
notes.setAdapter(cursorAdapter);
public void saveClicked(View view) {
Test test = new Test( inputOne.getText().toString(), inputTwo.getText().toString() );
dbHandler.addTest(test);
inputOne.setText("");
inputTwo.setText("");
cursorAdapter.notifyDataSetChanged();
}
MyDBHandler.java
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Database.db";
public static final String TABLE_TEST = "test";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_ONE = "one";
public static final String COLUMN_TWO = "two";
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TEST + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_ONE + " TEXT," +
COLUMN_TWO + " TEXT" + ");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}
public void addTest(Test test){
ContentValues values = new ContentValues();
values.put(COLUMN_ONE, test.get_one());
values.put(COLUMN_TWO, test.get_two());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_TEST, null, values);
db.close();
}
public Cursor getCursor(){
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_ACTIVITIES + " WHERE 1";
Cursor c = db.rawQuery(query, null);
return c;
}
}
MyCursorAdapter.java
public class MyCursorAdapter extends CursorAdapter {
public MyCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, 1);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.custom_row, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView one = (TextView) view.findViewById(R.id.one);
TextView two = (TextView) view.findViewById(R.id.two);
String one_string = cursor.getString(cursor.getColumnIndexOrThrow(MyDBHandler.COLUMN_ONE));
one.setText(one_string);
String two_string = cursor.getString(cursor.getColumnIndexOrThrow(MyDBHandler.COLUMN_TWO));
two.setText(two_string);
}
}
Test.java
public class Test {
private int _id;
private String _one;
private String _two;
public Test(){
}
public Test(int id){
this._id = id;
}
public Test(String one, String two){
this._one = one;
this._two = two;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_one() {
return _one;
}
public void set_one(String _one) {
this._one = _one;
}
public String get_two() {
return _two;
}
public void set_two(String _two) {
this._two = _two;
}
The correct way to refresh a ListView backed by a Cursor is to call cursorAdapter.notifyDatasetChanged(), without needing to recreate and reset the adapter.
So in your saveClicked method you just update the db and let the Adapter know there has been a change.
To do this, you'll need to keep a reference to the adapter as an instance field instead of declaring it as a local variable.
Turns out my ListView was populating, but I made the mistake of putting a ListView inside of a ScrollView - so I wasn't able to see the addition of entries. It worked once I used the solution from this: Android - ListView's height just fits 1 ListView item

Unable to bind data by query from DB to spinner

Hey guys I already have a data in my database but I want to show it into spinner I'm really new to this problem, so would you guys help me to solve this problem,or I would prefer if you write the correct code for me :) Thanks in advance.
First this is my DB class
public class DBAdapter
{
public static final String UPDATEDATE = "UpdateDate";
//Declare fields in PersonInfo
public static final String ROWID = "_id";
public static final String PT_FNAME = "Username";
public static final String PT_COLORDEF = "ColorDeficiency";
private static final String DATABASE_CREATE =
"create table PersonInfo (_id integer primary key autoincrement, "
+ "Username text not null, ColorDeficiency text);";
private static final String DATABASE_NAME = "CAS_DB";
private static final String tbPerson = "PersonInfo";
private static final int DATABASE_VERSION = 1;
private final Context databaseContext;
private final Context context;
private DatabaseHelper DBHelper;
public SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
databaseContext = ctx;
}
//start database helper
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);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public Cursor all(Activity activity){
String[] from ={ROWID,PT_FNAME,PT_COLORDEF};
String order = PT_FNAME;
Cursor cursor =db.query(tbPerson, from, null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
In another class
private DBAdapter db;
private Spinner spinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.greeting);
initComponent();
db = new DBAdapter(this);
Cursor c = db.all(this);
SimpleCursorAdapter CursorAdapter = new SimpleCursorAdapter(
this,android.R.layout.simple_spinner_item,c,
new String[]{DBAdapter.PT_FNAME},new int[]{android.R.id.list});
CursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(CursorAdapter);
try changing
new int[]{android.R.id.list}
to
new int[]{android.R.layout.simple_spinner_item}

Categories

Resources