How to view data in database on fragment [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to view data in database on fragment and I use TableRow to view data.
my code Setting database :
public class SqliteManager extends Activity {
public static final int VERSI_DATABASE= 1;
public static final String NAMA_DATABASE = "dbCrudSqlite";
public static final String NAMA_TABEL = "tbAgenda";
public static final String FIELD_ID = "_id";
public static final int POSISI_ID = 0;
public static final String FIELD_JUDUL = "judul";
public static final int POSISI_JUDUL = 1;
public static final String FIELD_DESKRIPSI = "deskripsi";
public static final int POSISI_DESKRIPSI = 2;
public static final String FIELD_WAKTU = "waktu";
public static final int POSISI_WAKTU = 3;
public static final String[] FIELD_TABEL ={ SqliteManager.FIELD_ID, SqliteManager.FIELD_JUDUL, SqliteManager.FIELD_DESKRIPSI, SqliteManager.FIELD_WAKTU };
private Context crudContext;
private SQLiteDatabase crudDatabase;
private SqliteManagerHelper crudHelper;
private static class SqliteManagerHelper extends SQLiteOpenHelper {
private static final String BUAT_TABEL =
"create table " + NAMA_TABEL + " (" +
SqliteManager.FIELD_ID + " integer primary key autoincrement, " +
SqliteManager.FIELD_JUDUL + " text not null, " +
SqliteManager.FIELD_DESKRIPSI + " text not null," +
SqliteManager.FIELD_WAKTU + " text not null " +
");";
public SqliteManagerHelper(Context context) {
super(context, NAMA_DATABASE, null, VERSI_DATABASE);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(BUAT_TABEL);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
public void generateData(SQLiteDatabase database){
ContentValues cv=new ContentValues();
cv.put(FIELD_ID, "3");
cv.put(FIELD_JUDUL, "Abang");
cv.put(FIELD_DESKRIPSI, "Abang");
cv.put(FIELD_WAKTU, "Merah");
database.insert(NAMA_TABEL,null,cv);
cv.put(FIELD_ID, "2");
cv.put(FIELD_JUDUL, "Opo");
cv.put(FIELD_DESKRIPSI, "Opo");
cv.put(FIELD_WAKTU, "Apa");
database.insert(NAMA_TABEL,null,cv);
}
public SqliteManager(Context context) {
crudContext = context;
}
public void bukaKoneksi() throws SQLException {
crudHelper = new SqliteManagerHelper(crudContext);
crudDatabase = crudHelper.getWritableDatabase();
generateData(crudDatabase);
}
public void tutupKoneksi() {
crudHelper.close();
crudHelper = null;
crudDatabase = null;
}
public long insertData(ContentValues values) {
return crudDatabase.insert(NAMA_TABEL, null, values);
}
public boolean updateData(long rowId, ContentValues values) {
return crudDatabase.update(NAMA_TABEL, values,
SqliteManager.FIELD_ID + "=" + rowId, null) > 0;
}
public boolean hapusData(long rowId) {
return crudDatabase.delete(NAMA_TABEL,
SqliteManager.FIELD_ID + "=" + rowId, null) > 0;
}
public Cursor bacaData() {
return crudDatabase.query(NAMA_TABEL,FIELD_TABEL,null, null, null, null,SqliteManager.FIELD_JUDUL + " DESC");
}
public Cursor bacaDataTerseleksi(long rowId) throws SQLException {
Cursor cursor = crudDatabase.query(true, NAMA_TABEL,FIELD_TABEL,FIELD_ID + "=" + rowId,null, null, null, null, null);
cursor.moveToFirst();
return cursor;
}
public ContentValues ambilData(String tempat, String lat, String lng) {
ContentValues values = new ContentValues();
values.put(SqliteManager.FIELD_JUDUL, tempat);
values.put(SqliteManager.FIELD_DESKRIPSI, lat);
values.put(SqliteManager.FIELD_WAKTU, lng);
return values;
}
public ArrayList<ArrayList<Object>> ambilSemuaBaris(){
ArrayList<ArrayList<Object>> dataArray = new ArrayList<ArrayList<Object>>();
Cursor cur;
try
{
cur = crudDatabase.query(NAMA_TABEL, new String[]{FIELD_ID,FIELD_JUDUL,FIELD_DESKRIPSI}, null, null, null, null, null);
cur.moveToFirst();
if (!cur.isAfterLast())
{
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cur.getLong(0));
dataList.add(cur.getString(1));
dataList.add(cur.getString(2));
dataArray.add(dataList);
}while (cur.moveToNext());
}
}catch (Exception e)
{
e.printStackTrace();
Log.e("DB ERROR",e.toString());
}
return dataArray;
}
}
I want to view data on fragment:
public class JawaIndo extends Fragment {
private SqliteManager sqliteDB;
private Activity activity;
TextView bhsjawa,bhsindo;
Button addBtn;
TableLayout tabel4data;
public JawaIndo(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.jawaindo, container, false);
sqliteDB = new SqliteManager(getActivity());
sqliteDB.bukaKoneksi();
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
return rootView;
}
protected void updateTable() {
while (tabel4data.getChildCount()>1){
tabel4data.removeViewAt(1);
}
ArrayList<ArrayList<Object>> data = sqliteDB.ambilSemuaBaris();
for (int posisi = 0; posisi < data.size(); posisi++) {
TableRow tabelBaris = new TableRow(getActivity());
ArrayList<Object> baris = data.get(posisi);
TextView idTxt = new TextView(getActivity());
idTxt.setText(baris.get(0).toString());
tabelBaris.addView(idTxt);
TextView namaTxt = new TextView(getActivity());
namaTxt.setText(baris.get(1).toString());
tabelBaris.addView(namaTxt);
TextView hobiTxt = new TextView(getActivity());
hobiTxt.setText(baris.get(2).toString());
tabelBaris.addView(hobiTxt);
tabel4data.addView(tabelBaris);
}
}
}
Error when I write this code on class JawaIndo :
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();

You have just change some in your onCreateView() method:
And it should be
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.jawaindo, container, false);
sqliteDB = new SqliteManager(getActivity());
sqliteDB.bukaKoneksi();
//activity = new Activity();
// Update Here
tabel4data = (TableLayout) rootView .findViewById(R.id.tabel_data);
bhsjawa = (TextView) rootView .findViewById(R.id.nama_id);
bhsindo = (TextView) rootView .findViewById(R.id.hobi_id);
updateTable();
return rootView;
}
In this passed your View's object named rootView as referenced to find the id of your UI element.

Didn't read all the code, just the snippet you highlighted and the logcat and even there spotted multiple problems:
The constraint failed comes when you're trying to call generateData() from onCreateView(). When running the code again, the very same data is re-inserted, causing the constraint failed failure.
Then, in here:
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
You should never instantiate activities with new. Now all those findViewById()s will return null and get you a NullPointerException later on in updateTable().

You can not get reference of your from your activity instance. It will always get from the View only. The View class is responsible to initialize and find the views in your screen. So always find your views by layout only.
Here is your code:
activity = new Activity();
tabel4data = (TableLayout) activity.findViewById(R.id.tabel_data);
bhsjawa = (TextView) activity.findViewById(R.id.nama_id);
bhsindo = (TextView) activity.findViewById(R.id.hobi_id);
updateTable();
Change it as below. Change your reference of activity to rootView
activity = new Activity();
tabel4data = (TableLayout) rootView .findViewById(R.id.tabel_data);
bhsjawa = (TextView) rootView .findViewById(R.id.nama_id);
bhsindo = (TextView) rootView .findViewById(R.id.hobi_id);
updateTable();

Related

IndexOutofBoundsException error while trying to populate custom listview with data from database [duplicate]

This question already has an answer here:
What is a StringIndexOutOfBoundsException? How can I fix it?
(1 answer)
Closed 4 years ago.
I am trying to retrieve data from database and populate a custom listview. However, I am getting error
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
and the app crashes and stops. Can you tell me how can i resolve this?
I want the listview to be like this.
Logcat:
FATAL EXCEPTION: main
Process: com.example.dell.remindme, PID: 28020
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at
com.example.dell.remindme.CustomAdapter.getView(CustomAdapter.java:68)
at android.widget.AbsListView.obtainView(AbsListView.java:3170)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1389)
at android.widget.ListView.onMeasure(ListView.java:1296)
at android.view.View.measure(View.java:21126)
at
android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at
android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at
android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:400)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at
android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:899)
at android.view.View.measure(View.java:21126)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2612)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1664)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1915)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1537)
at
android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:959)
at android.view.Choreographer.doCallbacks(Choreographer.java:734)
at android.view.Choreographer.doFrame(Choreographer.java:670)
at
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:945)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Dbhelper.java
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
// Database Version
private static final int DATABASE_VERSION = 5;
// Database Name
private static final String DATABASE_NAME = "RemindMe";
// Table Names
private static final String TABLE_TODO = "Todo";
private static final String TABLE_LOGIN = "Login";
// TODO Table - column names
private static final String TASK_ID = "task_id";
private static final String TASK_TITLE = "task_title";
private static final String TASK_DESCRIP = "task_descrip";
private static final String TASK_DATE = "task_date";
private static final String TASK_TIME = "task_time";
// LOGIN Table - column names
private static final String LOGIN_ID = "login_id";
private static final String EMAIL = "email";
private static final String PASSWORD = "password";
// Table Create Statements
// Todo table create statement
private static final String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_TODO + "(" + TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TASK_TITLE + " TEXT," + TASK_DESCRIP + " TEXT," + TASK_DATE + " TEXT," + TASK_TIME + " TEXT" + ")";
// Login table create statement
private static final String CREATE_TABLE_LOGIN = "CREATE TABLE " + TABLE_LOGIN + "(" + LOGIN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + EMAIL + " EMAIL," + PASSWORD + " TEXT" + ")";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_TODO);
db.execSQL(CREATE_TABLE_LOGIN);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// create new tables
onCreate(db);
}
//Todo table
//add new task
public void Add_New_Task(String task_title, String task_descrip, String task_date, String task_time){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TASK_TITLE, task_title);
values.put(TASK_DESCRIP, task_descrip);
values.put(TASK_DATE, task_date);
values.put(TASK_TIME, task_time);
// insert row
long id = db.insert(TABLE_TODO, null, values);
db.close();
Log.d(TAG, "New task added" + id);
}
//delete task
public void Delete_Task(String title){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TODO,TASK_TITLE + " = ? ",new String[] {title});
db.close();
}
}
CustomAdapter
public class CustomAdapter extends BaseAdapter {
private Context mContext;
DbHelper dbHelper;
private ArrayList<String> title = new ArrayList<String>();
private ArrayList<String> date = new ArrayList<String>();
private ArrayList<String> time = new ArrayList<String>();
public CustomAdapter(Context context,ArrayList<String> title,ArrayList<String> date, ArrayList<String> time)
{
this.mContext = context;
this.title = title;
this.date = date;
this.title = time;
}
#Override
public int getCount() {
return title.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class viewHolder {
TextView Title;
TextView Date;
TextView Time;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final viewHolder holder;
dbHelper = new DbHelper(mContext);
LayoutInflater layoutInflater;
if (convertView == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.activity_list, null);
holder = new viewHolder();
holder.Title = (TextView) convertView.findViewById(R.id.task_title);
holder.Date = (TextView) convertView.findViewById(R.id.task_date);
holder.Time = (TextView) convertView.findViewById(R.id.task_time);
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
}
holder.Title.setText(title.get(position));
holder.Date.setText(date.get(position));
holder.Time.setText(time.get(position));
return convertView;
}
}
Todolist.java
public class To_Do_List extends AppCompatActivity{
private DbHelper dbHelper;
private SQLiteDatabase db;
private ListView lstTask;
//ArrayAdapter<String> myAdapter;
private ArrayList<String> Title = new ArrayList<String>();
private ArrayList<String> Date = new ArrayList<String>();
private ArrayList<String> Time = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to__do__list);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
lstTask = (ListView)findViewById(R.id.List);
dbHelper = new DbHelper(this);
Load_List();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
//back button on actionbar
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent main_activity = new Intent(To_Do_List.this, MainActivity.class);
startActivity(main_activity);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//load activity_list of tasks
private void Load_List() {
/*ArrayList<String> taskList = dbHelper.getTaskList();
if (myAdapter == null) {
myAdapter = new ArrayAdapter<String>(this, R.layout.activity_list, R.id.task_title, taskList);
lstTask.setAdapter(myAdapter);
} else {
myAdapter.clear();
myAdapter.addAll(taskList);
myAdapter.notifyDataSetChanged();
}*/
db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT task_title, task_date, task_time FROM todo",null);
Title.clear();
Date.clear();
Time.clear();
if (cursor.moveToFirst()) {
do {
Title.add(cursor.getString(cursor.getColumnIndex("task_title")));
Date.add(cursor.getString(cursor.getColumnIndex("task_date")));
Time.add(cursor.getString(cursor.getColumnIndex("task_time")));
} while (cursor.moveToNext());
}
CustomAdapter myadapter = new CustomAdapter(To_Do_List.this,Title,Date,Time);
lstTask.setAdapter(myadapter);
//code to set adapter to populate list
cursor.close();
}
//add new task
public void Add_New_Task(View view) {
Intent intent = new Intent(To_Do_List.this, Reminder.class);
startActivity(intent);
finish();
}
//delete existing task
public void Delete_Task(View view){
View parent = (View)view.getParent();
TextView taskTextView = (TextView)parent.findViewById(R.id.task_title);
Log.e("String", (String) taskTextView.getText());
String task = String.valueOf(taskTextView.getText());
dbHelper.Delete_Task(task);
Load_List();
}
}
Your problem is explained in this line:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java:411)
You are trying to read the first element of an empty List.
Check whether there are elements before trying to read them.
You are getting
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at
that means trying to access empty list or size that not in your arraylist.
validate first list in not empty and size is greater than 0 before access.
if(list!=null && list.size()>0){
//access list
}else {
}
Hope it will help you!!
The variable "time" was queried but not updated. My bad! I fixed it and now it works. Thank you for your help guys!
You just check the length of list before getting the value from list.
if(list.size()>0){
}else {
}

How to get Sum of SQLite Column by matching id

The app: I have an app that creates multiple machines with:
id, name and location
each of these machines I have to let the user input the income respectively.
The problem: I need to SUM all income(money, date, note, machines_id) inputted from each machine AND display it in a TextView in a different Activity.
My question: How do I get the data from the rawQuery of my getIncomeOfMachine method to another Activity?
What I tried: Using Bundles, Intents, SharedPreferences from the DBHelper class.
DBHelper
public class DBHelpter extends SQLiteOpenHelper {
private static final String DB_NAME = "machines.db";
private static final int DB_VERSION = 1;
public static final String TABLE_MACHINES = "machines";
public static final String MACHINES_COLUMN_NAME = "name";
public static final String MACHINES_COLUMN_LOCATION = "location";
public static final String MACHINES_ID = "id";
public static final String TABLE_INCOME = "income";
public static final String INCOME_COLUMN_MONEY = "money";
public static final String INCOME_COLUMN_DATE = "date";
public static final String INCOME_COLUMN_NOTE = "note";
public static final String INCOME_ID = "id";
public static final String INCOME_COLUMN_MACHINES_ID = "machines_id";
private Context mContext;
public DBHelpter(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query1 = String.format("CREATE TABLE " + TABLE_MACHINES + "("
+ MACHINES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MACHINES_COLUMN_NAME + " TEXT NOT NULL, "
+ MACHINES_COLUMN_LOCATION + " TEXT NOT NULL)",
TABLE_MACHINES, MACHINES_COLUMN_NAME, MACHINES_COLUMN_LOCATION, MACHINES_ID);
String query2 = String.format("CREATE TABLE " + TABLE_INCOME + "("
+ INCOME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ INCOME_COLUMN_MONEY + " REAL NOT NULL, "
+ INCOME_COLUMN_DATE + " DATE NOT NULL, "
+ INCOME_COLUMN_NOTE + " TEXT NOT NULL, "
+ INCOME_COLUMN_MACHINES_ID + " INTEGER NOT NULL)",
TABLE_INCOME, INCOME_ID, INCOME_COLUMN_MONEY, INCOME_COLUMN_DATE, INCOME_COLUMN_NOTE, INCOME_COLUMN_MACHINES_ID);
db.execSQL(query1);
db.execSQL(query2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query1 = String.format("DROP TABLE IF EXISTS " + TABLE_MACHINES);
String query2 = String.format("DROP TABLE IF EXISTS " + TABLE_INCOME);
db.execSQL(query1);
db.execSQL(query2);
onCreate(db);
}
public void insertNewMachine(String name, String location){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MACHINES_COLUMN_NAME, name);
values.put(MACHINES_COLUMN_LOCATION, location);
db.insertWithOnConflict(TABLE_MACHINES, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
public void insertNewIncome(Double money, String date, String note, long machines_id){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(INCOME_COLUMN_MONEY, money);
values.put(INCOME_COLUMN_DATE, date);
values.put(INCOME_COLUMN_NOTE, note);
values.put(INCOME_COLUMN_MACHINES_ID, machines_id);
db.insertWithOnConflict(TABLE_INCOME, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
}
public void getIncomeOfMachine(long machinesId){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT machines_id, SUM(money) AS total FROM income WHERE machines_id = "+machinesId+"", null);
while (cursor.moveToFirst()){
String totalAmount = String.valueOf(cursor.getInt(0));
SharedPreferences mSharedPreferences = mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putString("total_amount", totalAmount);
mEditor.commit();
}
cursor.close();
db.close();
}
public ArrayList<MachinesClass> getAllMachines(){
ArrayList<MachinesClass> machinesList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_MACHINES, null);
while (cursor.moveToNext()){
final long id = cursor.getLong(cursor.getColumnIndex(MACHINES_ID));
final String name = cursor.getString(cursor.getColumnIndex(MACHINES_COLUMN_NAME));
final String location = cursor.getString(cursor.getColumnIndex(MACHINES_COLUMN_LOCATION));
machinesList.add(new MachinesClass(id, name, location));
}
cursor.close();
db.close();
return machinesList;
}
RecyclerViewAdapter
public class MachinesAdapter extends RecyclerView.Adapter<MachinesAdapter.ViewHolder> {
private ArrayList<MachinesClass> machinesList;
private LayoutInflater mInflater;
private DBHelpter mDBHelpter;
private Context mContext;
public static final String PREFS_NAME = "MyPrefsFile";
public MachinesAdapter(Context mContext, ArrayList<MachinesClass> machinesList){
this.mContext = mContext;
this.machinesList = machinesList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.machines_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.mLocation.setText(machinesList.get(position).getLocation());
holder.v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences mSharedPreferences = mContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putString("location", machinesList.get(position).getLocation());
mEditor.putLong("machines_id", machinesList.get(position).getId());
mEditor.commit();
Bundle bundle = new Bundle();
bundle.putString("location", machinesList.get(position).getLocation());
Intent intent = new Intent(v.getContext(), MachineInfo.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtras(bundle);
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return machinesList != null ? machinesList.size() : 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mLocation, mMoney;
public LinearLayout mLinearLayout;
public View v;
public ViewHolder(View v) {
super(v);
mLinearLayout = (LinearLayout) v.findViewById(R.id.linearLayout);
mLocation = (TextView) v.findViewById(R.id.tvLocation);
mMoney = (TextView) v.findViewById(R.id.tvMoney);
this.v = v;
}
}
}
MachineInfo
public class MachineInfo extends AppCompatActivity {
private TextView mLocation, mMoney, mNotes;
private DBHelpter mDBHelpter;
private FloatingActionButton mFAB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_machine_info);
mDBHelpter = new DBHelpter(getApplicationContext());
mLocation = (TextView) findViewById(R.id.tvLocation);
mMoney = (TextView) findViewById(R.id.tvMoney);
mNotes = (TextView) findViewById(R.id.tvNotes);
mFAB = (FloatingActionButton) findViewById(R.id.fabAddIncome);
SharedPreferences mSharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String total_amount = mSharedPreferences.getString("total_amount", null);
mMoney.setText(total_amount);
String location = mSharedPreferences.getString("location", null);
mLocation.setText(location);
mFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), IncomeCreation.class);
startActivity(i);
}
});
}
}
If you need any other Activity or layout, let me know!
First, I suggest a change to getIncomeOfMachine(). Since this method is in DBHelper, it should only be responsible for interacting with the database. It should not know anything about SharedPreferences or Activity. Instead, it should return the value retrieved from the database and let the caller decide what to do with that value. Since you know there is only one row in the resulting Cursor, you do not need a loop. Just move to the first row, get the total, and return it.
Second, since you are only passing a single value to an activity, and you presumably do not need to store it permanently for later use, you should use an Intent rather than SharedPreferences. Starting Another Activity has a clear example of sending a value to another activity. If you have problems using this example in your app, feel free to post a new question showing what you did and explaining the problem you encountered.

SQLite Database not displaying on ListView

Thanks in advance for helping me out. This is my first time working on SQLite Database as well as creating an app.
Problem: When I click save"ImageButton" on the AddEntry.xml for some reason its not displaying on my listview which is located in my Fragment Home.xml. I found fragments to be a tad difficult since you have to change the code around in order for it to work. so please excuse if my code is all over the place.
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener
{
EditText DescriptionET,CalorieET;
ImageButton Savebtn, Cancelbtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry,
container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
descriptionET.setText("");
EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
calorieET.setText("");
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER =
"section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private View v;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home,
container, false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain)getActivity()).loadSelection(1);
}
});
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView)
getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
listview = (ListView) getActivity().findViewById(R.id.listViewDB);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber -
FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new
SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
closeDataBase();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
// Constants & Data
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[]
{KEY_ROWID, KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Thanks again for helping me out. I've been stressing for the last couple of days trying to figure it out.

ContentProvider.createUri Cannot resolve method?

I dont know why i cant compile my code , it is setting me that ContentProvider.createUri cannot resolve method. What i am missing can anyone tell me please. Here is my code for class:
public class Connectivity extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
MySQLiteHelper db;
String[] name;
String[] username;
String[] password;
String[] category;
int[] ids;
int[] color;
ListView listView;
Cursor identityCursor;
FloatingActionButton addIndentity;
int REQUEST_CODE =0;
int color1;
ToastersAdapter customAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.cards_frag, container, false);
addIndentity = (FloatingActionButton) android.findViewById(R.id.fab3);
db = new MySQLiteHelper(getActivity());
final List<IdentityHelper> list = db.getAllIdentities();
name= new String[db.getIdentitiesCount()];
username = new String[db.getIdentitiesCount()];
password = new String[db.getIdentitiesCount()];
category = new String[db.getIdentitiesCount()];
color = new int[db.getIdentitiesCount()];
ids = new int[db.getIdentitiesCount()];
for (int i = 0; i < list.size(); i++) {
IdentityHelper n= list.get(i);
name[i]= n.getName();
username[i]=n.getUsername();
password[i]=n.getPassword();
category[i]=n.getCategory();
color[i] = n.getColor();
ids[i] = n.getId();
}
addIndentity.setOnClickListener(handler);
// Get access to the underlying writeable database
SQLiteDatabase dbs = db.getWritableDatabase();
// Query for items from the database and get a cursor back
identityCursor = dbs.rawQuery("SELECT * FROM Identities ORDER BY category", null);
listView = (ListView) android.findViewById(R.id.listView1);
customAdapter = new ToastersAdapter(getActivity(), identityCursor);
listView.setAdapter(customAdapter);
addIndentity.attachToListView(listView);
getActivity().getSupportLoaderManager().initLoader(0, null, Connectivity.this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
ToastersAdapter adapter1 = (ToastersAdapter) adapter.getAdapter();
Object sectionObject = adapter1.getItem(position);
int cursorPosition = adapter1.getCursorPositionWithoutSections(position);
if (adapter1.isSection(position) && sectionObject != null) {
// Handle the section being clicked on.
Toast.makeText(getActivity(),"Header Clicked", Toast.LENGTH_SHORT).show();
} else if (cursorPosition != SectionCursorAdapter.NO_CURSOR_POSITION) {
// Handle the cursor item being clicked on.
//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("Name", name[cursorPosition]);
bundle.putString("Username",username[cursorPosition]);
bundle.putString("Password",password[cursorPosition]);
bundle.putString("Category", category[cursorPosition]);
bundle.putInt("Color", color[cursorPosition]);
bundle.putInt("ID", ids[cursorPosition]);
Intent intent = new Intent(getActivity(), theIdentity.class);
intent.putExtras(bundle);
Connectivity.this.startActivity(intent);
getActivity().overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);
getActivity().finish();
}}
});
return android;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
**String orderBy = category[id] + " ASC, " + name[id] + " ASC";
return new CursorLoader(this, ContentProvider.createUri(IdentityHelper.class, null), null, null, null, orderBy);**
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
customAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
customAdapter.swapCursor(null);
}
I have used https://github.com/twotoasters/SectionCursorAdapter, for Cursor adapter to manipulate the ListView. I will really appreciate any help
Since there is no createUri method in android.content.ContentProvider class, it appears to me that your ContentProvider class is from some other library.
May be it is ActiveAndroid, which has createUri method in com.activeandroid.content.ContentProvider class.
I dont know why i cant compile my code , it is setting me that ContentProvider.createUri cannot resolve method
There is no method named createUri() on ContentProvider, whether static or otherwise.

Android sqllite cannot remove item by position

I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview.
Now I want to delete values by position (for example, if i click listview's 4th item i would to delete full this items)
This is my code:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
My Adapter Code:
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and my Main Java code:
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
int a;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
a = Integer.parseInt(holder.counter.getText().toString());
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
dbHelper.close();
cAdapter.notifyDataSetChanged();
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
cAdapter.notifyDataSetChanged();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
I found one example about how to delete title but it's not working.
How could I delete user by position in listview 'onclick' listener?
Any help would be great, thanks
db.delete(DATABASE_NAME, "username = ?", new String[] { userName });
You'll need to use the table name here, if all else is correct.

Categories