Android SQLite database doesnot Update and Delete - android

This is mainactivity which provides the user Input
public class Welcome extends AppCompatActivity{
private DBMANAGER_person dbmanager_person;
private ListView listView;
private SimpleCursorAdapter adapter;
final String [] from = new String[]{MyDB.COLUMN_ID, MyDB.COLUMN_NAME, MyDB.COLUMN_AGE, MyDB.COLUMN_HEIGHT , MyDB.COLUMN_WEIGHT};
final int [] to = new int[]{R.id.nameTV,R.id.ageTV,R.id.heightTV,R.id.weightTV};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
dbmanager_person = new DBMANAGER_person(this);
dbmanager_person.open();
Cursor cursor = dbmanager_person.fetch();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.emptyTV));
adapter = new SimpleCursorAdapter(this, R.layout.person, cursor, from, to,0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView idTextView = (TextView)view.findViewById(R.id.idTV);
TextView nameTextView = (TextView) view.findViewById(R.id.nameTV);
TextView ageTextView = (TextView) view.findViewById(R.id.ageTV);
TextView heightTextView = (TextView) view.findViewById(R.id.heightTV);
TextView weightTextView = (TextView) view.findViewById(R.id.weightTV);
String iD = idTextView.getText().toString();
String name = nameTextView.getText().toString();
String age = ageTextView.getText().toString();
String height = heightTextView.getText().toString();
String weight = weightTextView.getText().toString();
Intent intent = new Intent(getApplicationContext(), Modiffy_person_Details.class);
intent.putExtra("_id",iD);
intent.putExtra("name", name);
intent.putExtra("age", age);
intent.putExtra("height", height);
intent.putExtra("weight", weight);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.add_person,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.add){
Intent intent = new Intent(this,Add_people.class);
startActivity(intent);
}else if (id == R.id.logout){
Intent backToHome = new Intent(this,MainActivity.class);
startActivity(backToHome);
}
return super.onOptionsItemSelected(item);
}
}
This is Add_prople class
public class Add_people extends AppCompatActivity implements View.OnClickListener {
private EditText nameEditText;
private EditText ageEditText;
private EditText heightEditText;
private EditText weightEditText;
private Button save;
private DBMANAGER_person dbmanager_person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Add People");
setContentView(R.layout.activity_add_people);
nameEditText = (EditText)findViewById(R.id.nameET);
ageEditText = (EditText)findViewById(R.id.ageET);
heightEditText = (EditText)findViewById(R.id.heightET);
weightEditText = (EditText)findViewById(R.id.weightET);
save = (Button)findViewById(R.id.saveBtn);
dbmanager_person = new DBMANAGER_person(this);
dbmanager_person.open();
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.saveBtn:
final String name = nameEditText.getText().toString();
final String age = ageEditText.getText().toString();
final String height = heightEditText.getText().toString();
final String weight = weightEditText.getText().toString();
dbmanager_person.insert(name,age,height,weight);
Intent main = new Intent(this,Welcome.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
break;
}
}
}
This is DBMANAGER_person class where the CRUD operation works
This is the Modiffy_person_Details class where user can Update and Delete their information
public class DBMANAGER_person {
private SQLiteDatabase database;
private MyDB myDB;
private Context context;
public DBMANAGER_person(Context context) {
this.context = context;
}
public DBMANAGER_person open() throws SQLiteException{
myDB = new MyDB(context);
database = myDB.getWritableDatabase();
return this;
}
public void close(){
myDB.close();
}
public void insert(String name,String age,String height,String weight){
ContentValues contentValues = new ContentValues();
contentValues.put(MyDB.COLUMN_NAME,name);
contentValues.put(MyDB.COLUMN_AGE,age);
contentValues.put(MyDB.COLUMN_HEIGHT,height);
contentValues.put(MyDB.COLUMN_WEIGHT,weight);
database.insert(MyDB.TABLE_NAME,null,contentValues);
}
public Cursor fetch(){
String[] columns = new String[]{MyDB.COLUMN_ID, MyDB.COLUMN_NAME, MyDB.COLUMN_AGE , MyDB.COLUMN_HEIGHT, MyDB.COLUMN_WEIGHT};
Cursor cursor = database.rawQuery( "select rowid _id,* from "+MyDB.TABLE_NAME, null);
cursor.moveToFirst();
return cursor;
}
public int update(long id, String name, String age, String height, String weight){
ContentValues contentValues = new ContentValues();
contentValues.put(MyDB.COLUMN_NAME,name);
contentValues.put(MyDB.COLUMN_AGE,age);
contentValues.put(MyDB.COLUMN_HEIGHT,height);
contentValues.put(MyDB.COLUMN_WEIGHT,weight);
int i = database.update(MyDB.TABLE_NAME,contentValues,MyDB.COLUMN_ID + " = "+id,null);
return i;
}
public void delete(long id){
database.delete(MyDB.TABLE_NAME, MyDB.COLUMN_ID + "="+ id,null);
}
}
public class Modiffy_person_Details extends AppCompatActivity implements View.OnClickListener{
private EditText nameField;
private EditText ageField;
private EditText heightField;
private EditText weightField;
private Button update;
private Button delete;
private long _id;
private DBMANAGER_person dbmanager_person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Modify Record");
setContentView(R.layout.activity_modiffy_person__details);
dbmanager_person = new DBMANAGER_person(this);
dbmanager_person.open();
nameField = (EditText)findViewById(R.id.nameEditText);
ageField = (EditText)findViewById(R.id.ageEditText);
heightField = (EditText)findViewById(R.id.heightEditText);
weightField = (EditText)findViewById(R.id.weightEditText);
update = (Button)findViewById(R.id.update_btn);
delete = (Button)findViewById(R.id.delete_btn);
Intent intent = getIntent();
String ID = intent.getStringExtra("_id");
String name = intent.getStringExtra("name");
String age = intent.getStringExtra("age");
String height = intent.getStringExtra("height");
String weight = intent.getStringExtra("weight");
String check_ID = ID;
if(!check_ID.equals("")) {
_id = Long.parseLong(ID);
}/*else{
Toast.makeText(getApplicationContext(),"There is no id",Toast.LENGTH_LONG).show();
}*/
nameField.setText(name);
ageField.setText(age);
heightField.setText(height);
weightField.setText(weight);
update.setOnClickListener(this);
delete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.update_btn:
String na = nameField.getText().toString();
String ag = ageField.getText().toString();
String hei = heightField.getText().toString();
String wei = weightField.getText().toString();
dbmanager_person.update( _id , na , ag,hei,wei);
this.returnHome();
break;
case R.id.delete_btn:
dbmanager_person.delete(_id);
this.returnHome();
break;
}
}
public void returnHome(){
Intent home_intent = new Intent(getApplicationContext(),Welcome.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
My problem is whenever i want to update or delete my information it does not work.

Check the returned values for both delete and update. For both functions, it returns 0 for no rows affected, or it returns 1 if there are rows are affected. If it's 0, then your issue is dealing with the SQL query itself, in which case the first thing to check would be the validity of the IDs.
update
delete

Related

Get all the data from one row in sqlitedatabase with the name_column and store it in listview

I have coded a RecyclerView where I search for data from my SQLiteDatabase with the SearchAdapter. The MaterialSearchBar (PlaceHolder) only shows the names of the data from the Database. Now I want to select one item, which i choose in the searchbar and get all the other columns of that one row and store the data in a listview in another activity.
So my first question is, how can i get all data from one row, if i only have the name? Should I do it with a cursor?
And my second question is, how should i store all the data from that one row in a listview in another activity?
Thank you for your help!
enter cclass SearchViewHolder extends RecyclerView.ViewHolder{
public TextView medid,name,menge,art,nummer;
public SearchViewHolder(View itemView) {
super(itemView);
medid = (TextView) itemView.findViewById(R.id.medid);
name = (TextView) itemView.findViewById(R.id.name);
menge = (TextView) itemView.findViewById(R.id.menge);
art = (TextView) itemView.findViewById(R.id.art);
nummer = (TextView) itemView.findViewById(R.id.nummer);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Drugs> drugs;
public SearchAdapter(Context context, List<Drugs> drugs) {
this.context = context;
this.drugs = drugs;
}
public SearchAdapter() {
}
#Override
public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater =LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.medikamentensuche,parent,false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(SearchViewHolder holder, int position) {
//String pharmaId,name,menge,art,preis,code,bezeichnung;
holder.medid.setText(toString().valueOf(drugs.get(position).getMedID()));
holder.name.setText(drugs.get(position).getName());
holder.menge.setText(drugs.get(position).getMenge());
holder.art.setText(drugs.get(position).getArt());
holder.nummer.setText(drugs.get(position).getNummer());
}
#Override
public int getItemCount() {
return drugs.size();
}
}
DataBaseOpenhelper class
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DB_NAME = "medikamente.db";
private static final String TABLE = "Medikamente";
private static final int DB_VER = 1;
public static final String ID = "MedID";
public static final String NAME = "Handelsname";
public static final String MENGE = "Mengenangabe";
public static final String ART = "Mengenart";
public static final String NUMMER = "Pharmanummer";
public DatabaseOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);
}
//neues Medikament hinzufügen
public boolean insertNewEntry (String name, String mengenangabe, String mengenart, String pharmanummer) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME,name);
values.put(MENGE,mengenangabe);
values.put(ART,mengenart);
values.put(NUMMER,pharmanummer);
long result = db.insert("Medikamente",null,values);
if (result == -1)
return false;
else
return true;
}
public List<Drugs> getDrug() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
Log.d("in der DrugDatabases", "SQLiteQueryBuilder successful");
//Kathi habe hier: "ATCCode", "BezeichnungATCCode" gelöscht
String [] sqlSelect = {"MedID", "Handelsname", "Mengenangabe", "Mengenart", "Pharmanummer"};
String tableName = "Medikamente";
Log.d("in der DrugDatabases", " successful" + sqlSelect);
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, null, null, null, null, null);
List<Drugs> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
Drugs drug = new Drugs();
drug.setMedID(cursor.getInt(cursor.getColumnIndex("MedID")));
drug.setName(cursor.getString(cursor.getColumnIndex("Handelsname")));
drug.setMenge(cursor.getString(cursor.getColumnIndex("Mengenangabe")));
drug.setArt(cursor.getString(cursor.getColumnIndex("Mengenart")));
drug.setNummer(cursor.getString(cursor.getColumnIndex("Pharmanummer")));
result.add(drug);
}while (cursor.moveToNext());
}return result;
}
public List<String> getNames() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"Handelsname" };
String tableName = "Medikamente";
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, null, null, null, null, null);
List<String> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
result.add(cursor.getString(cursor.getColumnIndex("Handelsname" )));
}while (cursor.moveToNext());
}return result;
}
public List<Drugs> getDrugsByName(String name) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"MedID" ,"Handelsname" ,"Mengenangabe" ,"Mengenart" ,"Pharmanummer"};
String tableName = "Medikamente";
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, "Handelsname LIKE ?",new String[]{"%"+name+"%"}, null, null, null);
List<Drugs> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
Drugs drug = new Drugs();
drug.setMedID(cursor.getInt(cursor.getColumnIndex("MedID")));
drug.setName(cursor.getString(cursor.getColumnIndex("Handelsname")));
drug.setMenge(cursor.getString(cursor.getColumnIndex("Mengenangabe")));
drug.setArt(cursor.getString(cursor.getColumnIndex("Mengenart")));
drug.setNummer(cursor.getString(cursor.getColumnIndex("Pharmanummer")));
result.add(drug);
}while (cursor.moveToNext());
}return result;
}
}
MedSucheActivity
public class MedSucheActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
TextView textView;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
DatabaseOpenHelper database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medsuchen);
Button button = (Button) findViewById(R.id.hinzufügen);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MedTableActivity.class);
TextView suche = (TextView) findViewById(R.id.SuchMedikament);
intent.putExtra("weitergabe",suche.getText().toString());
startActivityForResult(intent,1);
//wichtig wenn man Daten zurück geben will von der 2.Activity
}
});
textView = (TextView) findViewById(R.id.SuchMedikament);
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar) findViewById(R.id.search_bar);
//textView = (TextView) findViewById(R.id.versuch);
//Datenbank
database = new DatabaseOpenHelper(this);
//Searchbar
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for(String search:suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled)
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//init Adapter default set all result
adapter = new SearchAdapter(this,database.getDrug());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getDrugsByName(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getNames();
materialSearchBar.setLastSuggestions(suggestList);
}
public void onHinzuClick(View v) {
Log.d("msg","Auf Hinzufügen Button geklickt");
Intent intent = new Intent (getBaseContext(),MedikamentHinzufugenActivity.class);
startActivity(intent);
}
}
So my first question is, how can i get all data from one row, if i
only have the name?
And my second question is, how should i store all the data from that
one row in a listview in another activity?
If name is definitely going to be unique, which it appears that it may not be, then you can use that in conjunction with the getDrugsByName method to obtain a list of Drug objects (1 if the name is unique). So name is all that would be required and this can be passed to another activity via an Intent Extra and thus retrieved from that Intent Extra, you can then use the getDrugsbyName method in that activity to then get all the data for the row (for 2.). Of course you could also pass all values via Intent Extras.
If name isn't necessarily unique then you could use MedId (column ID) (assuming that it's the PRIMARY KEY of the table and thus unique) instead of the name. You would probably have a method getDrugById in the DatabaseHelper class along the lines of (for 2.) :-
public Drugs getDrugById(long id) {
SQLiteDatabase db = getReadableDatabase();
Drugs rv = new Drugs();
rv.setMedID(-1); // set so that drug not found can be determined
String whereclause = ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setMedID(id);
rv.setName(csr.getString(csr.getColumnIndex(NAME)));
rv.setMenge(csr.getString(csr.getColumnIndex(MENGE)));
rv.setArt(csr.getString(csr.getColumnIndex(ART)));
rv.setNummer(csr.getString(csr.getColumnIndex(NUMMER)));
}
csr.close();
return rv;
}
Notes
The returned value should be checked for the MedID being -1, this indicating that there is no such row that matches the passed id.
Rather than risking mistyping names the CONSTANTS defined in the class have been used (you may wish to adopt this throughout).
Cursors should ALWAYS be closed when done with, otherwise an exception can occur.
The above assumes that the ID column is the PRIMARY KEY and that it is an alias of the rowid column. That is you have ID INTEGER PRIMARY KEY or ID INTEGER,..other columns.., PRIMARY KEY (ID)
The above assumes the correct usage of the ID column i.e. that it is treated as a long not an int (int is ok as long as the rows are limited, however SQLite allows rowid's as high as 9223372036854775807, which cannot be handled by an int).
This is the usual method, as using an alias of rowid will likely be the most efficient.

connecting sqli database to recyclerView

I made a material book which included a Recycler view that loaded from my sqli database
I did everything which it needed but when i start the app it gave me some differents error :
first it gaves me this no such table: tbl_heros (code 1): , while compiling: SELECT * FROM tbl_heros WHERE fav==1
and then when i change the type from data base it said that
it cant initialize my code (This 4 which i used for connecting my database and i call theme here but it dont work .. ) :
selectHeros();
selectItem();
selectFav();
selectAll();
and here is the main activity codes
public class ActivityMain extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
DrawerLayout drawer;
NavigationView navigationView;
ImageView imgToolbar;
public static ArrayList<Heros> herosArrayList=new ArrayList<>();
public static ArrayList<Heros> itemArrayList =new ArrayList<>();
public static ArrayList<Heros> favArrayList=new ArrayList<>();
public static ArrayList<Heros> heroItemArrayList=new ArrayList<>();
public static SQLiteDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_menu);
drawer=(DrawerLayout)findViewById(R.id.drawer);
navigationView=(NavigationView)findViewById(R.id.navigation) ;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.serch){
Intent intent=new Intent(G.context,ActivitySearch.class);
startActivity(intent);
}
if(id==R.id.setting){
Intent intent=new Intent(G.context,ActivitySetting.class);
startActivity(intent);
}if(id==R.id.hero){
// Intent intent=new Intent(G.context,Test.class);
// startActivity(intent);
}
return true;
}
});
tabLayout=(TabLayout)findViewById(R.id.tabLayout);
viewPager=(ViewPager)findViewById(R.id.viewPager);
imgToolbar=(ImageView)findViewById(R.id.imgToolbar);
imgToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(Gravity.RIGHT);
}
});
selectHeros();
selectItem();
selectFav();
selectAll();
for(int i=0;i<herosArrayList.size();i++) {
Log.i("LOG","id:"+herosArrayList.get(i).getInt()+"name:"+herosArrayList.get(i).getName() );
}
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public void selectHeros(){
database=SQLiteDatabase.openOrCreateDatabase(G.direction +"/material_book.sqlite",null);
Cursor cursor=database.rawQuery("SELECT * FROM tbl_heros WHERE fav==1",null);
while(cursor.moveToNext()){
int id=cursor.getInt(cursor.getColumnIndex("id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String desc=cursor.getString(cursor.getColumnIndex("desc"));
String pic=cursor.getString(cursor.getColumnIndex("pic"));
String type=cursor.getString(cursor.getColumnIndex("type"));
int fav=cursor.getInt(cursor.getColumnIndex("fav"));
Heros heros=new Heros(id,name,desc,pic,fav,type);
herosArrayList.add(heros);
Log.i("LOG","heros check----id:"+name);
}
}
public static void selectItem(){
database=SQLiteDatabase.openOrCreateDatabase(G.direction +"/material_book.sqlite",null);
Cursor cursor=database.rawQuery("SELECT * FROM tbl_heros WHERE type='item'",null);
while(cursor.moveToNext()){
int id=cursor.getInt(cursor.getColumnIndex("id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String desc=cursor.getString(cursor.getColumnIndex("desc"));
String pic=cursor.getString(cursor.getColumnIndex("pic"));
String type=cursor.getString(cursor.getColumnIndex("type"));
int fav=cursor.getInt(cursor.getColumnIndex("fav"));
Heros heros=new Heros(id,name,desc,pic,fav,type);
itemArrayList.add(heros);
}
}
public static void selectFav(){
database=SQLiteDatabase.openOrCreateDatabase(G.direction +"/material_book.sqlite",null);
Cursor cursor=database.rawQuery("SELECT * FROM tbl_heros WHERE fav=1",null);
while(cursor.moveToNext()){
int id=cursor.getInt(cursor.getColumnIndex("id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String desc=cursor.getString(cursor.getColumnIndex("desc"));
String pic=cursor.getString(cursor.getColumnIndex("pic"));
String type=cursor.getString(cursor.getColumnIndex("type"));
int fav=cursor.getInt(cursor.getColumnIndex("fav"));
Heros heros=new Heros(id,name,desc,pic,fav,type);
favArrayList.add(heros);
}
}
public static void selectAll() {
database = SQLiteDatabase.openOrCreateDatabase(G.direction + "/material_book.sqlite", null);
Cursor cursor = database.rawQuery("SELECT * FROM tbl_heros", null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String desc = cursor.getString(cursor.getColumnIndex("desc"));
String pic = cursor.getString(cursor.getColumnIndex("pic"));
String type = cursor.getString(cursor.getColumnIndex("type"));
int fav = cursor.getInt(cursor.getColumnIndex("fav"));
Heros heros = new Heros(id, name, desc, pic, fav, type);
heroItemArrayList.add(heros);
}
}
#Override
protected void onResume() {
super.onResume();
if(!herosArrayList.isEmpty()){
herosArrayList.clear();
selectHeros();
} if(!itemArrayList.isEmpty()){
itemArrayList.clear();
selectItem();
}if(!favArrayList.isEmpty()){
favArrayList.clear();
selectFav();
}if(!heroItemArrayList.isEmpty()){
heroItemArrayList.clear();
selectAll();
}
}
}
`

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.

How to get selected index or position of a listview and pass into a new actvity?

I would like to get the clicked index/position of a listview and then pass it over to a new activity. Bellow is my code of what i have done but I keep getting errors when i ran my code. Thank you in advance for the help.
MainAcitivity.Java
public static int hymnIndex;
private void setUpList() {
setListAdapter(new ArrayAdapter<HymnClass>(this, android.R.layout.simple_list_item_1, HymnArrayTitle));
listView = getListView();
//Let’s set a message shown upon tapping an item
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
hymnIndex = position;
Toast.makeText(getApplicationContext(),
((TextView) view).getText().toString(),
Toast.LENGTH_SHORT).show();
Intent selectedItem = new Intent(MainActivity.this, Content.class);
startActivity(selectedItem);
}
});
}
**Content.Java********************************
public class Content extends Activity{
private SQLiteDatabase database;
private static final String DB_NAME = "Akan_DB.db";
private static final String TABLE_NAME = "Hymn";
private static final String HYMN_ID = "_id";
private static final String HYMN_NUMBER = "Hymn_number";
private static final String TITLE = "Title";
private static final String Content = "Content";
private static final String Author = "Author";
private ArrayList<HymnClass> HymnArray;
TextView title_textview;
TextView Content_texview;
TextView author_textview;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hymn_content);
setHymnTitle();
public class HymnClass {
int hymnId;
String hymnNumber;
String title;
String content;
String Author;
#Override
public String toString(){
return this.hymnNumber + " " + this.title;
}
}
private void setHymnTitle() {
String[] whereClause = {String.valueOf(MainActivity.hymnIndex)}; ///converted the int into a string because the where clause only accepts strings
HymnArray = new ArrayList<HymnClass>();
Cursor ListCursor = database.query(TABLE_NAME,
new String[]{HYMN_ID,HYMN_NUMBER,TITLE,Content,Author},
"HYMN_ID = ?",
whereClause,
null,
null,
TITLE);
ListCursor.moveToFirst();
if(!ListCursor.isAfterLast()) {
do {
HymnClass HymnData = new HymnClass();
HymnData.hymnNumber = ListCursor.getString(1);
HymnData.title = ListCursor.getString(2);
HymnData.content = ListCursor.getString(3);
HymnData.Author = ListCursor.getString(4);
HymnArray.add(HymnData);
// title_textview.setText(TITLE);
} while (ListCursor.moveToNext());
}
ListCursor.close();
}
}
//Let’s set a message shown upon tapping an item
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Intent selectedItem = new Intent(MainActivity.this, Content.class);
selectedItem.putExtart("MySelectedPOS",position);
startActivity(selectedItem);
}
});
in your second Activity , in the create method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hymn_content);
Bundel lBundel=getIntent().getExtrat();
if(lBundel!=null){
// get your passed value
int lSelectedPosition=lBundel.getInt("MySelectedPOS");
}
.
.
.
}

Categories

Resources