first time posting here, long time lurker. I am developing an Android app using an SQLite Database to persist data. The first view I have is a ListView where the user can add, change or delete Animal names. They can also hit an Edit Button, which brings them to a second view. This view has more details about the same animal, such as DOB and Comments, with the name and id transferred over from the first view.
The problem I am running into is I cannot figure out how to get the current animal's DOB and Comments to display in their respective EditTexts from the database. I have a save button at the bottom of this view that should save whatever info they put into these fields already, but then going back into this view needs to display whatever they have entered. My code for the two views and my DBHelper class is below. Thanks!
Here are images of what the two views look like.
ListView Primary View
Detail View
The MainActivity that contains the first view and the ListView:
public class MainActivity extends AppCompatActivity
{
public final static String ID_EXTRA = "com.example.josh.boergoats._ID";
public final static String NAME_EXTRA = "com.example.josh.boergoats.name";
private DBHelper dbHelper = null;
private Cursor cursor = null;
private DBAdapter adapter = null;
EditText editAnimal = null;
String animalId = null;
long idAnimal = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
editAnimal = (EditText) findViewById(R.id.animalEditText);
dbHelper = new DBHelper(this);
cursor = dbHelper.getAll();
startManagingCursor(cursor);
adapter = new DBAdapter(cursor);
listView.setAdapter(adapter);
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(onSave);
Button deleteButton = (Button) findViewById(R.id.deleteButton);
deleteButton.setOnClickListener(onDelete);
Button editButton = (Button) findViewById(R.id.editButton);
editButton.setOnClickListener(onEdit);
listView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
dbHelper.close();
}
private View.OnClickListener onSave = new View.OnClickListener()
{
public void onClick(View v)
{
Button addButton = (Button) findViewById(R.id.addButton);
if (animalId == null)
{
dbHelper.insert(editAnimal.getText().toString());
}
else
{
dbHelper.update(animalId, editAnimal.getText().toString());
animalId = null;
}
cursor.requery();
editAnimal.setText("");
addButton.setText("Add Animal");
}
};
private View.OnClickListener onDelete = new View.OnClickListener()
{
public void onClick(View v)
{
if (animalId == null)
{
return;
}
else
{
dbHelper.delete(animalId);
animalId = null;
}
cursor.requery();
editAnimal.setText("");
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setText("Add Animal");
}
};
private View.OnClickListener onEdit = new View.OnClickListener()
{
public void onClick(View v)
{
Button editButton = (Button) findViewById(R.id.editButton);
editButton.setVisibility(View.INVISIBLE);
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setText("Add Animal");
Intent i = new Intent(MainActivity.this, DetailActivity.class);
//i.putExtra(ID_EXTRA, String.valueOf(id));
i.putExtra(NAME_EXTRA, String.valueOf(editAnimal.getText().toString()));
i.putExtra(ID_EXTRA, String.valueOf(idAnimal));
editAnimal.setText("");
startActivity(i);
}
};
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
animalId = String.valueOf(id);
Cursor c = dbHelper.getById(animalId);
c.moveToFirst();
editAnimal.setText(dbHelper.getAnimal(c));
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setText("Update");
Button editButton = (Button) findViewById(R.id.editButton);
editButton.setVisibility(View.VISIBLE);
idAnimal = id;
}
};
public class DBAdapter extends CursorAdapter
{
DBAdapter(Cursor c)
{
super(MainActivity.this, c);
}
#Override
public void bindView(View view, Context context, Cursor c)
{
DBHolder holder = (DBHolder) view.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
DBHolder holder = new DBHolder(row);
row.setTag(holder);
return(row);
}
}
static class DBHolder
{
private TextView name = null;
DBHolder(View row)
{
name = (TextView) row.findViewById(R.id.nameTextView);
}
void populateFrom(Cursor c, DBHelper helper)
{
//name.setText(r.getName(c));
name.setText(helper.getAnimal(c));
}
}
}
The second activity, DetailActivity, where I am having the problem.
public class DetailActivity extends AppCompatActivity
{
private DBHelper dbHelper = null;
//private Cursor cursor = null;
String passedName = null;
String passedID = null;
private EditText passedIdView = null;
private EditText passedNameView = null;
private EditText dobView = null;
private EditText commentsView = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//dbHelper = new DBHelper(this);
//cursor = dbHelper.getAllInfo();
passedName = getIntent().getStringExtra(MainActivity.NAME_EXTRA);
passedNameView = (EditText) findViewById(R.id.nameDetailEditText);
passedNameView.setText(passedName);
passedID = getIntent().getStringExtra(MainActivity.ID_EXTRA);
passedIdView = (EditText) findViewById(R.id.idDetailEditText);
passedIdView.setText(passedID);
dobView = (EditText) findViewById(R.id.dobDetailEditText);
commentsView = (EditText) findViewById(R.id.commentsDetailEditText);
Button saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(onSave);
}
private View.OnClickListener onSave = new View.OnClickListener()
{
public void onClick(View v)
{
String id = passedID;
passedID = getIntent().getStringExtra(MainActivity.ID_EXTRA);
if (passedNameView.getText().toString() != null)
{
if (passedID != null)
{
dbHelper.update(id, passedNameView.getText().toString());
}
}
if (dobView.getText().toString() != null)
{
dbHelper.updateDob(id, dobView.getText().toString());
}
if (commentsView.getText().toString() != null)
{
dbHelper.updateComments(id, commentsView.getText().toString());
}
//reset all edittext fields to blank before leaving
passedIdView.setText("");
passedNameView.setText("");
dobView.setText("");
commentsView.setText("");
Intent i = new Intent(DetailActivity.this, MainActivity.class);
startActivity(i);
}
};
}
The Database Helper class, where the database is created and manipulated. Note that not all of the methods are being used, a few of them are from my experimenting.
public class DBHelper extends SQLiteOpenHelper
{
private static final String dbPath = "/data/data/com.example.josh.boergoats/";
private static final String dbName = "animals.db";
private static final int schemaVersion = 1;
public DBHelper(Context context)
{
super(context, dbName, null, schemaVersion);
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE Animals (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, dob TEXT, comments TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
public void insert(String animal)
{
ContentValues cv = new ContentValues();
cv.put("name", animal);
getWritableDatabase().insert("Animals", "name", cv);
}
public void update(String id, String animal)
{
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("name", animal);
getWritableDatabase().update("Animals", cv, "_id=?", args);
}
public void updateDob(String id, String dob)
{
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("dob", dob);
getWritableDatabase().update("Animals", cv, "_id=?", args);
}
public void updateComments(String id, String comment)
{
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("comments", comment);
getWritableDatabase().update("Animals", cv, "_id=?", args);
}
public void delete(String id)
{
getWritableDatabase().delete("Animals", "_id=?", new String[] {id});
}
public Cursor getAll()
{
return(getReadableDatabase().rawQuery("SELECT _id, name FROM Animals", null));
}
public Cursor getAllInfo()
{
return(getReadableDatabase().rawQuery("SELECT _id, name, dob, comments FROM Animals", null));
}
public String getAnimal(Cursor c)
{
return(c.getString(1));
}
public String getDob(Cursor c)
{
return(c.getString(2));
}
public String getComments(Cursor c)
{
return(c.getString(3));
}
public Cursor getById(String id)
{
String[] args = {id};
return(getReadableDatabase().rawQuery("SELECT _id, name FROM Animals WHERE _id=?", args));
}
}
Thank you again in advance.
What I do, to use the same activity to add or edit (which I believe is what you're trying to do), is to pass, via an Intent Extra, the respective option and then have the code set the respective values. here's an example :-
String caller = getIntent().getStringExtra("Caller");
if(getIntent().getStringExtra("Caller").equals("ShopListByCursorActivityUpdate")) {
((EditText) findViewById(R.id.ase_storename_input)).setText(getIntent().getStringExtra("ShopName"));
((EditText) findViewById(R.id.ase_storeorder_input)).setText(getIntent().getStringExtra("ShopOrder"));
((EditText) findViewById(R.id.ase_storestreet_input)).setText(getIntent().getStringExtra("ShopStreet"));
((EditText) findViewById(R.id.ase_storecity_input)).setText(getIntent().getStringExtra("ShopCity"));
((EditText) findViewById(R.id.ase_storestate_input)).setText(getIntent().getStringExtra("ShopState"));
((EditText) findViewById(R.id.ase_storephone_input)).setText(getIntent().getStringExtra("ShopPhone"));
((EditText) findViewById(R.id.ase_storenotes_input)).setText(getIntent().getStringExtra("ShopNotes"));
setTitle(getResources().getString(R.string.title_activity_shop_edit));
}
The 2nd Line checks for the Update mode (ie what is in the Intent Extra named Caller (extracted into caller)) and then sets the respective values which themselves are in Intent Extras. 1st line isn't needed I just had it there for debugging purposes.
Note the when called by Edit as opposed to Add then the Intent Extra Caller is set to ShopListByCursorActivityUpdate when adding is is set to ShopListByCursorActivity.
PS You may have issues in the first activity not displaying the changed/saved data as it doesn't appear that you refresh the data. In brief, if this is an issue. You need to rebuild the cursor (ie redo the query) and then get the adapter to use the new/amended cursor via changeCursor, SwapCursor or notifyDataSetChanged. eg :-
Cursor csr = shopperdb.getShopsAsCursor();
currentsca.swapCursor(csr);
In regards to comment
You are on the right track, but I was actually having trouble putting the information that I needed into the Intent Extra. Since I don't have the DOB or comments field on my first activity, I need to pull that information from my database and put it into the Intent Extra somehow. Those 2 fields are created in my DBHelper class. Also, depending on how they can be pulled from the database, they may not even need to be put in the Intent Extra if they can be put straight into my EditTexts.
Then Use SELECT * FROM Animals to get all columns in getAll then all columns will be available in the returned Cursor.
Related
So just to describe the app im building, there are 3 buttons on the home screen, "Data Input", "Info Display" and "Exit". When user clicks "Data Input", they get to fill in some EditText boxes with info and also UPLOAD AN IMAGE from gallery. Once they click a "Save" button on the page, all data entered will be sent to a ListView widget in the "Info Display" screen. However my problem now is that I have managed to get the EditText values to the list view throught the use of Sqlite, but i currently have no clue on how to get the image which was uploaded from the gallery to the ListView widget
These are the working codes I have(only missing the image part)
TouristHelper
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class TouristHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "assignment.db";
private static final int SCHEMA_VERSION = 1;
public TouristHelper(Context context){
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
//will be called once when the database 1s not created
db.execSQL("CREATE TABLE tourist_table ( _id INTEGER PRIMARY KEY AUTOINCREMENT," +
" Vactivity TEXT, Vdate TEXT, Vdescription TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//Will not be called until SCHEMA_VERSION increases
// Here we can upgrade the database e.g. add more tables
}
/*Read all records from restaurants_Table */
public Cursor getAll() {
return (getReadableDatabase().rawQuery(
"SELECT _id, Vactivity, Vdate, Vdescription " +
"FROM tourist_table ORDER BY Vactivity", null));
}
public Cursor getById(String id) {
String[] args = {id};
return (getReadableDatabase().rawQuery(
"SELECT _id, Vactivity, Vdate, Vdescription" +
" FROM tourist_table WHERE _ID = ?", args));
}
public void insert (String Vactivity, String Vdate,
String Vdescription) {
ContentValues cv = new ContentValues();
cv.put("Vactivity", Vactivity);
cv.put("Vdate", Vdate);
cv.put("Vdescription", Vdescription);
getWritableDatabase().insert("tourist_table", "Vactivity", cv);
}
public void update(String id, String Vactivity, String Vdate,
String Vdescription) {
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("Vactivity", Vactivity);
cv.put("Vdate", Vdate);
cv.put("Vdescription", Vdescription);
getWritableDatabase().update("tourist_table", cv, "_ID = ?", args);
}
public String getID(Cursor c) { return (c.getString(0)); }
public String getActivity(Cursor c){
return (c.getString(1));
}
public String getDate(Cursor c){
return (c.getString(2));
}
public String getDescription(Cursor c){
return (c.getString(3));
}
}
InfoDisplay
public class InfoDisplay extends AppCompatActivity {
private Cursor model = null;
private VietnamAdapter adapter = null;
private ListView list;
private TouristHelper helper = null;
private TextView empty = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_display);
empty = findViewById(R.id.empty);
helper = new TouristHelper(this);
list = findViewById(R.id.listview);
model = helper.getAll();
adapter = new VietnamAdapter(this, model, 0);
list.setOnItemClickListener(onListClick);
list.setAdapter(adapter);
}
#Override
protected void onResume() {
super.onResume();
if (model != null) {
model.close();
}
model = helper.getAll();
if (model.getCount() > 0) {
empty.setVisibility(View.INVISIBLE);
}
adapter.swapCursor(model);
}
#Override
protected void onDestroy() {
helper.close();
super.onDestroy();
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
model.moveToPosition(position);
String recordID = helper.getID(model);
Intent intent;
intent = new Intent(InfoDisplay.this, DataIn.class);
intent.putExtra("ID", recordID);
startActivity(intent);
}
};
static class DataHolder {
private TextView VietACTI = null;
private TextView VietDATE = null;
private TextView VietDES = null;
DataHolder(View row) {
VietACTI = row.findViewById(R.id.VAct);
VietDATE = row.findViewById(R.id.VDate);
VietDES = row.findViewById(R.id.VDes);
}
void populateFrom(Cursor c, TouristHelper helper) {
VietACTI.setText(helper.getActivity(c));
VietDATE.setText(helper.getDate(c));
VietDES.setText(helper.getDescription(c));
}
}
class VietnamAdapter extends CursorAdapter {
VietnamAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
DataHolder holder = (DataHolder) view.getTag();
holder.populateFrom(cursor, helper);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
DataHolder holder = new DataHolder(row);
row.setTag(holder);
return (row);
}
}
}
DataIn
public class DataIn extends AppCompatActivity {
private EditText Vactivity;
private EditText Vdate;
private EditText Vdescription;
private Button buttonSave;
private Button buttonImg;
ImageView imageView;
private Bitmap imageToStore;
private static int RESULT_LOAD_IMAGE = 1;
private TouristHelper helper = null;
private String touristID = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_input);
Vactivity = findViewById(R.id.activity);
Vdate = findViewById(R.id.date);
Vdescription = findViewById(R.id.description);
buttonSave = findViewById(R.id.button_save);
buttonSave.setOnClickListener(onSave);
buttonImg = findViewById(R.id.imginput);
buttonImg.setOnClickListener(onImg);
imageView = findViewById(R.id.imgView);
helper = new TouristHelper(this);
touristID = getIntent().getStringExtra("ID");
if (touristID != null) {
load();
}
/*list = findViewById(R.id.Data);
adapter = new DataAdapter();
list.setAdapter(adapter);*/
}
#Override
protected void onDestroy() {
super.onDestroy();
helper.close();
}
private void load() {
Cursor c = helper.getById(touristID);
c.moveToFirst();
Vactivity.setText(helper.getActivity(c));
Vdate.setText(helper.getDate(c));
Vdescription.setText(helper.getDescription(c));
}
View.OnClickListener onImg = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
/*Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE*/);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "pick an image"), RESULT_LOAD_IMAGE);
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
/*String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();*/
// String picturePath contains the path of selected Image
imageView.setImageURI(selectedImage);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
}
}
private View.OnClickListener onSave = new View.OnClickListener(){
#Override
public void onClick(View v){
//read data from restaurantName EditText
String nameStr = Vactivity.getText().toString();
String dateStr = Vdate.getText().toString();
String desStr = Vdescription.getText().toString();
if (touristID == null) {
helper.insert(nameStr, dateStr, desStr);
}
else {
helper.update(touristID, nameStr, dateStr, desStr);
}
// To clase current Activity class and exit
finish();
}
};
}
At this point you have two options:
Save the image in the private storage of your app and save on the DB the URI to this image so you can load it later.
Having the Bitmap with the image get the ByteArray of the image and save it directly to the DB.
I prefer the first option, but the second one could do the job too, hope it helps you.
All i tried is to pass the listview selected items id to the next activity and show the id in a TextView on another page. I receive a number format exception when i click on list item. Any suggestions please.
DataBaseWrapper is the class where database is created.
DishOperation
public class DishOperation {
// Database fields
private DataBaseWrapper dbHelper;
private String[] DISHES_TABLE_COLUMNS = { DataBaseWrapper.DISHES_ID, DataBaseWrapper.DISHES_NAME,DataBaseWrapper.DISHES_INGREDIENTS };
private SQLiteDatabase database;
public DishOperation(Context context) {
dbHelper = new DataBaseWrapper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public Dish addDishes(String name,String ingredients) {
ContentValues values = new ContentValues();
values.put(DataBaseWrapper.DISHES_NAME, name);
values.put(DataBaseWrapper.DISHES_INGREDIENTS, ingredients);
long dishId = database.insert(DataBaseWrapper.DISHES, null, values);
// now that the student is created return it ...
Cursor cursor = database.query(DataBaseWrapper.DISHES,
DISHES_TABLE_COLUMNS, DataBaseWrapper.DISHES_ID + " = "
+ dishId, null, null, null, null);
cursor.moveToFirst();
Dish newComment = parseDishes(cursor);
cursor.close();
return newComment;
}
public void deleteDishes(Dish comment) {
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(DataBaseWrapper.DISHES, DataBaseWrapper.DISHES_ID + " = " + id, null);
}
public List getAllDishes() {
List dishes = new ArrayList();
Cursor cursor = database.query(DataBaseWrapper.DISHES,
DISHES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Dish dish = parseDishes(cursor);
dishes.add(dish);
cursor.moveToNext();
}
cursor.close();
return dishes;
}
public String getInformation(Dish i)
{
long id=i.getId();
String ing= i.getIngredients();
return ing;
}
private Dish parseDishes(Cursor cursor) {
Dish dish = new Dish();
dish .setId((cursor.getInt(0)));
dish .setName(cursor.getString(1));
dish .setIngredients(cursor.getString(2));
return dish ;
}
}
Activity 1
public void onCreate(Bundle savedInstanceState) {
Button btListe;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dishDBoperation = new DishOperation(this);
dishDBoperation.open();
final List values = dishDBoperation.getAllDishes();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("key",id);
startActivity(intent);
}
});
Activity 2
int value;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView text = (TextView) findViewById(R.id.editText3);
Bundle extras = getIntent().getExtras();
if (extras != null) {
long value = extras.getLong("key");
text.setText(String.valueOf(value));// updated!!
}
}
Change
value =Integer.parseInt( extras.getString("key"));
with
long value = extras.getLong("key");
also in your Activity2 you should move
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
in the very beginning of onCreate otherwise your findViewById will return null.
Edit.
Accordingly to the code you posted you have an ArrayAdapter of Dish. Your dataset and your ArrayAdapter should reflect it, and this can be done with Generics.
To get the id of your row as argument of onItemClick, you have to override getItemId. E.g.
setListAdapter(new ArrayAdapter<Dish>(this, android.R.layout.simple_list_item_1, values ) {
#Override
public long getItemId(int position) {
return getItem(position).getId();
}
}));
You should use value = extras.getLong("key"));
In Activity 1, id is of type long and in Activity 2, you try to retrieve it as a String.
Retrieve it by extras.getLong("key");
I am trying to get a list of names with total amounts from a sqlite db.
It is working in a way that shows a list of all the transactions with the
correct combined total. I also have a table in the same db that has usernames
& phone numbers, but I don't think that would be too useful for this activity.
Also, how do I use the onListItemClick to send the next activity something
that I can use to pull only names from the User the person selected? The ID
is being sent, but I don't know how to use it.
ie:
trans table:
Justin 25
Justin 25
Justin 25
Sophia 80
Hoped results:
Justin 75
Sophia 80
Actual results:
Justin 75
Justin 75
Justin 75
Sophia 80
ListActivity that populates the list (with cursor and TextView link)
public class Totals extends ListActivity {
PaymentHelper helper;
Cursor model = null;
PaymentAdapter adapter = null;
UserHelper uhelp;
Cursor umodel = null;
public final static String ID_EXTRA = "com.curtis.bookkeeping._ID";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_person);
helper = new PaymentHelper(this);
model = helper.getAll();
startManagingCursor(model);
adapter = new PaymentAdapter(model);
setListAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i = new Intent(Totals.this, Detail.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public class PaymentAdapter extends CursorAdapter {
PaymentAdapter(Cursor c) {
super(Totals.this, c, FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public void bindView(View row, Context context, Cursor c) {
PaymentHolder holder = (PaymentHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.person_row, parent, false);
PaymentHolder holder = new PaymentHolder(row);
row.setTag(holder);
return row;
}
}
static class PaymentHolder {
private TextView name_line = null;
private TextView amount_line = null;
PaymentHolder(View row) {
name_line = (TextView)row.findViewById(R.id.name_row);
amount_line = (TextView)row.findViewById(R.id.amount_row);
}
void populateFrom(Cursor c, PaymentHelper helper) {
name_line.setText(helper.getName(c));
amount_line.setText(Integer.toString(helper.sumPerson(c, helper.getName(c))));
}
}
}
SQLiteOpenHelper code to retrieve info
public class PaymentHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "bookkeeping.db";
private static final int SCHEMA_VERSION = 1;
SQLiteDatabase db;
public PaymentHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db1) {
db = db1;
String sql = "CREATE TABLE IF NOT EXISTS trans (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, date TEXT, amount INT, note TEXT)";
//execute the sql statement
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String name, String date, int amount, String note){
Log.e(name, date + " " + amount);
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("date", date);
cv.put("amount", amount);
cv.put("note", note);
Log.e("Almost", "there");
db.insert("trans", "abc", cv);
Log.e("successfully", "inserted");
}
public Cursor getAll(){
String sql = "SELECT * FROM trans ORDER BY name";
Cursor cursor = getReadableDatabase().rawQuery(sql, null);
return cursor;
}
public Cursor getAllNames(){
String sql = "SELECT * FROM users";
Cursor cursor = getReadableDatabase().rawQuery(sql, null);
return cursor;
}
public String getName(Cursor c){
return c.getString(c.getColumnIndex("name"));
}
public String getDate(Cursor c){
return c.getString(c.getColumnIndex("date"));
}
public int getAmount(Cursor c){
return c.getInt(c.getColumnIndex("amount"));
}
public String getNote(Cursor c){
return c.getString(c.getColumnIndex("note"));
}
public void delete(String id){
String[] args = {id};
getWritableDatabase().delete("trans", "_id=?", args);
}
public Cursor getById(String id){
String[] args = {id};
String sql = "SELECT * FROM trans WHERE _id=?";
Cursor cursor = getReadableDatabase().rawQuery(sql, args);
return cursor;
}
public void update(String id, String name, String date, int amount, String note){
String[] args = {id};
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("date", date);
cv.put("amount", amount);
cv.put("note", note);
getWritableDatabase().update("trans", cv, "_ID=?", args);
}
public int sumPerson(Cursor c, String name){
int total = 0;
// add up totals
String sql = "SELECT amount FROM trans WHERE name=?";
String[] aname = new String[]{name};
getReadableDatabase().rawQuery(sql,aname);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(name.equals(getName(c))){
total += c.getInt(c.getColumnIndex("amount"));
}
}
return total;
}
}
This is the activity that is receiving the ID from Totals:
I would like it to show only one user (which they selected
from the totals page) with all of their transactions.
public class Detail extends ListActivity {
PaymentHelper helper;
Cursor model = null;
PaymentAdapter adapter = null;
public final static String ID_EXTRA = "com.curtis.bookkeeping._ID";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
helper = new PaymentHelper(this);
model = helper.getAll();
startManagingCursor(model);
adapter = new PaymentAdapter(model);
setListAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.details_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.totals:
startActivity(new Intent(this, Totals.class));
break;
case R.id.users:
startActivity(new Intent(this, Users.class));
break;
case R.id.home:
startActivity(new Intent(this, MainMenu.class));
break;
}
return true;
}
#Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i = new Intent(Detail.this, DeletePayment.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public class PaymentAdapter extends CursorAdapter {
PaymentAdapter(Cursor c) {
super(Detail.this, c, FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public void bindView(View row, Context context, Cursor c) {
PaymentHolder holder = (PaymentHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
PaymentHolder holder = new PaymentHolder(row);
row.setTag(holder);
return row;
}
}
static class PaymentHolder {
private TextView name_line = null;
private TextView date_line = null;
private TextView amount_line = null;
private TextView note_line = null;
PaymentHolder(View row) {
name_line = (TextView)row.findViewById(R.id.name_line);
amount_line = (TextView)row.findViewById(R.id.amount_line);
date_line = (TextView)row.findViewById(R.id.date_line);
note_line = (TextView)row.findViewById(R.id.note_line);
}
void populateFrom(Cursor c, PaymentHelper helper) {
Log.e(helper.getName(c), Integer.toString(helper.getAmount(c)));
name_line.setText(helper.getName(c));
date_line.setText(helper.getDate(c));
amount_line.setText(Integer.toString(helper.getAmount(c)));
note_line.setText(helper.getNote(c));
}
}
}
I know this is long...but help would be awesome!
I feel like the "PaymentAdapter" needs to be modified to only
read two names if there is only two names. Should I be utilizing
the "UserHelper" db helper to populate this? but when I do, it only
runs one cursor through, and gets a nullpointerexception error because
it is not moving one of the cursors. Should I be making a PaymentAdapter
within PaymentAdapter to generate use of another cursor?
The following SQL query will give you the desired result:
SELECT name, SUM(amount)
FROM trans
GROUP BY name
I'm trying to display a selected item in a listview, populated with SQLite in another activity, but when i make the rawQuery, using the _id row identifier to show it the item in the other activity, but does not send any results, leads me to the other activity, but did not shows anything in the xml layout, i don't know if i'm doing correctly my declaration of rawQuery, this is my search code and my handler to show it:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.course_details);
courseId = getIntent().getIntExtra("COURSE_ID", 0);
SQLiteDatabase db = (new DBHelper(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT emp._id, emp.title, emp.instructor, emp.length, emp.rating, emp.topic, emp.subject, emp.description, mgr._id managerId, mgr.title managerTitle FROM courses emp LEFT OUTER JOIN courses mgr ON emp.title = mgr._id WHERE emp._id = ?",
new String[]{""+courseId});
if (cursor.getCount() == 1)
{
cursor.moveToFirst();
tTitle = (TextView) findViewById(R.id.tTitle);
tTitle.setText(cursor.getString(cursor.getColumnIndex("title")));
tInstructor = (TextView) findViewById(R.id.tInstructor);
tInstructor.setText(cursor.getString(cursor.getColumnIndex("instructor")));
tLength = (TextView) findViewById(R.id.tLength);
tLength.setText(cursor.getString(cursor.getColumnIndex("length")));
tRating = (TextView) findViewById(R.id.tRating);
tRating.setText(cursor.getString(cursor.getColumnIndex("rating")));
tTopic = (TextView) findViewById(R.id.tTopic);
tTopic.setText(cursor.getString(cursor.getColumnIndex("topic")));
tSubject = (TextView) findViewById(R.id.tSubject);
tSubject.setText(cursor.getString(cursor.getColumnIndex("subject")));
tDescription = (TextView) findViewById(R.id.tDescription);
tDescription.setText(cursor.getString(cursor.getColumnIndex("description")));
}
db.close();
cursor.close();
return;
}}
this is the class that shows the listview and performs the Intent:
public class lay_main extends ListActivity {
public ListView list;
public DBHelper myAdap;
protected SQLiteDatabase db;
public Cursor cursor;
DBHelper Context;
DBHelper ArrayList;
//adapter cAdapter class
protected ListAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
collectXML();
setupDataBase();
setupAdapter();
}
private void collectXML()
{
list = (ListView)findViewById(android.R.id.list);
}
public void setupDataBase() {
myAdap = new DBHelper(getApplicationContext());
myAdap.insertCourses();
}
public void setupAdapter()
{
if(myAdap.getCourses()!=null)
{
adapter = new cAdapter(this, R.layout.list_courses, myAdap.getCourses());
list.setAdapter(adapter);
}
}
public void onListItemClick(ListView parent, View view, int position, long id)
{
super.onListItemClick(parent, view, position, id);
Intent intent = new Intent(this, CourseDetails.class);
Courses course = (Courses) adapter.getItem(position);
intent.putExtra("COURSE_ID", course.title);
startActivity(intent);
}}
really would appreciate your help.
You can send your data over an bundle:
Bundle sendBundle = new Bundle();
sendBundle.putString("COURSE_ID", course.title); //or use putInt if course.title is int type
//sendBundle.putInt("COURSE_ID", course.title);
Intent i = new Intent(lay_main.this, CourseDetails.class);
i.putExtra("testBundle", sendBundle);
startActivity(i);
and recieve it like:
Bundle receiveBundle = this.getIntent().getBundleExtra("testBundle");
if (receiveBundle != null){
String courseId = receiveBundle.getString("COURSE_ID");
//or int courseId = receiveBundle.getInt("COURSE_ID");
}
I've one listView with multiple choice and checkbox.
I get the values from listview executing a query in sqlite3.
When i click a button, I need to insert the selected items in another table but i don't know how can i do it.
Before doing insert i'm trying to know if it works showing one console log (Log.v). in this code there is not insert statement.
Any suggestions? Thanks in advance and sorry about my english,
Alex.
I paste the code:
public class productos extends Activity {
SQLiteDatabase db;
Spinner prodSpinner;
ArrayAdapter<String> prodAdapter;
Spinner catSpinner;
ArrayAdapter<String> catAdapter;
Cursor catCursor;
Cursor prodCursor;
String Value2;
String valor2;
SparseBooleanArray sp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productos);
Bundle extras = getIntent().getExtras();
//final String Value = extras.getSerializable("Lista").toString();
//final String Value2 = extras.getSerializable("Super").toString();
Button CatText2 = (Button) findViewById(R.id.textCategoria);
CatText2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.v("valor4:", "AAAAA");
recCatSpinner();
}
});
Button btSelecciona = (Button) findViewById(R.id.btSelecciona);
btSelecciona.setOnClickListener(new OnClickListener() {
public void onClick (View arg0) {
Toast.makeText(getBaseContext(),"AAAA",Toast.LENGTH_SHORT).show();
}
});
Button btComanda = (Button) findViewById(R.id.btComanda);
btComanda.setOnClickListener(new OnClickListener() {
public void onClick (View arg0) {
EscriuComanda();
}
private void EscriuComanda() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
int count = 0;
//
sp = new SparseBooleanArray();
//SparseBooleanArray sp=prodSpinner.getCheckedItemPositions();
sp.clear();
sp = prodSpinner.getCheckedItemPositions();
for(int i = 0; i < sp.size(); i++)
{
if ( sp.valueAt(i)==true)
{
Log.v("400", "SI: " + valor2);
}
else
{
Log.v("500", "No: " + valor2);
}
}
}
});
//Toast.makeText(getBaseContext(),Value2,Toast.LENGTH_SHORT).show();
recCatSpinner();
}
public class UsuariosSQLiteHelper extends SQLiteOpenHelper {
public UsuariosSQLiteHelper(Context contexto, String nombre,
CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
public void onCreate(SQLiteDatabase db) {
Log.v("OnClickV", "1");
}
public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva) {
Log.v("OnClickV", "1");
}
}
public Cursor recuperaCategoria()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "Categorias";
String[] columns = {"_id","Nombre"};
return db.query(tableName, columns, null, null, null, null, null);
}
public Cursor recuperaProductos()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "ArtSuperV";
String[] columns = {"_id","NombreA"};
String where = "NombreC='" + valor2 + "'";
return db.query(tableName, columns, where, null, null, null, null);
}
public void recCatSpinner() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
catCursor = recuperaCategoria();
catCursor.moveToPosition(1);
catAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); //.simple_list_item_multiple_choice);// .simple_spinner_item);
catAdapter.setDropDownViewResource (android.R.layout.simple_list_item_multiple_choice); //.simple_spinner_dropdown_item);
prodSpinner.setAdapter(catAdapter);
if (catCursor.moveToFirst()) {
do {
catAdapter.add(catCursor.getString(1));
}
while (catCursor.moveToNext());
if (db != null) {
Toast.makeText(getBaseContext(),catCursor.getString(1),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(catCursor);
catCursor.close();
prodSpinner.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view2, int pos, long id) {
valor2 = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(),valor2,Toast.LENGTH_SHORT).show();
Log.v("valor2:", valor2);
recProdSpinner();
}
});
}
public void recProdSpinner() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
prodCursor = recuperaProductos();
prodCursor.moveToPosition(1);
prodAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice); //.simple_list_item_multiple_choice);// .simple_spinner_item);
prodSpinner.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
prodAdapter.setDropDownViewResource (android.R.layout.simple_list_item_multiple_choice); //.simple_spinner_dropdown_item);
prodSpinner.setAdapter(prodAdapter);
if (prodCursor.moveToFirst()) {
do {
prodAdapter.add(prodCursor.getString(1));
}
while (prodCursor.moveToNext());
if (db != null) {
Toast.makeText(getBaseContext(),prodCursor.getString(1),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(prodCursor);
prodCursor.close();
prodSpinner.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view2, int pos, long id) {
valor2 = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(),valor2,Toast.LENGTH_SHORT).show();
Log.v("valor2:", valor2);
}
});
}
}
Cant figure out some of the code flow due to language issue.But scheme should be:1. Set the adapters for both the lists (even if the lists are empty on launch, set the adapter with the empty but initialised array lists and make the array list as the global variables of the class so that they can be accessed from anywhere in the activity.) 2. Now select the items from the list1 and get their index in the first list.3. Add those items in the second array list. 4. Call the "notifyDataSetChanged()" for the adapter of the second list view.Link to know about proper use of "notifyDataSetChanged()" are notifyDataSetChanged example