Good evening friends , I'm having trouble to fill the listview with data that has been recorded in a table SQlite works , however only brings the last item , and the same view when I load the result of a webservice with the same data appears correct with all items
Base Adapter:
public class Ad_Categoria_Produto extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Ac_Df_Produto_Categoria> categoria_produtoList;
private String[] bgColors;
private int lastPosition = -1;
public Ad_Categoria_Produto(Activity activity, List<Ac_Df_Produto_Categoria> movieList) {
this.activity = activity;
this.categoria_produtoList = movieList;
}
#Override
public int getCount() {
return categoria_produtoList.size();
}
#Override
public Object getItem(int location) {
return categoria_produtoList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.la_categoria_produtorow, null);
TextView CategoriaNome = (TextView) convertView.findViewById(R.id.textCategoriaNome);
CategoriaNome.setText(categoria_produtoList.get(position).getDescricaoInternet());
Animation animation = AnimationUtils.loadAnimation(activity.getApplicationContext(), (position > lastPosition) ? R.anim.rotate_nav_drawer_image : R.anim.up_from_bottom);
convertView.startAnimation(animation);
lastPosition = position;
return convertView;
}
Class representing the table in the database :
public class Ac_Df_Produto_Categoria {
private int id;
private int PCT_ID;
private String descricao_internet;
private String possui_tamanho;
public Ac_Df_Produto_Categoria(){
//generica
}
public Ac_Df_Produto_Categoria(int id, int PCT_ID, String descricao_internet, String possui_tamanho){
this.id = id;
this.PCT_ID = PCT_ID;
this.descricao_internet = descricao_internet;
this.possui_tamanho = possui_tamanho;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPCT_ID() {
return PCT_ID;
}
public void setPCT_ID(int PCT_ID) {
this.PCT_ID = PCT_ID;
}
public String getDescricaoInternet() {
return descricao_internet;
}
public void setDescricaoInternet(String descricao) {
this.descricao_internet = descricao;
}
public String getPossui_tamanho() {
return possui_tamanho;
}
public void setPossui_tamanho(String possui_tamanho) {
this.possui_tamanho = possui_tamanho;
}
SQLiteOpenHelper:
public class Ac_Bs_Produto_Categoria extends SQLiteOpenHelper {
public SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private Ad_Categoria_Produto adapter;
private List<Ac_Df_Produto_Categoria> categoria_produtoList;
public static final int VERSAO_DATABASE = 1;
public static final String NOME_DATABASE = "BD_PRODUTO_CATEGORIA";
public static final String NOME_TABELA_TERMOS_USO = "produtos_categorias_21";
public Ac_Bs_Produto_Categoria(Context context) {
super(context, NOME_DATABASE, null, VERSAO_DATABASE);
}
#Override
public void onCreate(SQLiteDatabase db) {
String Create_Tabela_Termos_Uso = "CREATE TABLE " + NOME_TABELA_TERMOS_USO + "("
+ "_id INTEGER PRIMARY KEY,"
+ "PCT_Id TEXT" + ","
+ "DescricaoInternet TEXT" + ","
+ "Possui_tamanho TEXT" + ")";
db.execSQL(Create_Tabela_Termos_Uso);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String Drop_Tabela_Termos_Uso = "DROP TABLE IF EXISTS " + NOME_TABELA_TERMOS_USO;
db.execSQL(Drop_Tabela_Termos_Uso);
onCreate(db);
}
public void InserirCategoria_Produto(Ac_Df_Produto_Categoria ac_df_produtoCategoria){
ContentValues is_c = new ContentValues();
is_c.put("_id", ac_df_produtoCategoria.getId());
is_c.put("PCT_ID", ac_df_produtoCategoria.getPCT_ID());
is_c.put("DescricaoInternet", ac_df_produtoCategoria.getDescricaoInternet());
is_c.put("Possui_tamanho", ac_df_produtoCategoria.getPossui_tamanho());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(NOME_TABELA_TERMOS_USO, null, is_c);
db.close();
}
public boolean DeletarCategoria_Produto() {
SQLiteDatabase db = getWritableDatabase();
if (db.delete(NOME_TABELA_TERMOS_USO, "_id <>" + 0, null) > 0)
return true;
else
return false;
}
public Ac_Df_Produto_Categoria buscarCategoria_ProdutoTodos() {
Ac_Df_Produto_Categoria Cat_prod = new Ac_Df_Produto_Categoria();
String query = "Select * FROM " + NOME_TABELA_TERMOS_USO;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
Cat_prod.setId(Integer.parseInt(cursor.getString(0)));
Cat_prod.setPCT_ID(Integer.parseInt(cursor.getString(1)));
Cat_prod.setDescricaoInternet(cursor.getString(2));
Cat_prod.setPossui_tamanho(cursor.getString(3));
} while(cursor.moveToNext());
}
db.close();
return Cat_prod;
}
}
And finally Activity ( Fragment ) :
public class Fr_Categoria_Produto extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private Ad_Categoria_Produto adapter;
private List<Ac_Df_Produto_Categoria> categoria_produtoList;
String nCategoria = null;
String nomeCategoria = null;
int nPosition = 0;
String vPossuiTamanho = null;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fr_categoria_produto, container, false);
listView = (ListView) rootview.findViewById(R.id.listView);
swipeRefreshLayout = (SwipeRefreshLayout) rootview.findViewById(R.id.swipe_refresh_layout);
categoria_produtoList = new ArrayList<>();
adapter = new Ad_Categoria_Produto(getActivity(), categoria_produtoList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
Ac_Bs_Produto_Categoria con = new Ac_Bs_Produto_Categoria(getContext());
Ac_Df_Produto_Categoria config = con.buscarCategoria_ProdutoTodos();
if (config != null) {
if (config.getDescricaoInternet() != null) {
categoria_produtoList.add(0, config);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}
}
}
);
return rootview;
}
}
Related
I'm developing an application in Android Studio using this library: com.daimajia.swipelayout:library:1.2.0#aar. My app user a SQLite database with the following classes:
BDSQLiteHelper.java
public class BDSQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ExtraOficial";
private static final String TABELA_VAZAMENTOS = "VazamentosToSQL";
private static final String vazID = "VazID";
private static final String nomeServico = "nomeServico";
private static final String[] VAZ_COLUNAS = {vazID, nomeServico};
public BDSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_VAZAMENTOTABLE = "CREATE TABLE VazamentosToSQL ("+
"vazID INTEGER PRIMARY KEY AUTOINCREMENT,"+
"nomeServico)";
db.execSQL(CREATE_VAZAMENTOTABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS VazamentosToSQL");
this.onCreate(db);
}
public void addVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(nomeServico, VazamentosToSQL.getNomeServico());
db.insert(TABELA_VAZAMENTOS, null, values);
db.close();
}
public VazamentosToSQL getVazamentos (int vazID) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABELA_VAZAMENTOS,
VAZ_COLUNAS,
" vazID = ?",
new String[] {String.valueOf(vazID)},
null,
null,
null,
null);
if (cursor == null) {
return null;
} else {
cursor.moveToFirst();
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
return VazamentosToSQL;
}
}
private VazamentosToSQL cursorTovazamentos(Cursor cursor) {
VazamentosToSQL VazamentosToSQL = new VazamentosToSQL();
VazamentosToSQL.setVazID(Integer.parseInt(cursor.getString(0)));
VazamentosToSQL.setNomeServico(cursor.getString(1));
return VazamentosToSQL;
}
public ArrayList<VazamentosToSQL> getAllVazamentos() {
ArrayList<VazamentosToSQL> listaVazamentos = new ArrayList<VazamentosToSQL>();
String query = "SELECT * FROM " + TABELA_VAZAMENTOS + " ORDER BY "+ vazID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
listaVazamentos.add(VazamentosToSQL);
} while (cursor.moveToNext());
}
return listaVazamentos;
}
[...]
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS,
vazID+" =?",
new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
VazamentosToSQL.java
public class VazamentosToSQL {
private int vazID;
private String nomeServico;
public int getVazID() { return vazID; }
public void setVazID(int vazID) {
this.vazID = vazID;
}
public String getNomeServico() { return nomeServico; }
public void setNomeServico(String nomeServico) { this.nomeServico = nomeServico; }
}
ListViewActivity.java:
[...]
//variables
private BDSQLiteHelper bd;
ArrayList<VazamentosToSQL> listaVazamentos;
SwipeLayout swipeLayout;
private final static String TAG = ListViewActivity.class.getSimpleName();
vazamentosAdapter adapter;
ListView lista;
[...]
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
[...]
bd = new BDSQLiteHelper(this);
lista = (ListView) findViewById(R.id.lvdenuncias);
listaVazamentos = bd.getAllVazamentos();
setListViewHeader();
setListViewAdapter();
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { //aqui é o vazamentosAdapter
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ExibeVazamentosActivity.this, DetalhesVazamentosActivity.class);
intent.putExtra("vazID", listaVazamentos.get(position).getVazID());
startActivity(intent);
}
});
#Override
protected void onStart() {
super.onStart();
updateAdapter(); //Refresh ListView items
}
private void setListViewHeader() {
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview, lista, false);
totalClassmates = (TextView) header.findViewById(R.id.total);
swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
setSwipeViewFeatures();
//UNNECESSARY for me: lista.addHeaderView(header);
}
private void setSwipeViewFeatures() {
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
//add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));
swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
Log.i(TAG, "onClose");
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
Log.i(TAG, "on swiping");
}
#Override
public void onStartOpen(SwipeLayout layout) {
Log.i(TAG, "on start open");
}
#Override
public void onOpen(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally show");
}
#Override
public void onStartClose(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally close");
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
}
private void setListViewAdapter() {
adapter = new vazamentosAdapter(this, listaVazamentos);
lista.setAdapter(adapter);
}
public void updateAdapter() {
listaVazamentos.clear();
listaVazamentos.addAll(bd.getAllVazamentos());
adapter.notifyDataSetChanged(); //update adapter
lista.invalidateViews();
lista.refreshDrawableState();
}
}
vazamentosAdapter.java:
public class vazamentosAdapter extends ArrayAdapter<VazamentosToSQL> {
private final Context context;
private final ArrayList<VazamentosToSQL> elementos;
File imgFile;
private Bitmap bitmap;
private ExifInterface exifObject;
private ExibeVazamentosActivity activity;
int vazID;
private SQLiteDatabase bd;
public vazamentosAdapter(Context context, ArrayList<VazamentosToSQL> elementos) {
super(context, R.layout.linha, elementos);
this.context = context;
this.elementos = elementos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.linha, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
}else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
[...]
editText.setText(elementos.get(position).getVaznomeServico());
holder.btnEdit.setOnClickListener(onEditListener(position, holder));
holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));
return convertView;
}
private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
/**--------------Tried it, not working =( ---------------*/
elementos.get(position).getVazID();
//listaVazamentos.remove(position);
//activity.listaVazamentos.remove(position);
//bd = context.openOrCreateDatabase("DesoExtraOficial", Activity.MODE_PRIVATE, null);
//bd.execSQL("DELETE from VazamentosToSQL where vazID = '" + elementos.get(position).getVazID() + "'");
//bd.close();
//elementos.remove(position);
Toast.makeText(context, "ID: "+elementos.get(position).getVazID(),Toast.LENGTH_LONG).show();
bd.deleteVazamentos(VazamentosToSQL);
holder.swipeLayout.close();
// activity.updateAdapter(); //Executa o método "updateAdapter()" na Activity "ExibeVazamentos"
/**--------------Tried it, not working =( ---------------*/
}
};
}
private class ViewHolder {
private TextView name;
private View btnDelete;
private View btnEdit;
private SwipeLayout swipeLayout;
private ListView listv;
public ViewHolder(View v) {
swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
btnDelete = v.findViewById(R.id.delete);
btnEdit = v.findViewById(R.id.edit_query);
listv = (ListView) v.findViewById(R.id.lvdenuncias);
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
}
}
The mentioned library is working great. But i'm trying to delete database row when user click in a button according to the listview selected line. With this code: elementos.get(position).getVazID() I get the database index. But I can't delete from database. Someone can help me with the code to delete row from database and line from listview?
Try changing this:
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS, vazID+" =?", new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
To this:
public void deleteVazamentos(int vazID) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABELA_VAZAMENTOS, "vazID=" + vazID, null);
}
Then if you want to delete a row, you can call:
(Inside onDeleteListener)
bd.deleteVazamentos(elementos.get(position).getVazID());
my app stores name and result in SQLite database and displays that in RecycleViewer. Previously I use a listView where on LongClick I could delete an item like here LuckyNumbersApk/commit/4cec554359662d557626935046b8de68fb1b5c60
now I have switched to recyclerView I can't handle it properly. When I delete it, it disapears but when I reload the fragment the deleted entry reappears again. I assume it because the item is deleted only from the list in the adapter but how can I delete it from the list that is in the fragment that actually calls the recylerViewer?
This is my Adapter:
public class DatabaseAdapter extends RecyclerView.Adapter {
List dataModelArrayList;
Context context;
public DatabaseAdapter(List<DataModel> dataModelArrayList, Context context) {
this.dataModelArrayList = dataModelArrayList;
this.context = context;
}
class Myholder extends RecyclerView.ViewHolder implements CardView.OnLongClickListener {
TextView name, result;
public Myholder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.card_name);
result = (TextView) itemView.findViewById(R.id.card_result);
CardView cardView = (CardView) itemView.findViewById(R.id.card_view);
cardView.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(context)
.setIcon(R.drawable.ic_warning_black_24dp)
.setTitle("Delete result")
.setMessage("Are you sure you want delete this result?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* This is where deletions should be handled */
int id = getAdapterPosition();
DataBHelper database = new DataBHelper(context);
database.deleteEntry(id);
dataModelArrayList.remove(id);
notifyItemRemoved(id);
notifyDataSetChanged();
database.close();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, int position) {
DataModel dataModel = dataModelArrayList.get(position);
holder.name.setText(dataModel.getName());
holder.result.setText(dataModel.getResult());
}
#Override
public int getItemCount() {
return dataModelArrayList.size();
}}
This is DataBHelper:
public class DataBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "results_database";
public static final String RESULTS_TABLE_NAME = "results_table";
public static final String RESULTS_COLUMN_ID = "_id";
public static final String RESULTS_COLUMN_NAME = "name";
public static final String RESULTS_COLUMN_RESULT = "result";
public DataBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE " + RESULTS_TABLE_NAME + " (" +
RESULTS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
RESULTS_COLUMN_NAME + " TEXT, " +
RESULTS_COLUMN_RESULT + " TEXT" + ")");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + RESULTS_TABLE_NAME);
onCreate(sqLiteDatabase);
}
public void saveToDB(String fname, String lname, String result) {
SQLiteDatabase database = getWritableDatabase();
ContentValues values = new ContentValues();
String name = fname + " " + lname;
values.put(DataBHelper.RESULTS_COLUMN_NAME, name);
values.put(DataBHelper.RESULTS_COLUMN_RESULT, result);
database.insert(DataBHelper.RESULTS_TABLE_NAME, null, values);
database.close();
}
public List<DataModel> readDB(){
List<DataModel> data=new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+RESULTS_TABLE_NAME+" ;",null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
dataModel= new DataModel();
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String result = cursor.getString(cursor.getColumnIndexOrThrow("result"));
dataModel.setName(name);
dataModel.setResult(result);
stringBuffer.append(dataModel);
data.add(dataModel);
}
return data;
}
public void clearDatabase() {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String clearDBQuery = "DELETE FROM "+RESULTS_TABLE_NAME;
sqLiteDatabase.execSQL(clearDBQuery);
}
public void deleteEntry(long row) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.delete(RESULTS_TABLE_NAME, RESULTS_COLUMN_ID + "=" + row, null);
}}
And this is the fragment which loads recyclerViewer
public class ResultsFragment extends Fragment {
DataBHelper database;
RecyclerView recyclerView;
DatabaseAdapter recycler;
public List<DataModel> datamodel;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_results,
container, false);
datamodel =new ArrayList<DataModel>();
recyclerView = (RecyclerView) view.findViewById(R.id.app_recycle_view);
database = new DataBHelper(getActivity());
datamodel = database.readDB();
recycler = new DatabaseAdapter(datamodel, getActivity());
RecyclerView.LayoutManager reLayoutManager =new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(reLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(recycler);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
if (datamodel.isEmpty()) {
recyclerView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
}
return view;
}}
In onCreateViwHolder:
#Override
public void onBindViewHolder(Myholder holder, int position) {
DataModel dataModel = dataModelArrayList.get(position);
holder.name.setText(dataModel.getName());
holder.result.setText(dataModel.getResult());
holder.id = dataModel.getId();
}
Add long id; into the ViewHolder, so your onClick you can delete the int id = getAdapterPosition(); and the id will be the id from the model.
To remove still use the adapter position:
dataModelArrayList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
I am an amateur android developer and I would like to get user entered items from the database and then display it in a recyclerview list (not ListView) that is in a fragment.
So far I have already created the SQLite database which saves the data into it, I just want to know I can display all this information in the recyclerview. The Java code shown below shows what I want to make but is in a listview instead of a recyclerview.
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
public static final String DATABASE_NAME = "budget10.db";
public static final String TABLE_NAME = "expense_table";
public static final String TABLE_NAME2 = "income_table";
public static final String COL_1 = "_id";
public static final String COL_2 = "_id";
public static final String EXPENSE_AMOUNT = "EXPENSE_AMOUNT";
public static final String EXPENSE_DATE = "DATE";
public static final String EXPENSE_NOTES = "NOTES";
public static final String INCOME_AMOUNT = "INCOME_AMOUNT";
public static final String INCOME_DATE = "DATE";
public static final String INCOME_NOTES = "NOTES";
public static final String INCOME_CATEGORY = "INCOME_CATEGORY";
public static final String EXPENSE_CATEGORY = "EXPENSE_CATEGORY";
public static final String EXPENSE_ACCOUNT = "EXPENSE_ACCOUNT";
public static final String INCOME_ACCOUNT = "INCOME_ACCOUNT";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 3);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, EXPENSE_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, EXPENSE_CATEGORY TEXT, EXPENSE_ACCOUNT TEXT)");
db.execSQL("create table " + TABLE_NAME2 + " (_id INTEGER PRIMARY KEY AUTOINCREMENT,INCOME_AMOUNT DOUBLE,DATE INTEGER,NOTES TEXT, INCOME_CATEGORY TEXT, INCOME_ACCOUNT TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
onCreate(db);
}
public boolean insertexpenseData(Double amount_expense, String date_expense, String notes_expense, String category_expense, String expense_account) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EXPENSE_AMOUNT, amount_expense);
contentValues.put(EXPENSE_DATE, date_expense);
contentValues.put(EXPENSE_NOTES, notes_expense);
contentValues.put(EXPENSE_CATEGORY, category_expense);
contentValues.put(EXPENSE_ACCOUNT, expense_account);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean insertincomeData(Double amount_income, String date_income, String notes_income, String category_income, String income_account) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INCOME_AMOUNT, amount_income);
contentValues.put(INCOME_DATE, date_income);
contentValues.put(INCOME_NOTES, notes_income);
contentValues.put(INCOME_CATEGORY, category_income);
contentValues.put(INCOME_ACCOUNT, income_account);
long result = db.insert(TABLE_NAME2, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getexpenseData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public Cursor getincomeData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME2, null);
return res;
}
public boolean updateexpenseData(String id, String amount, String date, String notes, String catagory_income) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(EXPENSE_AMOUNT, amount);
contentValues.put(EXPENSE_DATE, date);
contentValues.put(EXPENSE_NOTES, notes);
contentValues.put(EXPENSE_CATEGORY, catagory_income);
db.update(TABLE_NAME, contentValues, "_id = ?", new String[]{id});
return true;
}
public boolean updateincomeData(String id, String amount, String date, String notes, String catagory_income) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, id);
contentValues.put(INCOME_AMOUNT, amount);
contentValues.put(INCOME_DATE, date);
contentValues.put(INCOME_NOTES, notes);
contentValues.put(INCOME_CATEGORY, catagory_income);
db.update(TABLE_NAME2, contentValues, "_id = ?", new String[]{id});
return true;
}
public Integer deleteexpenseData(String _id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "_id = ?", new String[]{_id});
}
public Integer deleteincomeData(String _id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME2, "_id = ?", new String[]{_id});
}
public double getNetBudget() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) - (SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table) FROM income_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netBudget = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netBudget = cursor.getDouble(0);
}
cursor.close();
return netBudget;
}
public double getTotalExpense() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(EXPENSE_AMOUNT) FROM expense_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netExpense = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netExpense = cursor.getDouble(0);
}
cursor.close();
return netExpense;
}
public double getTotalIncome() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT TOTAL(INCOME_AMOUNT) FROM income_table";
Cursor cursor = db.rawQuery(selectQuery, null);
double netIncome = 0.00; // if there is no row, this will mean 0 is returned. You could also set it to -1, or throw an Exception if no record is returned
if (cursor.moveToFirst()) {
netIncome = cursor.getDouble(0);
}
cursor.close();
return netIncome;
}
public void deleteAllIncome() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME2, null, null);
db.execSQL("delete from " + TABLE_NAME2);
db.close();
}
public void deleteAllExpense() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
db.execSQL("delete from " + TABLE_NAME);
db.close();
}
}
Fragment ListView that I want to turn into a recyclerview
public class tab2income extends Fragment {
private static final String TAG = "tab2income";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
View rootView;
Cursor incomedata;
SimpleCursorAdapter sca;
DecimalFormat formatter = new DecimalFormat("0.00");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab2income, container, false);
return rootView;
}
#Override
public void onActivityCreated( Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (ListView) rootView.findViewById(R.id.listViewincome);
mListView.setEmptyView(rootView.findViewById(R.id.empty));
mDatabaseHelper = new DatabaseHelper(getActivity());
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
incomedata = mDatabaseHelper.getincomeData();
sca = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_1, incomedata, new String[]{DatabaseHelper.INCOME_AMOUNT}, new int[]{android.R.id.text1}, 0);
mListView.setAdapter(sca);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
l,
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
incomedata.close();
}
public void displayNoteDate(String noteContent, String dateValue,String category, final long noteID,String account) {
MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity())
.title("Income Information")
.content("Date: "+ dateValue+
"\nCategory: "+category+
"\nAccount: "+account+
"\nNote: "+noteContent)
.positiveText("close")
.negativeText("delete")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
mDatabaseHelper.deleteincomeData(Long.toString(noteID));
incomedata = mDatabaseHelper.getincomeData();
sca.swapCursor(incomedata);
}
});
builder.show();
}
}
EDIT
This is what I have done so far with the code in the answer from Saurov Bagchi and I have the recyclerview in my xml file and nothing happens when an item is clicked:
Fragment
public class tab2income extends Fragment implements ItemClickListener {
private static final String TAG = "tab2income";
DatabaseHelper mDatabaseHelper;
private RecyclerView mListView;
View rootView;
Cursor incomedata;
SimpleCursorAdapter sca;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab2income, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = rootView.findViewById(R.id.ListViewincome);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mListView.setLayoutManager(layoutManager);
mDatabaseHelper = new DatabaseHelper(getActivity());
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
ArrayList<String> arrayList = new ArrayList<>();
MyAdapter myAdapter = new MyAdapter(arrayList);
mListView.setAdapter(myAdapter);
incomedata = mDatabaseHelper.getincomeData();
if(incomedata.moveToFirst()){
do {
arrayList.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_AMOUNT)));
} while (incomedata.moveToNext());
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onDestroy() {
super.onDestroy();
incomedata.close();
}
#Override
public void onClick(View view, int i) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
public void displayNoteDate(String noteContent, String dateValue,String category,String account) {
MaterialDialog.Builder builder= new MaterialDialog.Builder(getActivity())
.title("Income Information")
.content("Date: "+ dateValue+
"\nCategory: "+category+
"\nAccount: "+account+
"\nNote: "+noteContent)
.positiveText("close")
.negativeText("delete")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
}
});
builder.show();
}
}
Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private final ArrayList<String> dataSet;
private ItemClickListener clickListener;
public MyAdapter(ArrayList<String> myDataset) {
dataSet = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//layout of the list item
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(dataSet.get(position));
}
#Override
public int getItemCount() {
return dataSet.size();
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
ViewHolder(View v) {
super(v);
//textview for showing results
mTextView = v.findViewById(android.R.id.text1);
v.setOnClickListener(this);
}
//for click
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
For RecyclerView you need to create your own custom Adapter.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private final ArrayList<String> dataSet;
private ItemClickListener clickListener;
public MyAdapter(ArrayList<String> myDataset) {
dataSet = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//layout of the list item
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(dataSet.get(position));
}
#Override
public int getItemCount() {
return dataSet.size();
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
ViewHolder(View v) {
super(v);
//textview for showing results
mTextView = v.findViewById(android.R.id.text1);
v.setOnClickListener(this);
}
//for click
#Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
Then I am just rewriting the populateListView() method
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
ArrayList<String> arrayList = new ArrayList<>();
MyAdapter myAdapter = new MyAdapter(arrayList);
mListView.setAdapter(myAdapter);
incomedata = mDatabaseHelper.getincomeData();
if(incomedata.moveToFirst()){
do {
arrayList.add(incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_AMOUNT)));
} while (incomedata.moveToNext());
}
myAdapter.notifyDataSetChanged();
}
You also need to create an Interface for each Item Click.
public interface ItemClickListener {
void onClick (View view, int position);
}
And implement this Interface in your Fragment.
public class tab2income extends Fragment implements ItemClickListener{
//All of your codes
#Override
public void onClick (View view, int i) {
int csrpos = incomedata.getPosition();
incomedata.moveToPosition(i);
displayNoteDate(
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_NOTES)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_DATE)),
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_CATEGORY)),
l,
incomedata.getString(incomedata.getColumnIndex(DatabaseHelper.INCOME_ACCOUNT)));
incomedata.moveToPosition(csrpos);
}
}
I want to display data from sqlite database and I will show to listfragment, but until now have not been able to be displayed
Class Barang.java
public class Barang {
private long id;
private String nama_barang;
private String merk_barang;
private String harga_barang;
public Barang()
{
}
/**
* #return the id
*/
public long getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* #return the nama_barang
*/
public String getNama_barang() {
return nama_barang;
}
/**
* #param nama_barang the nama_barang to set
*/
public void setNama_barang(String nama_barang) {
this.nama_barang = nama_barang;
}
/**
* #return the merk_barang
*/
public String getMerk_barang() {
return merk_barang;
}
/**
* #param merk_barang the merk_barang to set
*/
public void setMerk_barang(String merk_barang) {
this.merk_barang = merk_barang;
}
/**
* #return the harga_barang
*/
public String getHarga_barang() {
return harga_barang;
}
/**
* #param harga_barang the harga_barang to set
*/
public void setHarga_barang(String harga_barang) {
this.harga_barang = harga_barang;
}
#Override
public String toString()
{
return id +" "+ nama_barang +" "+ merk_barang + " "+ harga_barang;
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "data_inventori";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "nama_barang";
public static final String COLUMN_MERK = "merk_barang";
public static final String COLUMN_HARGA = "harga_barang";
private static final String db_name ="inventori.db";
private static final int db_version=1;
private static final String db_create = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID +" integer primary key autoincrement, "
+ COLUMN_NAME+ " varchar(50) not null, "
+ COLUMN_MERK+ " varchar(50) not null, "
+ COLUMN_HARGA+ " varchar(50) not null);";
public DBHelper(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(DBHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
DBDataSource.java
public class DBDataSource {
private SQLiteDatabase database;
private DBHelper dbHelper;
private String[] allColumns = { DBHelper.COLUMN_ID,
DBHelper.COLUMN_NAME, DBHelper.COLUMN_MERK,DBHelper.COLUMN_HARGA};
public DBDataSource(Context context)
{
dbHelper = new DBHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Barang createBarang(String nama, String merk, String harga) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, nama);
values.put(DBHelper.COLUMN_MERK, merk);
values.put(DBHelper.COLUMN_HARGA, harga);
long insertId = database.insert(DBHelper.TABLE_NAME, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, DBHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Barang newBarang = cursorToBarang(cursor);
cursor.close();
return newBarang;
}
private Barang cursorToBarang(Cursor cursor)
{
Barang barang = new Barang();
barang.setId(cursor.getLong(0));
barang.setNama_barang(cursor.getString(1));
barang.setMerk_barang(cursor.getString(2));
barang.setHarga_barang(cursor.getString(3));
return barang;
}
public ArrayList<Barang> getAllBarang() {
ArrayList<Barang> daftarBarang = new ArrayList<Barang>();
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Barang barang = cursorToBarang(cursor);
daftarBarang.add(barang);
cursor.moveToNext();
}
cursor.close();
return daftarBarang;
}
public Barang getBarang(long id)
{
Barang barang = new Barang();
Cursor cursor = database.query(DBHelper.TABLE_NAME, allColumns, "_id ="+id, null, null, null, null);
cursor.moveToFirst();
barang = cursorToBarang(cursor);
cursor.close();
return barang;
}
public void updateBarang(Barang b)
{
String strFilter = "_id=" + b.getId();
ContentValues args = new ContentValues();
args.put(DBHelper.COLUMN_NAME, b.getNama_barang());
args.put(DBHelper.COLUMN_MERK, b.getMerk_barang());
args.put(DBHelper.COLUMN_HARGA, b.getHarga_barang() );
database.update(DBHelper.TABLE_NAME, args, strFilter, null);
}
public void deleteBarang(long id)
{
String strFilter = "_id=" + id;
database.delete(DBHelper.TABLE_NAME, strFilter, null);
}
}
MasterBarang.java
public class MasterBarang extends ListFragment implements OnItemLongClickListener {
private DBDataSource dataSource;
private ImageButton bTambah;
private ArrayList<Barang> values;
private Button editButton;
private Button delButton;
private AlertDialog.Builder alertDialogBuilder;
public MasterBarang(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_masterbarang, container, false);
bTambah = (ImageButton) rootView.findViewById(R.id.button_tambah);
bTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateData.class);
startActivity(intent);
getActivity().finish();
}
});
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnItemLongClickListener(this);
return rootView;
}
public void OnCreate(Bundle savedInstanceStat){
dataSource = new DBDataSource(getActivity());
dataSource.open();
values = dataSource.getAllBarang();
ArrayAdapter<Barang> adapter = new ArrayAdapter<Barang>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
final Barang b = (Barang) getListAdapter().getItem(pos);
alertDialogBuilder.setTitle("Peringatan");
alertDialogBuilder
.setMessage("Pilih Aksi")
.setCancelable(false)
.setPositiveButton("Ubah",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
switchToEdit(b.getId());
dialog.dismiss();
}
})
.setNegativeButton("Hapus",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dataSource.deleteBarang(b.getId());
dialog.dismiss();
getActivity().finish();
startActivity(getActivity().getIntent());
}
}).create().show();
return false;
}
public void switchToEdit(long id)
{
Barang b = dataSource.getBarang(id);
Intent i = new Intent(getActivity(), EditData.class);
Bundle bun = new Bundle();
bun.putLong("id", b.getId());
bun.putString("nama", b.getNama_barang());
bun.putString("merk", b.getMerk_barang());
bun.putString("harga", b.getHarga_barang());
i.putExtras(bun);
finale();
startActivity(i);
}
public void finale()
{
MasterBarang.this.getActivity().finish();
dataSource.close();
}
#Override
public void onResume() {
dataSource.open();
super.onResume();
}
#Override
public void onPause() {
dataSource.close();
super.onPause();
}
}
in simple not displayed
Here is the example code.
First create a layout for one list row.
example : list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
>
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/merk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/harga"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/merk"
android:layout_marginTop="5dp"/>
</RelativeLayout>
After creating this list_row.xml layout, create a adapter class.
create CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<Barang> barangList;
public CustomListAdapter(Activity activity, ArrayList<Barang> barangList) {
this.activity = activity;
this.barangList = barangList;
}
/*
get count of the barangList
*/
#Override
public int getCount() {
return barangList.size();
}
#Override
public Object getItem(int location) {
return barangList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
/*
inflate the items in the list view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row, null);
}
/*
creating objects to access the views
*/
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView merk = (TextView) convertView.findViewById(R.id.merk);
TextView harga = (TextView) convertView.findViewById(R.id.harga);
// getting barang data for the row
Barang barang = barangList.get(position);
name.setText(barang.getNama_barang());
merk.setText(barang.getMerk_barang());
harga.setText(barang.getHarga_barang());
return convertView;
}}
Now in your MasterBarang.java, put the following code in your onCreate method.
values = dataSource.getAllBarang();
CustomListAdapter adapter;
adapter = new CustomListAdapter(getActivity(), values);
setListAdapter(adapter);
Now run the application.. Cheers !
You are using simple list templete as a list view. But in case of custom list view, you should create your custom list model and "BaseAdapter" for the custom list model.
Below links will help you to make custom list view in easier way.
https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
The problem is you are closing your database in onPause() method, so the reference of the database will get destroyed. Then, you again trying to open the database in onResume() method. So here the null pointer exception occurs.
Solution:
change your onResume() method like this.
#Override
public void onResume() {
dataSource = new DBDataSource(getActivity());
dataSource.open();
super.onResume();
}
Now check it and if you got any error please post it here,.
After a long time I figured out that changing argument from 0 to different number allows me to update row with corresponding id to this number:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
In above code I changed 0 to 2 and I was able to update content of row no 2. Here is full class code:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
Now, what do I need to do in order to tell it that I want to update row that is clicked, not row number 2? Any help would be appreciated.
Here is MyDB code:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the Adapter:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Implement getItemId(int position) in your adapter. In your onListItemClick method, call this method with the given position.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long itemId = adapter.getItemId(position);
saveItToDB(itemId);
}
private void saveItToDB(long itemId) {
String text = editText.getText().toString();
editText.setText("");
dba.open();
dba.updateDiaryEntry(text, itemId);
dba.close();
}