ArrayList<String> is not working properly in CursorAdapter - java

I am trying to get database from SQLite database and trying to populate the ListView and also adding data in ArrayList<String> . The ListView is populated nicely but problem is ArrayList<String> is not populated nicely.
Suppose I have data in database like:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
........
My ListView Showing data in this way. But ArrayList<String> add the data this way:
A
B
C
D
E
F
A
B
C
D
E
F
G
H
......
That means my ArrayList<String> takes first 6 value then repeat it and then it takes next 6 value then again repeat it ..... . That means When I click item "H" from list view the ArrayList<String> shows me "B". I don't know why it is happening?
My Code, CustomList which extends CursorAdapter
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class CustomList extends CursorAdapter {
CheckBox favoriteBox;
TextView cityName, countryName;
ArrayList<String> city_name;
ArrayList<String> country_name;
ArrayList<String> country_short;
ArrayList<CheckBox> check_box;
public CustomList(Context context, Cursor c, ArrayList<String> city_name,
ArrayList<String> country_name, ArrayList<String> country_short,
ArrayList<CheckBox> check_box) {
super(context, c, 0);
this.city_name = city_name;
this.country_name = country_name;
this.country_short = country_short;
this.check_box = check_box;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.all_city_list, parent, false);
return retView;
}
#Override
public void bindView(final View view, Context context, Cursor cursor) {
cityName = (TextView) view.findViewById(R.id.cityName);
String cityS = cursor.getString(cursor.getColumnIndex("city_name"));
cityName.setText(cityS);
city_name.add(cityS);//adding value to ArrayList<String>
countryName = (TextView) view.findViewById(R.id.countryName);
String conS = cursor.getString(cursor.getColumnIndex("country_name"));
countryName.setText(conS);
country_name.add(conS);//adding value to ArrayList<String>
country_short.add(""
+ cursor.getString(cursor.getColumnIndex("country_short")));//adding value to ArrayList<String>
favoriteBox = (CheckBox) view.findViewById(R.id.favoriteCheckBox);
check_box.add(favoriteBox);
if (cursor.getInt(cursor.getColumnIndex("favorite")) == 0) {
favoriteBox.setChecked(false);
} else {
favoriteBox.setChecked(true);
}
}
}
Class AllCityListFragment which extends Fragment
import java.io.IOException;
import java.util.ArrayList;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
public class AllCityListFragment extends Fragment {
private CustomList customAdapter;
private DatabaseHelper databaseHelper;
ArrayList<String> city_name = new ArrayList<String>();
ArrayList<String> country_name = new ArrayList<String>();
ArrayList<String> country_short = new ArrayList<String>();
ArrayList<CheckBox> check_box = new ArrayList<CheckBox>();
public static final String ARG_OS = "OS";
int pos;
String sql = "";
ListView list;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.all_city_layout, null);
databaseHelper = new DatabaseHelper(view.getContext());
try {
databaseHelper.createDataBase();
databaseHelper.openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(view.getContext(), "Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
list = (ListView) view.findViewById(R.id.citylist);
list.setFocusable(false);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View myview,
int position, long id) {
Toast.makeText(getActivity(),
position + " " + city_name.get(position),
Toast.LENGTH_LONG).show();
}
});
sql = "SELECT _id, city_name, country_name, country_short, favorite FROM city order by country_name asc;";
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomList(getActivity(), databaseHelper
.getResult(sql), city_name, country_name,
country_short, check_box);
list.setAdapter(customAdapter);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In this picture I clicked "Shirajganj" but the Toast shows me "230 Thakurgaon" position =230 is correct but city_name.get(230) should be "Shirajganj" . I think it is doing wrong when I am trying to add value to ArrayList<String> in binView in CustomList. How can I solve this problem?

It's not a good idea to fill that array in bindView method. The Android doesn't create separate view for each row in the list, it's utilize already created ones, that's why you will always receive unexpected results in your arraylist. The better is to fill the array in your activity, instead of the adapter. Just query your database for the same result like this:
Cursor cursor = getContentResolver().query(
uri,
projection,
selectionClause
selectionArgs,
sortOrder);
while (cursor.moveToNext ()){
arrayList.add(cursor.getAsString(cursor.getColumnIndex('column_name')));
}
cursor.close()

Related

How to delete custom listview row

I am trying to delete a row or any row while by clicking on my custom listview adapter which extends Baseadapter. I have found many solutions on Google but none of them worked for me.I am successfully generating a listview with the help of this class but can't delete a row or any row.
Here is my code
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.BaseAdapter;
import com.brl.loverfreedatingapp.R;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class WhoLikedMeAdapter extends BaseAdapter {
private Context context; //context
private ArrayList<String> masterID = new ArrayList<String>();
private ArrayList<String> slaveID = new ArrayList<String>();
private ArrayList<String> masterName = new ArrayList<String>();
private ArrayList<String> slaveName = new ArrayList<String>();
private ArrayList<String> slaveUrl = new ArrayList<String>();
public WhoLikedMeAdapter(Context context, ArrayList<String> masterID, ArrayList<String> slaveID, ArrayList<String> masterName, ArrayList<String> slaveName, ArrayList<String> slaveUrl) {
this.context = context;
this.masterID = masterID;
this.slaveID = slaveID;
this.masterName = masterName;
this.slaveName = slaveName;
this.slaveUrl = slaveUrl;
}
#Override
public int getCount() {
return masterID.size(); //returns total of items in the list
}
#Override
public Object getItem(int position) {
return masterID.get(position); //returns list item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// inflate the layout for each list row
if (convertView == null) {
convertView = LayoutInflater.from(context).
inflate(R.layout.wholikeme_row, parent, false);
}
CircleImageView profile_image = (CircleImageView) convertView.findViewById(R.id.profile_image);
TextView name = (TextView)convertView.findViewById(R.id.name);
ImageButton unlike = (ImageButton)convertView.findViewById(R.id.unlike);
ImageButton like = (ImageButton)convertView.findViewById(R.id.like);
name.setText(slaveName.get(position));
//--
if(slaveUrl.get(position).equals("")){
Picasso.with(context)
.load(R.drawable.image_placeholder)
//.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(R.drawable.image_placeholder)
.into(profile_image);
}else {
Picasso.with(context)
.load(slaveUrl.get(position))
//.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(R.drawable.image_placeholder)
.into(profile_image);
}
//-------------
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
masterID.remove(position);// not working
notifyDataSetChanged();
}
});
unlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
masterID.remove(position);// not working
notifyDataSetChanged();
}
});
// returns the view for the current row
return convertView;
}
}
Found the solution! I have to remove all the data in a row to remove a listview row. Previously I was trying with only 1 data (masterID).
masterID.remove(position);
slaveID.remove(position);
masterName.remove(position);
slaveName.remove(position);
slaveUrl.remove(position);
notifyDataSetChanged();

Android SQL Query only showing one result

I am fairly new to Android Application Development. I've been working on an application that computes a person's college GPA. At the moment I am currently struggling to show the GPA a student gets for each Semester. I am only able to print out the results for the first semester.
DISPLAYALLSEMESTERACTIVITY.java
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import static com.example.govinpillai.ca2.R.id.listView1;
public class DISPLAYALLSEMESTERACTIVITY extends AppCompatActivity {
DataManager sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
GPAListAdapter listAdapter ;
ListView LISTVIEW;
String SEMHOLDER;
ArrayList<String> ID_Array;
ArrayList<String> GPA_Array;
ArrayList<String> SEMESTER_Array;
Intent intent;
ArrayList<String> ListViewClickItemArray = new ArrayList<String>();
String TempHolder ;
private String LOG_TAG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displayallsemesteractivity);
LISTVIEW = (ListView) findViewById(listView1);
intent = getIntent();
SEMHOLDER = intent.getStringExtra("SEM");
ID_Array = new ArrayList<String>();
GPA_Array = new ArrayList<String>();
SEMESTER_Array = new ArrayList<String>();
sqLiteHelper = new DataManager(this);
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
/* Intent intent = new
Intent(getApplicationContext(),DISPLAYONEGRADEACTIVITY.class);
intent.putExtra("ListViewClickedItemValue",
ListViewClickItemArray.get(position).toString());
startActivity(intent);*/
}
});
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
cursor = sqLiteDatabase.rawQuery("SELECT id, sum(gcproduct)/sum(credit) AS Semestergpa , Semester FROM " + DataManager.TABLE_NAME +" group by Semester", null);
ID_Array.clear();
SEMESTER_Array.clear();
GPA_Array.clear();
if (cursor.moveToFirst()) {
do {
ID_Array.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_ID)));
//Inserting Column ID into Array to Use at ListView Click Listener Method.
/* ListViewClickItemArray.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_ID)));*/
GPA_Array.add(cursor.getString(cursor.getColumnIndex("Semestergpa")));
SEMESTER_Array.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_5_SEMESTER)));
while(!cursor.isAfterLast()) {
Log.e(LOG_TAG, DatabaseUtils.dumpCurrentRowToString(cursor));
cursor.moveToNext();
}
} while (cursor.moveToNext());
}
listAdapter = new GPAListAdapter(DISPLAYALLSEMESTERACTIVITY.this,
ID_Array,
GPA_Array,
SEMESTER_Array
);
LISTVIEW.setAdapter(listAdapter);
cursor.close();
}
}
GPAListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class GPAListAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> GPA;
ArrayList<String> SEMESTER;
public GPAListAdapter(
Context context2,
ArrayList<String> id,
ArrayList<String> gPA,
ArrayList<String> sEMESTER
)
{
this.context = context2;
this.ID = id;
this.SEMESTER = sEMESTER;
this.GPA = gPA;
}
public int getCount() {
// TODO Auto-generated method stub
return ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View child, ViewGroup parent) {
Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.gpaitems, null);
holder = new Holder();
holder.IDTextView = (TextView) child.findViewById(R.id.textViewID);
holder.GPATextView = (TextView) child.findViewById(R.id.textViewGPA);
holder.SEMESTERTextView = (TextView) child.findViewById(R.id.textViewSEMESTER);
child.setTag(holder);
} else {
holder = (Holder) child.getTag();
}
holder.IDTextView.setText(ID.get(position));
holder.GPATextView.setText(GPA.get(position));
holder.SEMESTERTextView.setText(SEMESTER.get(position));
return child;
}
public class Holder {
TextView IDTextView;
TextView GPATextView;
TextView SEMESTERTextView;
}
}
My logcat output
[ 02-03 23:15:46.304 6376: 6376 E/ ]
0 {
id=2
Semestergpa=3.75
SEMESTER=1
}
[ 02-03 23:15:46.304 6376: 6376 E/ ]
1 {
id=4
Semestergpa=3
SEMESTER=2
}
Desired Output in Android Virtual Device
id=2
Semester=1
Semester GPA=3.75
id=4
Semester=2
Semester GPA=3
Actual Output in Android Virtual Device
id=2
Semester=1
Semester GPA=3.75
Could someone show me what have I done wrong and what I can do to fix it ?
In DISPLAYALLSEMESTERACTIVITY.java, my guess is you did cursor.moveToNext() twice, so it advances by 2 & skips one record each time.
For the cursor related code in ShowSQLiteDBdata(), can you try replacing it with the below code?
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
// do everything here first
ID_Array.add(....)
.....
.....
// only move to next cursor position at end of while loop
cursor.moveToNext();
}
}
Hope this help, good luck!

Delete item from database and listview on button click

I'm trying to get an item deleted from both my custom listview and from the database on button click. I got so far but from the code below you are likely to see my error. When the first item is deleted the positions change however the idarray info is not updated. Please help!
History Adapter:
package uk.co.rascagneres.clocking_app;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Jacques on 08/08/2016.
*/
public class HistoryAdapter extends BaseAdapter implements ListAdapter{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public ArrayList<String> idArray = new ArrayList<String>();
DatabaseHandler db;
public HistoryAdapter (ArrayList<String> list, Context context, ArrayList<String> idArray, DatabaseHandler db){
this.list = list;
this.context = context;
this.idArray = idArray;
this.db = db;
}
#Override
public int getCount(){
return list.size();
}
#Override
public Object getItem(int pos){
return list.get(pos);
}
#Override
public long getItemId(int pos){
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.history_list, null);
}
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
System.out.println(list.get(position));
System.out.println(idArray.get(position));
System.out.print(idArray);
db.deleteRowID(Integer.parseInt(idArray.get(position)));
list.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
HistoryFragment:
package uk.co.rascagneres.clocking_app;
import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Jacques on 03/08/2016.
*/
public class HistoryFragment extends Fragment {
DatabaseHandler db;
View myView;
ArrayList<String> historyArray = new ArrayList<String>();
ArrayList<String> idArray = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.history_layout, container, false);
db = new DatabaseHandler(getActivity());
ArrayList<String> list = insertData();
HistoryAdapter adapter = new HistoryAdapter(list, getActivity(), idArray, db);
ListView lView = (ListView)myView.findViewById(R.id.listView);
lView.setAdapter(adapter);
return myView;
}
public ArrayList<String> insertData(){
Cursor c = db.getAllData();
ArrayList<String> list = new ArrayList<String>();
while(c.moveToNext()) {
int id = c.getInt(0);
long in = c.getLong(1);
long out = c.getLong(2);
String outTime;
if(out == 0){
outTime = "N/A";
}else{
outTime = ClockingFragment.getDate(out, "HH:mm");
}
String date = ClockingFragment.getDate(in, "EEE, MMM d");
String inTime = ClockingFragment.getDate(in, "HH:mm");
historyArray.add(date + "\n Clocked In: " + inTime + "\n Clocked Out: " + outTime + "\n");
idArray.add(String.valueOf(id));
}
if (historyArray.isEmpty()){
historyArray.add("No History Available!");
}
return historyArray;
}
public ArrayList<String> getIdArray(){
System.out.println(idArray);
return idArray;
}
}
Section of Database Handler:
public void deleteRowID(int ID)
{
SQLiteDatabase db = this.getWritableDatabase();
String IDString = String.valueOf(ID);
try
{
db.delete(TABLE_NAME, "ID = ?", new String[] { IDString });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}

Highlight first item of listview when created

I am able to change the background of a selected item in a listview. I want the first item's background highlighted when the list is created. The code below gives an error when I try to perform a "performItemClick".
I have seen suggestions to modify my getView in the array adapter. However, I get the error "no default construction in Android.widget.ArrayAdapter when I try to create the class MyCustomAdapter in my java code.
So, if I need to create an extention of my ArrayAdapter class to do this, how do I get around this error. If there is another way I am open to suggestions.
Thanks
package com.hofficer.aclsfast;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.lang.reflect.Array;
public class NarrowChild extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_narrow_child);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//fix orientation
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//MyCustomAdapter adapter = new MyCustomAdapter();
createList();
}
/*
class MyCustomAdapter extends ArrayAdapter{
}*/
void createList(){
String[] narrowChoices = {"aFib/Flutter", "Narrow Cmplx Tachycardia", "PSVT", "Junctional Tachycardia", "Multifocal Tachycardia"};
ListAdapter theAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, narrowChoices);
final ListView listview = (ListView) findViewById(R.id.narrowListView);
listview.setAdapter(theAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
//clear menu and highlight selected item
for (int i = 0; i < 5; i++) {
listview.getChildAt(i).setBackgroundColor(Color.WHITE);
}
listview.getChildAt(position).setBackgroundColor(Color.CYAN);
}
});
Boolean result = listview.performItemClick(listview,0,0); //THIS GIVES ERROR NULL POINT EXCEPTION
}
}
in your MyCustomAdapter you have to override the one or more of the constructors of ArrayAdapter or create your own. and example of custom Adapter is :
public class WeatherAdapter extends ArrayAdapter<Weather>{
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
more info from the source
in your case you need to check the position if it is 0 and then return the desired item.
I can't test it right now but can't you just call listview.getChildAt(0).setBackgroundColor(Color.CYAN); instead of Boolean result = listview.performItemClick(listview,0,0);?
Try this:
Boolean result = listview.performItemClick(listview.getAdapter().getView(0),0,0);
or:
Boolean result = listview.performItemClick(listview.getAdapter().getView(0, null, null),0,0);
See this question and check the docs.
EDIT
I think your problem is the getChildAt() method. You should look at this question.

Android SQLite Update Query - What Am I Missing

package lab.ex1;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import lab.ex1.HospitalDatabase.Patient;
public class DisplayPatient extends HospitalActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
displayData();
}
private void displayData()
{
final List<Integer> myList = new ArrayList<Integer>();
final Intent me = new Intent(DisplayPatient.this,UpdatePatient.class);
final Bundle b = new Bundle();
//Build new Patient
PatientData build = new PatientData();
final TableLayout viewData = (TableLayout)findViewById(R.id.tblDisplay);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Patient.patientTableName);
SQLiteDatabase db = mDatabase.getReadableDatabase();
String asColumnsToReturn[] = {Patient.patientTableName + "." + Patient.ID,
Patient.patientTableName + "." + Patient.firstName,
Patient.patientTableName + "." + Patient.lastName,
Patient.patientTableName + "." + Patient.room,
Patient.patientTableName + "." + Patient.department};
Cursor c = queryBuilder.query(db,asColumnsToReturn,null,null,null,null,Patient.DEFAULT_SORT_ORDER);
if (c.moveToFirst())
{
for (int i=0; i< c.getCount(); i++)
{
final TableRow newRow = new TableRow(this);
Button update = new Button(this);
TextView display = new TextView(this);
display.setTextSize(15);
update.setX(15);
update.setY(10);
update.setTextSize(10);
Button deleteButton = new Button(this);
deleteButton.setX(100);
deleteButton.setY(100);
deleteButton.setTextSize(10);
deleteButton.setText("Delete");
update.setText("Update");
deleteButton.setTag(c.getInt(c.getColumnIndex(Patient.ID)));
update.setTag(c.getInt(c.getColumnIndex(Patient.ID)));
newRow.setTag(c.getInt(c.getColumnIndex(Patient.ID))); // set the tag field on the TableRow view so we know which row to delete
myList.add(c.getInt(c.getColumnIndex(Patient.ID)));
build.setID(Integer.parseInt(c.getString(c.getColumnIndex((Patient.ID)))));
build.setFirstName((c.getString(c.getColumnIndex(Patient.firstName))));
build.setLastName(c.getString(c.getColumnIndex(Patient.lastName)));
build.setDepartment(c.getString(c.getColumnIndex(Patient.department)));
build.setRoom(Integer.parseInt(c.getString(c.getColumnIndex(Patient.room))));
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer id = (Integer) v.getTag();
deletePatient(id);
final TableLayout patientTable = (TableLayout) findViewById(R.id.tblDisplay);
View viewToDelete = patientTable.findViewWithTag(id);
viewData.removeView(viewToDelete);
}
});
update.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Integer id = (Integer)v.getTag();
final TableLayout patientRmv = (TableLayout)findViewById(R.id.tblDisplay);
for (Integer delete : myList )
{
View viewToDelete = patientRmv.findViewWithTag(delete);
viewData.removeView(viewToDelete);
}
b.putString("key", Integer.toString(id));
me.putExtras(b);
startActivity(me);
}
});
display.setText(build.toString());
newRow.addView(display);
newRow.addView(update);
//newRow.addView(deleteButton);
viewData.addView(newRow);
c.moveToNext();
}
}
else
{
TableRow newRow = new TableRow(this);
TextView noResults = new TextView(this);
noResults.setText("No results to show.");
newRow.addView(noResults);
viewData.addView(newRow);
}
c.close();
db.close();
}
public void deletePatient(Integer id)
{
SQLiteDatabase db = mDatabase.getWritableDatabase();
String astrArgs[] = { id.toString() };
db.delete(Patient.patientTableName, Patient.ID+ "=?",astrArgs );
db.close();
}
}
package lab.ex1;
import lab.ex1.HospitalDatabase.Patient;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class UpdatePatient extends HospitalActivity {
Spinner spinner;
TextView update;
String up;
Button check;
EditText entry;
String setPosition;
TextView updateID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatepatient);
check = (Button)findViewById(R.id.btnUpdate);
entry = (EditText)findViewById(R.id.editUpdate);
updateID = (TextView)findViewById(R.id.txtIDUpdate);
Bundle accept = getIntent().getExtras();
up = accept.getString("key","0");
updateID.setText(null);
updateID.setText("ID: " + up);
update = (TextView)findViewById(R.id.txtUpdateMessage);
update.setText(null);
// update.setText(up);
spinner = (Spinner) findViewById(R.id.spnChoice);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.arrFields, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
updateDB(entry.getText().toString(),setPosition,up);
}
});
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> adapterView,
View view, int pos, long id) {
update.setText(null);
update.setText("I will update On " + adapterView.getItemAtPosition(pos).toString());
setPosition = adapterView.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public void updateDB(String valuesToUpdate, String field,String ID)
{
SQLiteDatabase db = mDatabase.getWritableDatabase();
db.beginTransaction();
try
{
ContentValues updatePatient = new ContentValues();
if (field == "First Name")
{
updatePatient.put(Patient.firstName, valuesToUpdate);
String astrArgs[] = { up.toString() };
db.update(Patient.patientTableName,updatePatient, Patient.ID+"=?", astrArgs);
//
db.setTransactionSuccessful();
}
}
finally
{
db.endTransaction();
}
db.close();
Intent me = new Intent(UpdatePatient.this,DisplayPatient.class);
startActivity(me);
}
}
I am using Android SQLite Database. In my display class, it reads all the entries from the database and displays them along with an update button next to each entry. That entries update button's tag has entries Patient.ID. When the user clicks update, they are taken to the update class where they can select what they want to update, First Name, Last Name, Apartment, Room. Afterward they click update, to which they are taken back to the Display class and they should see there changes. However, when they are taken back, the previous value is still there, the changes do not show up, what am I missing?
Move your displaydata() call from onCreate to onResume.

Categories

Resources