ListView and Custom Adapter - android

With putDate method in main, I have a method called updateStudentDate in dbManager class that get id and date, and when I click on save button the ids that i got from database and current date is sent to updateStudentDate.
but error occur.
This is main activity.
public class StartAttendance extends AppCompatActivity implements View.OnClickListener{
private DBManager dbManager;
private List<UserModel> students;
private String studentSubjectId;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_attendance);
final Button save = (Button) findViewById(R.id.save);
final Button cancel = (Button) findViewById(R.id.cancel);
final ListView listOfTakeAtt = (ListView) findViewById(R.id.listOfTakingAttendance);
Intent intent = getIntent();
studentSubjectId = intent.getStringExtra("studentSubjectId");
dbManager = new DBManager(StartAttendance.this);
dbManager.open();
ArrayList arrayList2 = dbManager.getAllStudentsName(Integer.valueOf(studentSubjectId));//Get the names from database.
students = new ArrayList<>();
setData(arrayList2);
final CustomLayoutOfTakingAttendance adapter = new CustomLayoutOfTakingAttendance(this, students);
listOfTakeAtt.setAdapter(adapter);
listOfTakeAtt.setDividerHeight(17);
cancel.setOnClickListener(this);
save.setOnClickListener(this);
listOfTakeAtt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
UserModel model = students.get(i);
int y=model.isSelected?1:0;
model.setSelected(true);
students.set(i, model);
if(y==1){
model.setSelected(false);
}
adapter.updateRecords(students);
}
});
}
public void setData(ArrayList arrayList2){
for(int i=0;i<arrayList2.size();i++){
students.add(new UserModel(false, (String) arrayList2.get(i)));
}
}
#Override
public void onClick(View v){
switch (v.getId()){
//When save button is clicked i want to see present radioButton is checked or not for each item.
//if checked save current date into database for this id.
case R.id.save:
putDate();
break;
case R.id.cancel:
Intent i=new Intent(StartAttendance.this,ContentOfEachSubject.class);
i.putExtra("studentSubjectId",studentSubjectId);
startActivity(i);
break;
}
}
public void putDate(){
SimpleDateFormat DateFormat=new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
Date d=new Date();
String date=DateFormat.format(d);
boolean isUpdated=false;
UserModel model;
ArrayList arrayList1 = dbManager.getAllStudentsId(Integer.valueOf(studentSubjectId));//Get the ids from the database.
for(int i=0;i<students.size();i++)
{
model = students.get(i);
if(model.isSelected){
dbManager = new DBManager(StartAttendance.this);
dbManager.open();
isUpdated = dbManager.UpdateStudentDate((Integer) arrayList1.get(i), date);
}
}
if(isUpdated){Toast.makeText(StartAttendance.this,"You took attendance successfully..",Toast.LENGTH_SHORT);}
else {Toast.makeText(StartAttendance.this,"Fail while getting attendance!!",Toast.LENGTH_SHORT);}
}
}
UserModel class
public class UserModel {
boolean isSelected;
String name;
public UserModel(boolean isSelected,String name) {
this.isSelected = isSelected;
this.name=name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public String getStudentName() {
return name;
}
public void setStudentName(String name) {
this.name = name;
}
}
dbManager class
public boolean UpdateStudentDate(int id,String date){
ContentValues cv=new ContentValues();
cv.put(DatabaseHelper.KEY_STUDENT_DATE,date);
long result=database.update(DatabaseHelper.STUDENT_TABLE,cv,DatabaseHelper.KEY_STUDENT_ID+" = "+id,null);
databaseHelper.close();
if(result==-1){return false;}
else return true;
}

You have an error in implementation of getAllStudentsId(int id) method.
If your IDs are suppose to be of type Integer, I'd suggest you to change signature of method to return not ArrayList, but ArrayList<Integer>. It would be even better to return some generic type of list, such as List<Integer> is.
However, the main issue is, that within this method you are adding to collection String instances, instead of Integers.
arrayList.add(cursor.getString(cursor.getColumnIndex(Databas‌​eHelper.KEY_STUDENT_‌​ID)));
I don't know how data are persisted in DB, whether your IDs are numeric or varchar format, but I guess it should be enough to change cursor.getString(...) to cursor.getInt(...)
Then, implementation of this method could be like
public List<Integer> getAllStudentsId(int id){
List<Integer> result =new ArrayList<>();
String[] columns = new String[]{DatabaseHelper.KEY_STUDENT_ID};
Cursor cursor = database.query(DatabaseHelper.STUDENT_TABLE, columns, D‌​atabaseHelper.KEY_ST‌​UDENT_SUBJECT_ID + " = " + id, null, null,null,null);
while(cursor.moveToNext()){
result.add(cursor.getInt(cursor.getColumnIndex(Databas‌​eHelper.KEY_STUDENT_‌​ID)));
}
return result;
}
Also, don't forget to change type of your list within StartAttendance.java class.
List<Integer> arrayList1 = dbManager.getAllStudentsId(Integer.valueOf(studentSubjectId));//Get the ids from the database.

Related

What is wrong with my Sqlite To Listview that it is not displaying desired results [duplicate]

This question already has an answer here:
Android List item displaying package name and # instead of string value
(1 answer)
Closed 1 year ago.
I'm trying to get all ID and IncomeCategoryName from DB and put them into a listview.
The problem is that Package Name. ClassName#hexcode is displayed instead of ID and IncomeCategory Name.
Class File
public class IncomeCategoriesClass {
private Integer CATEGORY_ID;
private String CATEGORY_NAME;
public IncomeCategoriesClass(Integer CATEGORY_ID, String CATEGORY_NAME) {
this.CATEGORY_ID = CATEGORY_ID;
this.CATEGORY_NAME = CATEGORY_NAME;
}
public IncomeCategoriesClass() {
this.CATEGORY_NAME = CATEGORY_NAME;
}
public Integer getCATEGORY_ID() {
return CATEGORY_ID;
}
public void setCATEGORY_ID(Integer CATEGORY_ID) {
this.CATEGORY_ID = CATEGORY_ID;
}
public String getCATEGORY_NAME() {
return CATEGORY_NAME;
}
public void setCATEGORY_NAME(String CATEGORY_NAME) {
this.CATEGORY_NAME = CATEGORY_NAME;
}
}
Database helper snippet
public List get_AllIncomeCategories(){
List AllIncomeCategories = new LinkedList<>();
String queryString = "Select * FROM " + INCOME_CATEGORIES_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString,null);
IncomeCategoriesClass incomeCategoriesClass;
if(cursor.moveToFirst()){
do {
incomeCategoriesClass = new IncomeCategoriesClass();
incomeCategoriesClass.setCATEGORY_ID(Integer.parseInt(cursor.getString(0)));
incomeCategoriesClass.setCATEGORY_NAME(cursor.getString(1));
AllIncomeCategories.add(incomeCategoriesClass);
}while (cursor.moveToNext());
}
cursor.close();
db.close();
return AllIncomeCategories;
}
AddEditincomeCategoriesActivity
public class AddEditIncomeCategoriesActivity extends AppCompatActivity {
//Define Screen Fields And Variables
ListView listviewAllIncomeCategories;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_income_categories);
//Initialize Screen Field Variables
btn_ViewAllIncomeCategory = findViewById(R.id.btn_ViewAllIncomeCategory);
listviewAllIncomeCategories = findViewById(R.id.listviewAllIncomeCategories);
//View All Income Categories on Button Click
btn_ViewAllIncomeCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(AddEditIncomeCategoriesActivity.this);
List<IncomeCategoriesClass> AllIncomeCategories;
AllIncomeCategories = dataBaseHelper.get_AllIncomeCategories();
ArrayAdapter adapter = new ArrayAdapter(AddEditIncomeCategoriesActivity.this,android.R.layout.simple_list_item_1,AllIncomeCategories);
listviewAllIncomeCategories.setAdapter(adapter);
}
});
//Add Income Category on Button Click
}
}
It is outputing data but not the data I am looking for, it is Packagename.Class#HexCode instead of 1 Cash, 2 Credit Cards, etc.
What am I doing wrong and how can I do this properly?
Simple ArrayAdapter can only inflate flat values like strings or integers. For a list of objects, You need a Custom Adapter to render your views.
See ListView Android for the implementation details.
You're seeing the output of Object#toString().
You can override toString() in your IncomeCategoriesClass to produce the string output you'd like to be displayed for that item.

Get all the data from one row in sqlitedatabase with the name_column and store it in listview

I have coded a RecyclerView where I search for data from my SQLiteDatabase with the SearchAdapter. The MaterialSearchBar (PlaceHolder) only shows the names of the data from the Database. Now I want to select one item, which i choose in the searchbar and get all the other columns of that one row and store the data in a listview in another activity.
So my first question is, how can i get all data from one row, if i only have the name? Should I do it with a cursor?
And my second question is, how should i store all the data from that one row in a listview in another activity?
Thank you for your help!
enter cclass SearchViewHolder extends RecyclerView.ViewHolder{
public TextView medid,name,menge,art,nummer;
public SearchViewHolder(View itemView) {
super(itemView);
medid = (TextView) itemView.findViewById(R.id.medid);
name = (TextView) itemView.findViewById(R.id.name);
menge = (TextView) itemView.findViewById(R.id.menge);
art = (TextView) itemView.findViewById(R.id.art);
nummer = (TextView) itemView.findViewById(R.id.nummer);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Drugs> drugs;
public SearchAdapter(Context context, List<Drugs> drugs) {
this.context = context;
this.drugs = drugs;
}
public SearchAdapter() {
}
#Override
public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater =LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.medikamentensuche,parent,false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(SearchViewHolder holder, int position) {
//String pharmaId,name,menge,art,preis,code,bezeichnung;
holder.medid.setText(toString().valueOf(drugs.get(position).getMedID()));
holder.name.setText(drugs.get(position).getName());
holder.menge.setText(drugs.get(position).getMenge());
holder.art.setText(drugs.get(position).getArt());
holder.nummer.setText(drugs.get(position).getNummer());
}
#Override
public int getItemCount() {
return drugs.size();
}
}
DataBaseOpenhelper class
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DB_NAME = "medikamente.db";
private static final String TABLE = "Medikamente";
private static final int DB_VER = 1;
public static final String ID = "MedID";
public static final String NAME = "Handelsname";
public static final String MENGE = "Mengenangabe";
public static final String ART = "Mengenart";
public static final String NUMMER = "Pharmanummer";
public DatabaseOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);
}
//neues Medikament hinzufügen
public boolean insertNewEntry (String name, String mengenangabe, String mengenart, String pharmanummer) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME,name);
values.put(MENGE,mengenangabe);
values.put(ART,mengenart);
values.put(NUMMER,pharmanummer);
long result = db.insert("Medikamente",null,values);
if (result == -1)
return false;
else
return true;
}
public List<Drugs> getDrug() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
Log.d("in der DrugDatabases", "SQLiteQueryBuilder successful");
//Kathi habe hier: "ATCCode", "BezeichnungATCCode" gelöscht
String [] sqlSelect = {"MedID", "Handelsname", "Mengenangabe", "Mengenart", "Pharmanummer"};
String tableName = "Medikamente";
Log.d("in der DrugDatabases", " successful" + sqlSelect);
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, null, null, null, null, null);
List<Drugs> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
Drugs drug = new Drugs();
drug.setMedID(cursor.getInt(cursor.getColumnIndex("MedID")));
drug.setName(cursor.getString(cursor.getColumnIndex("Handelsname")));
drug.setMenge(cursor.getString(cursor.getColumnIndex("Mengenangabe")));
drug.setArt(cursor.getString(cursor.getColumnIndex("Mengenart")));
drug.setNummer(cursor.getString(cursor.getColumnIndex("Pharmanummer")));
result.add(drug);
}while (cursor.moveToNext());
}return result;
}
public List<String> getNames() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"Handelsname" };
String tableName = "Medikamente";
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, null, null, null, null, null);
List<String> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
result.add(cursor.getString(cursor.getColumnIndex("Handelsname" )));
}while (cursor.moveToNext());
}return result;
}
public List<Drugs> getDrugsByName(String name) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"MedID" ,"Handelsname" ,"Mengenangabe" ,"Mengenart" ,"Pharmanummer"};
String tableName = "Medikamente";
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, "Handelsname LIKE ?",new String[]{"%"+name+"%"}, null, null, null);
List<Drugs> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
Drugs drug = new Drugs();
drug.setMedID(cursor.getInt(cursor.getColumnIndex("MedID")));
drug.setName(cursor.getString(cursor.getColumnIndex("Handelsname")));
drug.setMenge(cursor.getString(cursor.getColumnIndex("Mengenangabe")));
drug.setArt(cursor.getString(cursor.getColumnIndex("Mengenart")));
drug.setNummer(cursor.getString(cursor.getColumnIndex("Pharmanummer")));
result.add(drug);
}while (cursor.moveToNext());
}return result;
}
}
MedSucheActivity
public class MedSucheActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
TextView textView;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
DatabaseOpenHelper database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medsuchen);
Button button = (Button) findViewById(R.id.hinzufügen);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MedTableActivity.class);
TextView suche = (TextView) findViewById(R.id.SuchMedikament);
intent.putExtra("weitergabe",suche.getText().toString());
startActivityForResult(intent,1);
//wichtig wenn man Daten zurück geben will von der 2.Activity
}
});
textView = (TextView) findViewById(R.id.SuchMedikament);
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar) findViewById(R.id.search_bar);
//textView = (TextView) findViewById(R.id.versuch);
//Datenbank
database = new DatabaseOpenHelper(this);
//Searchbar
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for(String search:suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled)
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//init Adapter default set all result
adapter = new SearchAdapter(this,database.getDrug());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getDrugsByName(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getNames();
materialSearchBar.setLastSuggestions(suggestList);
}
public void onHinzuClick(View v) {
Log.d("msg","Auf Hinzufügen Button geklickt");
Intent intent = new Intent (getBaseContext(),MedikamentHinzufugenActivity.class);
startActivity(intent);
}
}
So my first question is, how can i get all data from one row, if i
only have the name?
And my second question is, how should i store all the data from that
one row in a listview in another activity?
If name is definitely going to be unique, which it appears that it may not be, then you can use that in conjunction with the getDrugsByName method to obtain a list of Drug objects (1 if the name is unique). So name is all that would be required and this can be passed to another activity via an Intent Extra and thus retrieved from that Intent Extra, you can then use the getDrugsbyName method in that activity to then get all the data for the row (for 2.). Of course you could also pass all values via Intent Extras.
If name isn't necessarily unique then you could use MedId (column ID) (assuming that it's the PRIMARY KEY of the table and thus unique) instead of the name. You would probably have a method getDrugById in the DatabaseHelper class along the lines of (for 2.) :-
public Drugs getDrugById(long id) {
SQLiteDatabase db = getReadableDatabase();
Drugs rv = new Drugs();
rv.setMedID(-1); // set so that drug not found can be determined
String whereclause = ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setMedID(id);
rv.setName(csr.getString(csr.getColumnIndex(NAME)));
rv.setMenge(csr.getString(csr.getColumnIndex(MENGE)));
rv.setArt(csr.getString(csr.getColumnIndex(ART)));
rv.setNummer(csr.getString(csr.getColumnIndex(NUMMER)));
}
csr.close();
return rv;
}
Notes
The returned value should be checked for the MedID being -1, this indicating that there is no such row that matches the passed id.
Rather than risking mistyping names the CONSTANTS defined in the class have been used (you may wish to adopt this throughout).
Cursors should ALWAYS be closed when done with, otherwise an exception can occur.
The above assumes that the ID column is the PRIMARY KEY and that it is an alias of the rowid column. That is you have ID INTEGER PRIMARY KEY or ID INTEGER,..other columns.., PRIMARY KEY (ID)
The above assumes the correct usage of the ID column i.e. that it is treated as a long not an int (int is ok as long as the rows are limited, however SQLite allows rowid's as high as 9223372036854775807, which cannot be handled by an int).
This is the usual method, as using an alias of rowid will likely be the most efficient.

Click on ListView item not opening new Activity

I have a ListView "resultList", but clicking on an item is not opening the new (detailed) Activity. What's my mistake?
Thank you!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.resultList = (ListView) findViewById(R.id.resultList) ;
this.dataSource = MyExpenseOpenHandler.getInstance(this).readAllExpenses();
this.adapter = new ExpenseOverviewAdapter(this, dataSource);
this.resultList.setAdapter(adapter);
this.resultList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, final int i, final long l) {
Object element = adapterView.getAdapter().getItem(i);
if (element instanceof Expense) {
Expense expense = (Expense) element;
Intent intent = new Intent(MainActivity.this, ExpenseDetailActivity.class);
intent.putExtra(ExpenseDetailActivity.EXPENSE_KEY, expense);
startActivity(intent);
}
Log.e("Click on List: ", element.toString());
}
});
}
Your code seems alright .I think the problem is that your if condition may be returning false and the code inside the if statement is not being executed.You can put a log message inside the if statement to check if the code is being executed.
if (element instanceof Expense) {
Log.d(YOUR_LOG_TAG,"The if condition not executed")
Expense expense = (Expense) element;
Intent intent = new Intent(MainActivity.this, ExpenseDetailActivity.class);
intent.putExtra(ExpenseDetailActivity.EXPENSE_KEY, expense);
startActivity(intent);
}
If you see the log message in your android monitor you can be sure that the code inside your if condition is not executed and hence your activity is not starting.
Did you implement Parcelable on your class Expense ?
Something like this
public class Expense implements Parcelable{
private String id;
private String name;
private String grade;
// Constructor
public Expense(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getter and setter methods
.........
.........
// Parcelling part
public Expense(Parcel in){
String[] data = new String[3];
in.readStringArray(data);
// the order needs to be the same as in writeToParcel() method
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
#Оverride
public int describeContents(){
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.name,
this.grade});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Expense createFromParcel(Parcel in) {
return new Expense(in);
}
public Expense[] newArray(int size) {
return new Expense[size];
}
};
}
what kind of view in the list, if the child view get the focus like button may lead to item click not work well.
you can try to add android:descendantFocusability="beforeDescendants" in you listview.

Android SQLite database doesnot Update and Delete

This is mainactivity which provides the user Input
public class Welcome extends AppCompatActivity{
private DBMANAGER_person dbmanager_person;
private ListView listView;
private SimpleCursorAdapter adapter;
final String [] from = new String[]{MyDB.COLUMN_ID, MyDB.COLUMN_NAME, MyDB.COLUMN_AGE, MyDB.COLUMN_HEIGHT , MyDB.COLUMN_WEIGHT};
final int [] to = new int[]{R.id.nameTV,R.id.ageTV,R.id.heightTV,R.id.weightTV};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
dbmanager_person = new DBMANAGER_person(this);
dbmanager_person.open();
Cursor cursor = dbmanager_person.fetch();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.emptyTV));
adapter = new SimpleCursorAdapter(this, R.layout.person, cursor, from, to,0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView idTextView = (TextView)view.findViewById(R.id.idTV);
TextView nameTextView = (TextView) view.findViewById(R.id.nameTV);
TextView ageTextView = (TextView) view.findViewById(R.id.ageTV);
TextView heightTextView = (TextView) view.findViewById(R.id.heightTV);
TextView weightTextView = (TextView) view.findViewById(R.id.weightTV);
String iD = idTextView.getText().toString();
String name = nameTextView.getText().toString();
String age = ageTextView.getText().toString();
String height = heightTextView.getText().toString();
String weight = weightTextView.getText().toString();
Intent intent = new Intent(getApplicationContext(), Modiffy_person_Details.class);
intent.putExtra("_id",iD);
intent.putExtra("name", name);
intent.putExtra("age", age);
intent.putExtra("height", height);
intent.putExtra("weight", weight);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.add_person,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.add){
Intent intent = new Intent(this,Add_people.class);
startActivity(intent);
}else if (id == R.id.logout){
Intent backToHome = new Intent(this,MainActivity.class);
startActivity(backToHome);
}
return super.onOptionsItemSelected(item);
}
}
This is Add_prople class
public class Add_people extends AppCompatActivity implements View.OnClickListener {
private EditText nameEditText;
private EditText ageEditText;
private EditText heightEditText;
private EditText weightEditText;
private Button save;
private DBMANAGER_person dbmanager_person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Add People");
setContentView(R.layout.activity_add_people);
nameEditText = (EditText)findViewById(R.id.nameET);
ageEditText = (EditText)findViewById(R.id.ageET);
heightEditText = (EditText)findViewById(R.id.heightET);
weightEditText = (EditText)findViewById(R.id.weightET);
save = (Button)findViewById(R.id.saveBtn);
dbmanager_person = new DBMANAGER_person(this);
dbmanager_person.open();
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.saveBtn:
final String name = nameEditText.getText().toString();
final String age = ageEditText.getText().toString();
final String height = heightEditText.getText().toString();
final String weight = weightEditText.getText().toString();
dbmanager_person.insert(name,age,height,weight);
Intent main = new Intent(this,Welcome.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
break;
}
}
}
This is DBMANAGER_person class where the CRUD operation works
This is the Modiffy_person_Details class where user can Update and Delete their information
public class DBMANAGER_person {
private SQLiteDatabase database;
private MyDB myDB;
private Context context;
public DBMANAGER_person(Context context) {
this.context = context;
}
public DBMANAGER_person open() throws SQLiteException{
myDB = new MyDB(context);
database = myDB.getWritableDatabase();
return this;
}
public void close(){
myDB.close();
}
public void insert(String name,String age,String height,String weight){
ContentValues contentValues = new ContentValues();
contentValues.put(MyDB.COLUMN_NAME,name);
contentValues.put(MyDB.COLUMN_AGE,age);
contentValues.put(MyDB.COLUMN_HEIGHT,height);
contentValues.put(MyDB.COLUMN_WEIGHT,weight);
database.insert(MyDB.TABLE_NAME,null,contentValues);
}
public Cursor fetch(){
String[] columns = new String[]{MyDB.COLUMN_ID, MyDB.COLUMN_NAME, MyDB.COLUMN_AGE , MyDB.COLUMN_HEIGHT, MyDB.COLUMN_WEIGHT};
Cursor cursor = database.rawQuery( "select rowid _id,* from "+MyDB.TABLE_NAME, null);
cursor.moveToFirst();
return cursor;
}
public int update(long id, String name, String age, String height, String weight){
ContentValues contentValues = new ContentValues();
contentValues.put(MyDB.COLUMN_NAME,name);
contentValues.put(MyDB.COLUMN_AGE,age);
contentValues.put(MyDB.COLUMN_HEIGHT,height);
contentValues.put(MyDB.COLUMN_WEIGHT,weight);
int i = database.update(MyDB.TABLE_NAME,contentValues,MyDB.COLUMN_ID + " = "+id,null);
return i;
}
public void delete(long id){
database.delete(MyDB.TABLE_NAME, MyDB.COLUMN_ID + "="+ id,null);
}
}
public class Modiffy_person_Details extends AppCompatActivity implements View.OnClickListener{
private EditText nameField;
private EditText ageField;
private EditText heightField;
private EditText weightField;
private Button update;
private Button delete;
private long _id;
private DBMANAGER_person dbmanager_person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Modify Record");
setContentView(R.layout.activity_modiffy_person__details);
dbmanager_person = new DBMANAGER_person(this);
dbmanager_person.open();
nameField = (EditText)findViewById(R.id.nameEditText);
ageField = (EditText)findViewById(R.id.ageEditText);
heightField = (EditText)findViewById(R.id.heightEditText);
weightField = (EditText)findViewById(R.id.weightEditText);
update = (Button)findViewById(R.id.update_btn);
delete = (Button)findViewById(R.id.delete_btn);
Intent intent = getIntent();
String ID = intent.getStringExtra("_id");
String name = intent.getStringExtra("name");
String age = intent.getStringExtra("age");
String height = intent.getStringExtra("height");
String weight = intent.getStringExtra("weight");
String check_ID = ID;
if(!check_ID.equals("")) {
_id = Long.parseLong(ID);
}/*else{
Toast.makeText(getApplicationContext(),"There is no id",Toast.LENGTH_LONG).show();
}*/
nameField.setText(name);
ageField.setText(age);
heightField.setText(height);
weightField.setText(weight);
update.setOnClickListener(this);
delete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.update_btn:
String na = nameField.getText().toString();
String ag = ageField.getText().toString();
String hei = heightField.getText().toString();
String wei = weightField.getText().toString();
dbmanager_person.update( _id , na , ag,hei,wei);
this.returnHome();
break;
case R.id.delete_btn:
dbmanager_person.delete(_id);
this.returnHome();
break;
}
}
public void returnHome(){
Intent home_intent = new Intent(getApplicationContext(),Welcome.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
My problem is whenever i want to update or delete my information it does not work.
Check the returned values for both delete and update. For both functions, it returns 0 for no rows affected, or it returns 1 if there are rows are affected. If it's 0, then your issue is dealing with the SQL query itself, in which case the first thing to check would be the validity of the IDs.
update
delete

Update an object passed through Parcelable intent

I'm new to Android and i'm still learning. I currently have a ListView which allows you to click on an item. Clicking on an item will open a new intent displaying extra information about the item.
The thing i'm tripping up on is figuring out how to get the updated values back into my custom object and update the values in array at the correct index.
For example:
I'll add an item and set it's quantity to 2. This will appear in my ListView. Great. I decide i need 3 instead of 2, so i click the item to open the new activity, see 2 sitting in quantity, update it to 3 and hit save. On the save click i want to go back to my listview and have the updated quantity value displaying there and also updated in the array at the index.
Code for segments:
Onclick method for the listview in ItemList class
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
bean = (CustomObject) listview.getItemAtPosition(arg2);
Intent in1 = new Intent(Itemlist.this, SingleItem.class);
in1.putExtra("ActivityObject", bean);
startActivity(in1);
}
});
Adding an item the array in my ItemList class. this contain the listview.
else {
objects.add(new CustomObject(roomname.getText().toString() + " - " + resultSet.get(namecount), resultSet.get(partno), itemq, "$" + resultSet.get(rrpcol), resultSet.get(glcode), resultSet.get(desc)));
adapter.notifyDataSetChanged();
SingleItem class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleitem);
siname = (TextView) findViewById(R.id.siname);
sipartno = (TextView) findViewById(R.id.sipartno);
siquantity = (EditText) findViewById(R.id.siq);
sirrp = (EditText) findViewById(R.id.sirrp);
siglcode = (TextView) findViewById(R.id.siglcode);
sidesc = (EditText) findViewById(R.id.sidesc);
update = (Button) findViewById(R.id.siupdate);
Bundle b = getIntent().getExtras();
CustomObject itemInfo = b.getParcelable("ActivityObject");
siname.setText(itemInfo.getItemName());
sipartno.setText(itemInfo.getItemPartNo());
siquantity.setText(itemInfo.getItemQuantity());
sirrp.setText(itemInfo.getItemPrice());
siglcode.setText(itemInfo.getItemGLCode());
sidesc.setText(itemInfo.getItemDesc());
}
Custom Object class
public class CustomObject implements Parcelable {
private String itemName;
private String itemPartNo;
private String itemQuantity;
private String itemPrice;
private String itemGLCode;
private String itemDesc;
public CustomObject(Parcel source){
/*
* Reconstruct from the Parcel
*/
//Log.v(TAG, "ParcelData(Parcel source): time to put back parcel data");
//id = source.readInt();
itemName = source.readString();
itemPartNo = source.readString();
itemQuantity = source.readString();
itemPrice = source.readString();
itemGLCode = source.readString();
itemDesc = source.readString();
}
public CustomObject(String prop1, String prop2, String prop3, String prop4, String prop5, String prop6) {
this.itemName = prop1;
this.itemPartNo = prop2;
this.itemQuantity = prop3;
this.itemPrice = prop4;
this.itemGLCode = prop5;
this.itemDesc = prop6;
}
public String getItemName() {
return itemName;
}
public String getItemPartNo() { return itemPartNo; }
public String getItemQuantity() {
return itemQuantity;
}
public String getItemPrice() {
return itemPrice;
}
public String getItemGLCode() {return itemGLCode;}
public String getItemDesc() {return itemDesc;}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(itemName);
dest.writeString(itemPartNo);
dest.writeString(itemQuantity);
dest.writeString(itemPrice);
dest.writeString(itemGLCode);
dest.writeString(itemDesc);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public CustomObject createFromParcel(Parcel in) {
return new CustomObject(in);
}
public CustomObject[] newArray(int size) {
return new CustomObject[size];
}
};
}
I want to be able to change the quantity in the SingleItem class, click the Update button, and then have it load up the itemlist class with the updated values in the item list.
It'd be more efficient to use Fragments with your own callback interfaces defined for the activity. But, if you want to go the Activity approach, use startActivityForResult() and have your detail Activity send back a result Intent with any updates object contents.

Categories

Resources