Radio Button is messed up when its scrolling - java

i have 57 radio button in list view, i want to divide those radio button into 19 groups, so each group has 3 radio button. but when i scrolled it the view is messed up and automatically adding radio button become double.
the data is gotten from sqlite database.
KlasifikasiActivity
public class KlasifikasiActivity extends AppCompatActivity {
private ListView lvKlasifikasi;
private ListKlasifikasiAdapter adapter;
private List<Klasifikasi> mKlasifikasiList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klasifikasi);
lvKlasifikasi = (ListView)findViewById(R.id.stepSwitcher);
mDBHelper = new DatabaseHelper(this);
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
if (false == database.exists()){
mDBHelper.getReadableDatabase();
if (copyDatabase(this)){
Toast.makeText(this,"COPY SUCCESS",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"COPY ERROR",Toast.LENGTH_SHORT).show();
return;
}
}
//get db metode
mKlasifikasiList = mDBHelper.getListKlasifikasiByGroup();
adapter = new ListKlasifikasiAdapter(this,mKlasifikasiList);
lvKlasifikasi.setAdapter(adapter);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream = context.getAssets().open(DatabaseHelper.DBNAME);
String outFileName = DatabaseHelper.DBLOCATION + DatabaseHelper.DBNAME;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while ((length = inputStream.read(buff)) > 0){
outputStream.write(buff,0,length);
}
outputStream.flush();
outputStream.close();
Log.w("MainActivity","DB copied");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
DatabaseHelper and function method
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "database.db";
public static final String DBLOCATION = "/data/data/com.example.damar.finalproject/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context,DBNAME,null,1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if (mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null,SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if (mDatabase!=null){
mDatabase.close();
}
}
public List<Klasifikasi> getListKlasifikasiByGroup(){
Klasifikasi klasifikasi = null;
List<Klasifikasi> klasifikasiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM klasifikasi group by group_index", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
klasifikasi = new Klasifikasi(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getInt(4));
klasifikasiList.add(klasifikasi);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return klasifikasiList;
}
}

have you checked list just after fetching from db and before set to adapter

Related

Delete data from ListView (Android Studio)

I have 3 java classes (MainActivity, DatabaseOpenHelper and DatabaseAccess)
My add and show buttons work perfectly, but not my delete button. Add adds name and nickname into the database, show shows the list of names in the same layout under the buttons.
Here is my code in MainActivity.class
public class MainActivity extends AppCompatActivity {
public EditText name123, dogName, dogNickname;
public Button query_button, add_button, show_button, delete_button;
public TextView result_address;
public ListView listView;
ArrayList<String> naziv = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name123 = findViewById(R.id.name);
query_button = findViewById(R.id.query_button);
result_address = findViewById(R.id.result);
dogName = findViewById(R.id.et_dogName);
dogNickname = findViewById(R.id.et_dogNickname);
add_button = findViewById(R.id.add_button);
show_button = findViewById(R.id.show_button);
delete_button = findViewById(R.id.delete_button);
listView = findViewById(R.id.doglistview);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, naziv);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
long result = databaseAccess.add(dogName.getText().toString(), dogNickname.getText().toString());
if(result > 0){
dogName.setText("");
dogNickname.setText("");
} else {
Toast.makeText(getApplicationContext(), "Dodaj ime i nadimak", Toast.LENGTH_SHORT).show();
}
databaseAccess.close();
}
});
show_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
naziv.clear();
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
Cursor cnn = databaseAccess.getAllNames();
while (cnn.moveToNext()){
String name = cnn.getString(0);
naziv.add(name);
}
listView.setAdapter(adapter);
databaseAccess.close();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), naziv.get(position), Toast.LENGTH_SHORT).show();
}
});
//setting onclicklistener to query button
query_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//create the instance of database access class and open database connection
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
//getting sting value of edittext
String n = name123.getText().toString();
String address = databaseAccess.getAddress(n);//getAddress method to get address
//setting text to result field
result_address.setText(address);
databaseAccess.close();
}
});
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getApplicationContext());
databaseAccess.open();
Integer deletedRows = databaseAccess.deleteData("id_dogName");
if (deletedRows > 0){
Toast.makeText(MainActivity.this, "Deleted data", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Data not deleted", Toast.LENGTH_SHORT).show();
}
databaseAccess.close();
}
});
}
}
And here is the code from DatabaseAccess.class:
public class DatabaseAccess {
static final String NAME = "name_dogName";
static final String NICKNAME = "nickname_dogName";
static final String TBNAME = "dogName";
static final String ROWID = "id_dogName";
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static DatabaseAccess instance;
Cursor c = null;
//private constructor so that object creation from outside the class is avoided
private DatabaseAccess(Context context)
{
openHelper = new DatabaseOpenHelper(context);
}
//to return the single instance of database
public static DatabaseAccess getInstance(Context context)
{
if(instance == null)
{
instance = new DatabaseAccess(context);
}
return instance;
}
//to open the database
public void open()
{
db = openHelper.getWritableDatabase();
}
//closing the database connection
public void close()
{
if(db!=null)
{
db.close();
}
}
//method to query and return the results from database
//query for address by passing name
public String getAddress(String name)
{
c = db.rawQuery("select nickname_dogName from dogName where name_dogName = ?", new String[]{name});
String nickname = "";
while (c.moveToNext())
{
String address = c.getString(0);
nickname += address;
}
return nickname;
}
//add
public long add(String name, String nickname){
try {
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
contentValues.put(NICKNAME, nickname);
return db.insert(TBNAME, ROWID, contentValues);
} catch (SQLException e){
e.printStackTrace();
}
return 0;
}
public Cursor getAllNames (){
String[] columns = {NAME, ROWID, NICKNAME};
return db.query(TBNAME, columns, null, null, null, null, null);
}
public Integer deleteData (String id){
return db.delete(TBNAME, "id_dogName", new String[]{id});
}
}
When I click on my phone on the delete button it throws me out of the app. How to correct my code and make the delete button delete a selected item from the list?
something wrong in the second argument, your where clause should include "=?"
public Integer deleteData (String id){
return db.delete(TBNAME, "id_dogName=?", new String[]{id});
}

Database not restored from Activity

I have a problem with database in android.
I'd like to collect data from an activity then transfer them to another activity that should show them into a ListView and save them into the DB.
The problem is that the app shows only the first item in the listview and I don't know if all data are saved into the DB. When I try to insert a new item, the app probably overrides the first item and shows the newest one.
Thanks a lot!
public class HomeActivity extends AppCompatActivity {
Button addPets;
private ListView mainListView;
private ArrayList<User> listUser;
private ArrayAdapter adapter;
private DBAdapter dbAdapter;
DBOpenHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
addPets = (Button)findViewById(R.id.add_friends);
addPets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent apriRegistraPet = new Intent(HomeActivity.this, RegisterActivity.class);
startActivity(apriRegistraPet);
}
});
dbAdapter = DBAdapter.getInstance(this);
mainListView = (ListView)findViewById(R.id.elenco_pets);
listUser = new ArrayList<User>();
adapter = new ArrayAdapter<User>(this, android.R.layout.simple_list_item_1, listUser);
mainListView.setAdapter(adapter);
mainListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
onLongClick(position, mainListView);
return true;
}
});
}
private void addNewItem(User user) {
long idx = dbAdapter.insertUser(user);
user.setId(idx);
listUser.add(0, user);
adapter.notifyDataSetChanged();
}
private void onLongClick(final int position, final ListView listView){
User user = (User)listView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "Deleted Item", Toast.LENGTH_LONG).show();
if(!dbAdapter.deleteUser(user)){
return;
}
listUser.remove(user);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
dbAdapter.open();
fillData();
Bundle extras = getIntent().getExtras();
if(extras != null){
String nome = extras.getString("Nome");
String razza = extras.getString("Razza");
String sesso = extras.getString("Sesso");
User user = new User(0, nome, razza, sesso, 10, 2000);
addNewItem(user);
}
}
public void fillData(){
Cursor cursor = dbAdapter.getAllEntries();
this.listUser.clear();
cursor.moveToFirst();
while(!cursor.isAfterLast()){
long idx = cursor.getLong(cursor.getColumnIndex(DBContract.AttributiRegistrazione._ID));
String nome = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.NOME));
String razza = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.RAZZA));
String sesso = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.SESSO));
this.listUser.add(0, new User(idx, nome, razza, sesso, 10, 2000));
cursor.moveToNext();
}
cursor.close();
adapter.notifyDataSetChanged();
}
And this is Register Activity
public class RegisterActivity extends AppCompatActivity {
ImageButton settaImmagine;
String imgDecodableString;
Spinner sprazza;
Spinner spsesso;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Clicco V e mette nella listview
ImageButton salva = (ImageButton)findViewById(R.id.button_salva);
salva.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText editText = (EditText)findViewById(R.id.name);
sprazza = (Spinner)findViewById(R.id.spinner_razza);
String razza = sprazza.getSelectedItem().toString();
spsesso = (Spinner)findViewById(R.id.spinner_sesso);
String sesso = spsesso.getSelectedItem().toString();
Intent resultIntent = new Intent(RegisterActivity.this, HomeActivity.class);
resultIntent.putExtra("Nome", editText.getText().toString());
resultIntent.putExtra("Razza", razza);
resultIntent.putExtra("Sesso", sesso);
startActivity(resultIntent);
}
});
DBAdapter class;
public class DBAdapter {
private static final String TAG = "DBAdapter";
private static DBAdapter dbAdapter;
private static DBOpenHelper dbOpenHelper;
private SQLiteDatabase db;
public synchronized static DBAdapter getInstance(Context context){
if(dbAdapter==null) {
dbAdapter = new DBAdapter(context.getApplicationContext());
}
return dbAdapter;
}
private DBAdapter(Context context) {dbOpenHelper = DBOpenHelper.getInstance(context);}
public DBAdapter open() throws SQLException{
try{
db = dbOpenHelper.getWritableDatabase();
}
catch (SQLException e){
Log.e(TAG, e.toString());
throw e;
}
return this;
}
public void close() {
db.close();
}
public long insertUser (User user){
Log.v(TAG, "Inserisci un User to DB: " +user.getNome());
long idx = db.insert(DBContract.AttributiRegistrazione.NOME_TABELLA, null, user.getAsContentValue());
user.setId(idx);
Log.v(TAG, "Added user with ID: "+idx);
return idx;
}
public boolean deleteUser (User user){
Log.v(TAG, "Removing User: " + user.getClass());
return db.delete(DBContract.AttributiRegistrazione.NOME_TABELLA,
DBContract.AttributiRegistrazione.NOME + "=" + user.getNome(), null) == 1;
}
public boolean deleteUser(String name){
Log.v(TAG, "Removing user: " + name);
return db.delete(DBContract.AttributiRegistrazione.NOME_TABELLA,
DBContract.AttributiRegistrazione.NOME + "=" + name, null) == 1;
}
public Cursor getAllEntries(){
return db.query(DBContract.AttributiRegistrazione.NOME_TABELLA,
null, null, null, null, null, null);
}
ERROR LOG
E/SQLiteLog: (1) table Registrazione has no column named Anno_nascita 04-10 13:57:21.142 10175-10175/com.b.uzzo.snappaw E/SQLiteDatabase: Error inserting Anno_nascita=2000 Peso=10.0 Nome=simone Sesso=Maschio Razza=Akita Inu
android.database.sqlite.SQLiteException: table Registrazione has no column named Anno_nascita (code 1): , while compiling: INSERT INTO Registrazione(Anno_nascita,Peso,Nome,Sesso,Razza) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1500)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1373)
at com.b.uzzo.snappaw.DBAdapter.insertUser(DBAdapter.java:49)
at com.b.uzzo.snappaw.HomeActivity.addNewItem(HomeActivity.java:105)
at com.b.uzzo.snappaw.HomeActivity.onResume(HomeActivity.java:140)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6770)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3522)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3591)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2825)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1542)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1085)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:946)
But it's created in DBContract class
public class DBContract {
static final String DB_NAME = "RegistrazioneCuccioli";
static final int DB_VERSION = 1;
static abstract class AttributiRegistrazione implements BaseColumns{
static final String NOME_TABELLA = "Registrazione";
static final String NOME = "Nome";
static final String RAZZA = "Razza";
static final String SESSO = "Sesso";
static final String PESO = "Peso";
static final String ANNO_NASCITA = "Anno_nascita";
}
}
In fillData method of HomeActivity class, You are adding data into Arraylist using list.add(0,new User()),which add your data into 0 index, that is cause of your problem. You should have to call list.add(user)
Try this updated Code:
public void fillData(){
Cursor cursor = dbAdapter.getAllEntries();
this.listUser.clear();
if (cursor.moveToFirst()){
do {
long idx = cursor.getLong(cursor.getColumnIndex(DBContract.AttributiRegistrazione._ID));
String nome = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.NOME));
String razza = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.RAZZA));
String sesso = cursor.getString(cursor.getColumnIndex(DBContract.AttributiRegistrazione.SESSO));
User user = new User(idx, nome, razza, sesso, 10, 2000);
this.listUser.add(user);
}while(cursor.moveToNext());
}
cursor.close();
adapter.notifyDataSetChanged();}

Multiple List RecyclerView SQLitedatabase

here's the structure
I have an app that makes the users' all his/her favorites placed on one place. So that he/she will not go through all the data. All I want is to have a recyclerview with multiple list that the "ListTitle" dynamically created, and when the "ListTitle" is already in it, only the child will appear. If not, create again another cardview. Thanks in advance.
My Code:
LoadsFavoriteAdapter.java
public class LoadFavoritesAdapter extends RecyclerView.Adapter<LoadFavoritesAdapter.LoadFavoritesViewHolder> {
private ArrayList<LoadFavorites> loadFavorites;
private Context context;
private ArrayList<LoadFavorites> mloadFavorites;
final String loadParent = "";
public LoadFavoritesAdapter(ArrayList<LoadFavorites> loadFavorites, Context context){
this.loadFavorites = loadFavorites;
this.context = context;
this.mloadFavorites = loadFavorites;
}
public class LoadFavoritesViewHolder extends RecyclerView.ViewHolder{
TextView txtLoadNameTest, txtLoadAmountTest;
public LoadFavoritesViewHolder(View view){
super(view);
txtLoadAmountTest = view.findViewById(R.id.txtLoadAmountTest);
txtLoadNameTest = view.findViewById(R.id.txtLoadNameTest);
}
}
public LoadFavoritesViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favorite_item, parent, false);
return new LoadFavoritesViewHolder(itemView);
}
public void onBindViewHolder(final LoadFavoritesViewHolder holder, int position){
holder.txtLoadNameTest.setText(loadFavorites.get(position).getLoadName());
holder.txtLoadAmountTest.setText(loadFavorites.get(position).getLoadAmount());
}
public int getItemCount(){
return mloadFavorites.size();
}}
Favorites.java
public class Favorites extends AppCompatActivity {
Database localDb;
Context CTX = this;
private RecyclerView recyclerView;
private ArrayList<LoadFavorites> loadFavorites;
private LoadFavoritesAdapter loadFavoritesAdapter;
private Database database;
private ArrayList<LoadFavorites> mloadFavorites;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
localDb = new Database(this);
recyclerView = findViewById(R.id.recycler_favorites);
loadFavorites = new ArrayList<>();
loadFavoritesAdapter = new LoadFavoritesAdapter(loadFavorites, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(loadFavoritesAdapter);
database = new Database(this);
getDataFromSQLite();
}
private void getDataFromSQLite(){
new AsyncTask<Void, Void, Void>(){
protected Void doInBackground(Void... params){
loadFavorites.clear();
loadFavorites.addAll(database.getFavorites());
return null;
}
protected void onPostExecute(Void aVoid){
super.onPostExecute(aVoid);
}
}.execute();
}}
Database.java
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="Favorites.db";
private static final int DB_VER=1;
public Database(Context context) {
super(context, DB_NAME, null, DB_VER);
try{
String myPath = context.getFilesDir().getAbsolutePath(); // also check the extension of you db file
File dbfile = new File(myPath);
if(dbfile.exists()){
Toast.makeText(context, "database exists", Toast.LENGTH_LONG).show();
Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "cant find database", Toast.LENGTH_LONG).show();
Toast.makeText(context, ""+myPath, Toast.LENGTH_SHORT).show();
}
}
catch(SQLiteException e){
System.out.println("Database doesn't exist");
}
}
public void addToFavorites(String loadId, String loadName, String loadDetail, String loadNumber, String loadDuration, String loadAmount, String loadParent){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("INSERT INTO Favorites(LoadId, LoadName, LoadDetail, LoadNumber, LoadDuration, LoadAmount, LoadParent) VALUES('%s','%s','%s','%s','%s','%s','%s');", loadId, loadName, loadDetail, loadNumber, loadDuration, loadAmount, loadParent);
db.execSQL(query);
}
public void removeFromFavorites(String loadId){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("DELETE FROM Favorites WHERE LoadId='%s';", loadId);
db.execSQL(query);
}
public boolean isFavorite(String loadId){
SQLiteDatabase db = getReadableDatabase();
String query = String.format("SELECT * FROM Favorites WHERE LoadId='%s';", loadId);
Cursor cursor = db.rawQuery(query,null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
public Cursor getInformation(Database database){
SQLiteDatabase db = database.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] columns = {"LoadId", "LoadParent"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor CR = qb.query(db,columns,null,null,null,null,null);
return CR;
}
public List<LoadFavorites> getFavorites(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"LoadId", "LoadName", "LoadDetail", "LoadNumber", "LoadDuration", "LoadAmount", "LoadParent"};
String sqlTable = "Favorites";
qb.setTables(sqlTable);
Cursor c = qb.query(db,sqlSelect,null,null,null,null,null);
final List<LoadFavorites> result = new ArrayList<>();
if(c.moveToFirst()){
do{
result.add(new LoadFavorites(c.getString(c.getColumnIndex("LoadId")),
c.getString(c.getColumnIndex("LoadName")),
c.getString(c.getColumnIndex("LoadDetail")),
c.getString(c.getColumnIndex("LoadNumber")),
c.getString(c.getColumnIndex("LoadDuration")),
c.getString(c.getColumnIndex("LoadAmount")),
c.getString(c.getColumnIndex("LoadParent"))
));
}while(c.moveToNext());
}
return result;
}}

how to pass Position wise object data one activity to another using recyclerview and databse in android

I have create the recycerview and this recycerview display the Person image ,person name and + button when i have press + button change the button image like true.and after recycerview bottom one button this button click all data show the next activity..
My Adapter
public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;
private ItemFilter mFilter = new ItemFilter();
public BuildCustomAdapter(List<People> buildList) {
this.peopleList = buildList;
this.peopleListCopy = new ArrayList<>();
peopleListCopy.addAll(buildList);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.build_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
People people = peopleList.get(position);
byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivPeopleImage.setImageBitmap(decodedByte);
holder.tvPersonName.setText(people.getPeopleName());
holder.button.setSelected(people.isSelected());
holder.button.setOnClickListener(new onSelectListener(position));
}
#Override
public int getItemCount() {
return peopleList.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// public ImageView ivPeopleImage;
public TextView tvPersonName;
public Button button;
public CircularImageView ivPeopleImage;
public MyViewHolder(View itemView) {
super(itemView);
ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
button = (Button) itemView.findViewById(R.id.addbn);
}
}
private class ItemFilter extends Filter {
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<People> filterList = new ArrayList<>();
for (int i = 0; i < peopleListCopy.size(); i++) {
if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
People peopleName = peopleListCopy.get(i);
filterList.add(peopleName);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = peopleListCopy.size();
results.values = peopleListCopy;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
peopleList = (List<People>) results.values;
notifyDataSetChanged();
}
}
private class onSelectListener implements View.OnClickListener {
int mPosition;
public onSelectListener(int position) {
mPosition = position;
}
#Override
public void onClick(View view) {
view.setSelected(!view.isSelected());
People people = peopleList.get(mPosition);
people.setSelected(!people.isSelected());
notifyDataSetChanged();
}
}
Activity
public class BulidActivity extends AppCompatActivity {
private List<People> peopleList = new ArrayList<>();
private List<People> peopleListCopy = new ArrayList<>();
private RecyclerView recyclerView;
private BuildCustomAdapter buildCustomAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bulid);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
BuildData();
peopleListCopy.addAll(peopleList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(buildCustomAdapter);
AddTxt();
BtnBuildNow();
}
private void BtnBuildNow() {
Button btnnuildnow = (Button) findViewById(R.id.btn_build_now);
btnnuildnow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BulidActivity.this, AlertList.class);
startActivity(intent);
}
});
}
private void AddTxt() {
EditText editTxt = (EditText) findViewById(R.id.etSearch);
editTxt.setTextColor(Color.WHITE);
editTxt.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.setFocusable(true);
v.setFocusableInTouchMode(true);
return false;
}
});
editTxt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() <= 0) {
peopleList.clear();
peopleList.addAll(peopleListCopy);
recyclerView.setAdapter(null);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
recyclerView.setAdapter(buildCustomAdapter);
} else {
buildCustomAdapter.getFilter().filter(s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<People> BuildData() {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
if (db.open()) {
peopleList = db.getPeople();
}
return peopleList;
}
Model class
public class People implements Serializable {
private String peopleImage;
private String peopleName;
private boolean selected;
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getPeopleName() {
return peopleName;
}
public void setPeopleImage(String peopleImage) {
this.peopleImage = peopleImage;
}
public String getPeopleImage() {
return peopleImage;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
DatabaseHelper.class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/databasename/databases/";
private static final String DB_NAME = "alertme.db";
private final String TABLE_PEOPLE = "people";
private final String TABLE_CATEGORY = "category";
private final String CATEGORY_NAME = "name";
private final String ID = "id";
private final String CATEGORY_ID = "category_id";
private final String PEOPLE_IMAGE = "image";
private final String PEOPLE_NAME = "name";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch (SQLException sqle) {
myDataBase = null;
return false;
}
}
public List<People> getPeople(String category_id) {
List<People> peoples = new ArrayList<>();
try {
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery("select * from people where category_id = " + category_id, null);
while (cursor.moveToNext()) {
String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));
String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));
People people = new People();
people.setPeopleName(peopleName);
people.setPeopleImage(peopleImage);
peoples.add(people);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return peoples;
}
public List<Category> getCategory() {
List<Category> categoryList = new ArrayList<>();
try {
String query = " SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int categoryID = cursor.getInt(cursor.getColumnIndex(ID));
String categoryName = cursor.getString(cursor.getColumnIndex(CATEGORY_NAME));
Category category = new Category();
category.setId(categoryID);
category.setCategoryName(categoryName);
categoryList.add(category);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return categoryList;
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
First you should implement Serializable interface in your Build model class like this :-
public class Build implements Serializable{
//Content will be as it is
}
Change your clickListener like this :-
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("build",build);
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
In the onCreate method of receiving activity write this :-
Build build = (Build) getIntent().getSerializableExtra("build");
Add Intent in below Method,
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("key","value");
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
Huge mistak that you register to the click event on your ViewHolder! you will get diffrent position from the actual because when android use notifyItemMoved the viewBindHolder will not be called and than you got the wrong position.
and in the click listener implementation you should pass Intent with your data

What is error no such table: ... in android?

I need to show my data on a ListView everything is correct but When i run this project i get this error :
(1) no such table: WebSite_CategoryBack
My DataBase is correct .I think that my code has error.
This is my MainActivity.java:
public class MainActivity extends ActionBarActivity {
public static Context context;
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
DB db = new DB(MainActivity.this);
public String Titel_Drawer;
public String messageCursor;
private ListView mainListView ;
public SQLiteDatabase sql;
public Cursor cursor;
public ArrayList<String> array;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file= new File(DIR_DATABASE);
file.mkdirs();
try{
db.createDataBase();
}catch (IOException e) {
Log.e("create DB3", e.toString());
}
try{
db.openDataBase();
}catch (SQLException e) {
Log.e("create DB3", e.toString());
}
sql = db.getReadableDatabase();
cursor = sql.rawQuery("SELECT * FROM WebSite_CategoryBack;", null);
array = new ArrayList<String>();
while(cursor.moveToNext()){
Titel_Drawer = cursor.getString(cursor.getColumnIndex("tittle"));
array.add(Titel_Drawer);
}
cursor.close();
mainListView = (ListView) findViewById( R.id.mainListView );
listAdapter = new ArrayAdapter<String>(this, R.layout.drawer_layout_main,R.id.rowTextView_Main, array);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
int itemposition = position;
String itemvalue = (String) mainListView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position :"+itemposition+" ListItem : " +itemvalue , Toast.LENGTH_LONG).show();
}
});
mainListView.setTextFilterEnabled(true);
}
And this is my DB.java:
public class DB extends SQLiteOpenHelper{
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
private static String DB_NAME = "Resaleh.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DB(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database --> "+e.toString());
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DIR_DATABASE + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
Log.e("asdf", "checkDataBase-->"+e.toString());
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#getReadableDatabase()
*/
#Override
public synchronized SQLiteDatabase getReadableDatabase() {
return super.getReadableDatabase();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DIR_DATABASE + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
try{
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
}catch (IOException e) {
Log.e("Copy", e.toString());
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DIR_DATABASE + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
THANKS.
There is one good reason why this error will come and i used to get this...
The reason why i got was like i created the db without THAT TABLE now when during course of time if i add a new table then it wont appear and i used to get the error so to make it fresh i used to do the following :-
rename DB.
change version of DB.
uninstall the app.
now install the app.
This used to solve the issue in my case...
thx
By default the SQLite DB is created and saved in the path : data/data/.... on internal storage and opened from there. In case we want to save it on SD card, the address should be manually set and called exactly from the SD card otherwise we will have error.
The correct code is:
public class MainActivity extends ActionBarActivity {
public static Context context;
public static final String DIR_SDCARD =Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_DATABASE = DIR_SDCARD + "/Mafatih/";
public String Titel_Drawer;
public String messageCursor;
private ListView mainListView ;
public SQLiteDatabase sql;
public Cursor cursor;
public ArrayList<String> array;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file= new File(DIR_DATABASE);
file.mkdirs();
sql = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/Resaleh.db", null);
cursor = sql.rawQuery("SELECT * FROM WebSite_CategoryBack;", null);
array = new ArrayList<String>();
while(cursor.moveToNext()){
Titel_Drawer = cursor.getString(cursor.getColumnIndex("tittle"));
array.add(Titel_Drawer);
}
cursor.close();
mainListView = (ListView) findViewById( R.id.mainListView );
listAdapter = new ArrayAdapter<String>(this, R.layout.drawer_layout_main,R.id.rowTextView_Main, array);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
int itemposition = position;
String itemvalue = (String) mainListView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position :"+itemposition+" ListItem : " +itemvalue , Toast.LENGTH_LONG).show();
}
});
mainListView.setTextFilterEnabled(true);
}
Delete the DB.java.THANKS.

Categories