connecting sqli database to recyclerView - android

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();
}
}
}
`

Related

I have one issue on ListView

I want to implement refine on my app where the item will come from server but in the below Custom_List class code only one item is coming and another item is shown as null.This is screenshot of items.
On this item I am retrieving id,age,height,communities,caste,occupation,education,income,location,pics.
public class RefineCustomList extends ArrayAdapter<String> {
private NetworkImageView imageView;
private ImageLoader imageLoader;
private final String[] ids;
private String[] ages;
private String[] heights;
public String[] communities;
public String[] castes;
public String[] educations;
public String[] occupations;
public String[] incomes;
public String[] pics;
public String[] locations;
public String[] shortlist;
public String[] expressinterest;
private Activity context;
public RefineCustomList(Activity context, String[] ids, String[] ages, String[] heights, String[] communities, String[] castes,
String[] educations, String[] occupations, String[]incomes, String[]pics, String[] locations,
String[] shortlist, String[] expressinterest) {
super(context, R.layout.list_view_layout,ids);
this.ids = ids;
this.ages = ages;
this.heights = heights;
this.communities = communities;
this.castes = castes;
this.educations = educations;
this.occupations = occupations;
this.incomes = incomes;
this.pics = pics;
this.locations = locations;
this.context = context;
this.shortlist = shortlist;
this.expressinterest = expressinterest;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.refine_custom_list, null, true);
String url1 = "https://www.maangal.com/thumb/thumb_";
String url =url1+pics[position];
imageView = (NetworkImageView) listViewItem.findViewById(R.id.offer_image);
imageLoader = CustomVolleyRequest.getInstance(this.getContext()).getImageLoader();
imageLoader.get(url, ImageLoader.getImageListener(imageView,R.drawable.image,android.R.drawable.ic_dialog_alert));
imageView.setImageUrl(url,imageLoader);
TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
textViewId.setText(ids[position]);
textViewName.setText( ages[position]+" years"+" , "+heights[position]+" cm"+", "+communities[position]+" : "+castes[position]+" , "+educations[position]+" , "+occupations[position]+" , "+incomes[position]+", "+locations[position]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), BlankActivity.class);
Toast.makeText(getContext(), ids[position], Toast.LENGTH_LONG).show();
i.putExtra("id", ids[position]);
v.getContext().startActivity(i);
}
});
Button btnSort =(Button) listViewItem.findViewById(R.id.btnshort);
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Shortlisted",Toast.LENGTH_LONG).show();
}
});
Button btnChat =(Button) listViewItem.findViewById(R.id.btnchat);
btnChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Chatting",Toast.LENGTH_LONG).show();
}
});
Button declineButton = (Button)listViewItem.findViewById(R.id.declineButton);
declineButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Decline",Toast.LENGTH_LONG).show();
}
});
return listViewItem;
}
}
This is the parsing code
public class RefineActivity extends FragmentActivity {
SessionManager session;
String email;
public String JSON_URL;
private ListView listView;
Button rfb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.refine_activity);
// Session class instance
session = new SessionManager(this);
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
Log.e("email==========>", email);
//JSON_URL = "http://10.0.2.2/xp/ei_sent_pending.php?matri_id="+email;
listView = (ListView) findViewById(R.id.listView);
rfb = (Button) findViewById(R.id.refineBtn);
rfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
RefineFragment ls_fragment = new RefineFragment();
ls_fragment.show(fragmentManager, "simple fragment");
}
});
Intent intent = getIntent();
final String response = getIntent().getExtras().getString("res");
Log.e("responde rfi", response);
showJSON(response);
}
protected void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
RefineCustomList cl = new RefineCustomList(this, ParseJSON.ids, ParseJSON.ages, ParseJSON.heights, ParseJSON.communities, ParseJSON.castes, ParseJSON.educations, ParseJSON.occupations, ParseJSON.incomes, ParseJSON.pics, ParseJSON.locations, ParseJSON.shortlist, ParseJSON.expressinterest);
listView.setAdapter(cl);
}
}
This is the Log where the item data is showing
responde rfi: {"result":[{"id":"Mgl11638","age":"21","height":"160","caste":"Brahmin","community":"Kumaoni","education":"MA","occupation":"Not Working","income":"Will tell later","pic":"Mgl11638.jpg","location":"Almora"},{"id":"Mgl16111","age":"22","height":"160","caste":"Brahmin","community":"Kumaoni","education":"B.Sc","occupation":"Student","income":"Will tell later","pic":"","location":"Almora"},{"id":"Mgl11658","age":"22","height":"154","caste":"Brahmin","community":"Kumaoni","education":"Undergraduate","occupation":"Student","income":"Will tell later","pic":"","location":"Lucknow"},{"id":"Mgl11621","age":"21","height":"134","caste":"Brahmin","community":"Kumaoni","education":"MA","occupation":"Not Working","income":"No income","pic":"","location":"Bareilly"}]}
Why do you use too much of Arrays inside an adapter? Just follow these steps.
Put all your strings inside an Object as single fields.
Pass that object as a parameter into your adapter from your Activity.
Fetch the details from that object in your adapter.
Then the adapter will automatically fetch you multiple data and populate into the list view. And my kind advice is to extend the class as BaseAdapter instead of ArrayAdapter
This is your object. I created it exclusively for you. Create a new java class(not an activity, just a .java file) and put this code inside.
public class DetailsObject implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String age;
private String height;
public String community;
public String caste;
public String education;
public String occupation;
public String income;
public byte[] pic;
public String location;
public String shortlist;
public String expressinterest;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getCommunity() {
return community;
}
public void setCommunity(String community) {
this.community = community;
}
public String getCaste() {
return caste;
}
public void setCaste(String caste) {
this.caste = caste;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getIncome() {
return income;
}
public void setIncome(String income) {
this.income = income;
}
public byte[] getPic() {
return pic;
}
public void setPic(byte[] pic) {
this.pic = pic;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getShortlist() {
return shortlist;
}
public void setShortlist(String shortlist) {
this.shortlist = shortlist;
}
public String getExpressinterest() {
return expressinterest;
}
public void setExpressinterest(String expressinterest) {
this.expressinterest = expressinterest;
}
}
In your adapter class change extends ArrayAdapter<String> to extends BaseAdapter, change all the String[] to String and in the constructor, juzt pass (Context context, DetailsObject detailObject) as parameter. And in your activity call the adapter like below:
RefineCustomList refineCustomList;
refineCustomList = new RefineCustomList(MainActivity.this,detailObject);
yourListView.setAdapter(refineCustomList);
Thats it..

Android SQLite database doesnot Update and Delete

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

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.

Hi i tried to add some details to android database. I created the table but i cant retrive the details in to list view

My Mainactivity is
public class MainActivity extends Activity {
private EditText title_name,head_name,content;
private Button saveButton;
private DatabaseHandler dba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dba=new DatabaseHandler(MainActivity.this);
title_name=(EditText)findViewById(R.id.editText_Title);
head_name=(EditText)findViewById(R.id.ediText_Name);
content=(EditText)findViewById(R.id.editText_Content);
saveButton=(Button)findViewById(R.id.button_Save);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTodb();
}
});
}
private void saveTodb() {
Mywish wish=new Mywish();
wish.setTitle(title_name.getText().toString().trim());
wish.setHeadingName(head_name.getText().toString().trim());
wish.setContent(content.getText().toString().trim());
dba.addWishes(wish);
dba.close();
title_name.setText("");
head_name.setText("");
content.setText("");
Intent i =new Intent(MainActivity.this,DisplayItem.class);
startActivity(i);
}
}
and my Consatnts.java ,here i declared my Database variables and details`
public class Constants {
public static final String DATABASE_NAME="diary";
public static final int DATABASE_VERSION=1;
public static final String TABLE_NAME="details";
public static final String TITLE_NAME="title";
public static final String HEAD_NAME="headingname";
public static final String CONTENT_NAME ="content";
public static final String DATE_NAME="date";
public static final String KEY_ID="_id";
}
My DatabaseHandler class is
public class DatabaseHandler extends SQLiteOpenHelper{
private final ArrayList wishList=new ArrayList<>();
public DatabaseHandler(Context context ) {
super(context,Constants.DATABASE_NAME,null,Constants.DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DIARY_TABLE="CREATE TABLE "+Constants.TABLE_NAME + "("+Constants.KEY_ID +" INTEGER PRIMARY KEY,"+
Constants.TITLE_NAME + " TEXT,"+Constants.HEAD_NAME +" TEXT,"+ Constants.CONTENT_NAME+" TEXT,"+Constants.DATE_NAME +" INTEGER)";
db.execSQL(CREATE_DIARY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+Constants.TABLE_NAME);
onCreate(db);
}
public void addWishes(Mywish wish)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(Constants.TITLE_NAME,wish.getTitle());
values.put(Constants.HEAD_NAME,wish.getHeadingName());
values.put(Constants.CONTENT_NAME,wish.getContent());
values.put(Constants.DATE_NAME,java.lang.System.currentTimeMillis());
db.insert(Constants.TABLE_NAME, null, values);
Log.v("WISH SUCCESfuHOOO"," Hoo");
db.close();
}
public ArrayList<Mywish> getWishes()
{
String selectQuery="SELECT * FROM"+Constants.TABLE_NAME;
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query(Constants.TABLE_NAME,new String[]{Constants.KEY_ID,Constants.TITLE_NAME,Constants.HEAD_NAME,Constants.CONTENT_NAME,
Constants.DATE_NAME },null,null,null,null,null,Constants.DATE_NAME+"DESC" );
if (cursor.moveToFirst())
{
do {
Mywish wish=new Mywish();
wish.setTitle(cursor.getString(cursor.getColumnIndex(Constants.TITLE_NAME)));
wish.setHeadingName(cursor.getString(cursor.getColumnIndex(Constants.HEAD_NAME)));
wish.setContent(cursor.getString(cursor.getColumnIndex(Constants.CONTENT_NAME)));
java.text.DateFormat dateFormat=java.text.DateFormat.getDateInstance();
String datedata=dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Constants.DATE_NAME))).getTime());
wish.setDateRecorded(datedata);
wishList.add(wish);
}while (cursor.moveToNext());
}
return wishList;
}
}
Mywish class is used to declare data variables used in my app
public class Mywish {
public String Title;
public String DateRecorded;
public String Content;
public String HeadingName;
public String getContent() {
return Content;
}
public void setContent(String content) {
this.Content = content;
}
public String getDateRecorded() {
return DateRecorded;
}
public void setDateRecorded(String dateRecorded) {
this.DateRecorded = dateRecorded;
}
public String getHeadingName() {
return HeadingName;
}
public void setHeadingName(String headingName) {
this.HeadingName = headingName;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
this.Title = title;
}
}
Displayitem Class is used to display the details in to List view.I setup the adapter and everything but the values didnt get in to the List view.
public class DisplayItem extends Activity {
private DatabaseHandler dba;
private ArrayList<Mywish> dbwishes=new ArrayList<>();
private WishAdapter wishAdapter;
private ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_item);
Log.v("Dispaly act","DiSPLAYAVTIVIT");
listview=(ListView)findViewById(R.id.List);
referesData();
}
private void referesData() {
dbwishes.clear();
dba=new DatabaseHandler(getApplicationContext());
ArrayList<Mywish> wishesfrmDb=dba.getWishes();
for (int i=0;i<wishesfrmDb.size();i++)
{
String title=wishesfrmDb.get(i).getTitle() ;
String headname=wishesfrmDb.get(i).getHeadingName();
String content=wishesfrmDb.get(i).getContent();
String date=wishesfrmDb.get(i).getDateRecorded();
Mywish myWish=new Mywish();
myWish.setTitle(title);
myWish.setContent(content);
myWish.setHeadingName(headname);
myWish.setDateRecorded(date);
dbwishes.add(myWish);
}
dba.close();
wishAdapter =new WishAdapter(DisplayItem.this,R.layout.wish_row,dbwishes);
listview.setAdapter(wishAdapter);
}
public class WishAdapter extends ArrayAdapter<Mywish>
{
Activity activity;
int layoutResource;
Mywish wish;
ArrayList<Mywish> mData=new ArrayList<>();
public WishAdapter(Activity act, int resource, ArrayList<Mywish> data) {
super(act, resource, data);
activity=act;
layoutResource=resource;
mData=data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Mywish getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getPosition(Mywish item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row= convertView;
ViewHolder holder=null;
if (row==null ||(row.getTag()==null))
{
LayoutInflater inflater=LayoutInflater.from(activity);
row=inflater.inflate(layoutResource,null);
holder=new ViewHolder();
holder.mTitle=(TextView)row.findViewById(R.id.textView_listTitle);
holder.mHead=(TextView)row.findViewById(R.id.textView_listName);
holder.mDate=(TextView)row.findViewById(R.id.textView_listDate);
row.setTag(holder);
} else {
holder=(ViewHolder) row.getTag();
}
holder.myWish=getItem(position);
holder.mTitle.setText(holder.myWish.getTitle());
holder.mHead.setText(holder.myWish.getHeadingName());
holder.mDate.setText(holder.myWish.getDateRecorded());
return row;
}
class ViewHolder{
TextView mTitle;
TextView mHead;
TextView mDate;
TextView mId;
TextView mContent;
Mywish myWish;
}
}
}
My log is
Process: harico.databaseex, PID: 6329
java.lang.RuntimeException: Unable to start activity ComponentInfo{harico.databaseex/harico.databaseex.DisplayItem}: java.lang.IllegalArgumentException: invalid LIMIT clauses:date DESC
The same as Waqar Ahmed:
"Constants.DATE_NAME+"DESC", you didnt put space before "DESC"
And the parameters of your cursor are not well ordered, should be something like:
Cursor cursor=db.query(Constants.TABLE_NAME,new String[]{Constants.KEY_ID,Constants.TITLE_NAME,Constants.HEAD_NAME,Constants.CONTENT_NAME,Constants.DATE_NAME },null,null,null,null,Constants.DATE_NAME+" DESC", null);

Categories

Resources