I am working on a diary style application that uses an SQlite Database and fragments with a listview. I have a listview that displays records from the database with selected fields. When a user clicks a listview item a fragment opens to display all the fields from that record. The problem is the fragment is only displaying the fields which are called by the listview. How can I get my fragment to display all the field data for that record? I have a field called STIME that I am trying to display in the example below. Thanks!
List.java
private DBManager dbManager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SLOC, DatabaseHelper.DSNM, DatabaseHelper.SDATE, DatabaseHelper.STIME};
final int[] to = new int[] { R.id.id, R.id.sloc, R.id.dsnm ,R.id.sdate, R.id.add_time};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_list);
dbManager = new DBManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(this, R.layout.fragment_viewtrip, cursor, columns, to, 0);
adapter.notifyDataSetChanged();
Log.i("Listtrip", "STIMEad = " + DatabaseHelper.STIME);
listView.setAdapter(adapter);
//String stime = R.id.add_time;
// OnCLickListener For List Items
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView slocTextView = (TextView) view.findViewById(R.id.sloc);
TextView dsnmTextView = (TextView) view.findViewById(R.id.dsnm);
TextView sdateTextView = (TextView) view.findViewById(R.id.sdate);
String id = idTextView.getText().toString();
String sloc = slocTextView.getText().toString();
String dsnm = dsnmTextView.getText().toString();
String sdate = sdateTextView.getText().toString();
Log.i("Listtrip", "SDate = " + sdate);
Log.i("Listtrip", "STIME = " + R.id.add_time);
Intent modify_intent = new Intent(getApplicationContext(), UpdateTrip.class);
modify_intent.putExtra("sloc", sloc);
modify_intent.putExtra("dsnm", dsnm);
modify_intent.putExtra("sdate", sdate);
modify_intent.putExtra("id", id);
startActivity(modify_intent);
}
});
}
DBmanager Fetch
public Cursor fetch() {
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SLOC, DatabaseHelper.FLOC, DatabaseHelper.DSNM, DatabaseHelper.SDATE, DatabaseHelper.STIME };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToLast();
}
return cursor;
}
Update Fragment
public class UpdateTrip extends Activity implements View.OnClickListener {
private Button modButton;
private Button rmButton;
private EditText slocEditText;
private EditText flocEditText;
private EditText dsnmEditText;
private EditText descEditText;
private Button add_time;
private Button add_date;
private long _id;
private DBManager dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Modify Trip Details");
setContentView(R.layout.fragment_update);
dbManager = new DBManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
slocEditText = (EditText) findViewById(R.id.slocadd_edittext);
flocEditText = (EditText) findViewById(R.id.flocadd_edittext);
dsnmEditText = (EditText) findViewById(R.id.dsnmadd_edittext);
descEditText = (EditText) findViewById(R.id.descadd_edittext);
add_time = (Button) findViewById(R.id.add_time);
add_date = (Button) findViewById(R.id.add_date);
modButton = (Button) findViewById(R.id.mod_button);
rmButton = (Button) findViewById(R.id.rm_button);
//String stime = getItem();
Intent intent = getIntent();
String id = intent.getStringExtra("id");
String sloc = intent.getStringExtra("sloc");
String floc = intent.getStringExtra("floc");
String desc = intent.getStringExtra("desc");
String dsnm = intent.getStringExtra("dsnm");
String stime = intent.getStringExtra("stime");
String sdate = intent.getStringExtra("sdate");
_id = Long.parseLong(id);
slocEditText.setText(sloc);
flocEditText.setText(floc);
dsnmEditText.setText(dsnm);
descEditText.setText(desc);
add_time.setText(stime);
add_date.setText(sdate);
modButton.setOnClickListener(this);
rmButton.setOnClickListener(this);
}
Related
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.
public class AddMark extends AppCompatActivity {
SQLControlerSubject dbconnection;
Spinner spinnerM;
TextView tv_markId, tv_markSub,tv_markType;
TextView tv_listmarkId,tv_listmarkName,tv_listmarkMark,tv_listmarkType,tv_listmarkDescription;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_mark);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.buttonAddMark);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (spinnerM.getSelectedItem() != null) {
tv_markId = (TextView) findViewById(R.id.mark_id);
tv_markSub = (TextView) findViewById(R.id.markSub);
tv_markType = (TextView) findViewById(R.id.mark_tutorlec);
String markId = tv_markId.getText().toString();
String markSub = tv_markSub.getText().toString();
String markType = tv_markType.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), AddMarkInside.class);
modify_intent.putExtra("markId", markId);
modify_intent.putExtra("markSub", markSub);
modify_intent.putExtra("markType", markType);
startActivity(modify_intent);
}
else {Toast.makeText(getApplicationContext(), "Please select a subject", Toast.LENGTH_LONG).show();
}
}
});
// **************************Spinner view*****************************
dbconnection = new SQLControlerSubject(this);
dbconnection.openDatabase();
spinnerM = (Spinner)findViewById(R.id.spinnerMark);
Cursor cursor = dbconnection.readSubjectMark();
String[] from = new String[] {
DBhelperSubject.SUBJECT_ID,
DBhelperSubject.SUBJECT_NAME,
DBhelperSubject.SUBJECT_TYPE
};
int[] to = new int[] {
R.id.mark_id,
R.id.markSub,
R.id.mark_tutorlec
};
SimpleCursorAdapter adapterMark = new SimpleCursorAdapter
(AddMark.this, R.layout.row_format_mark, cursor, from, to);
adapterMark.notifyDataSetChanged();
spinnerM.setAdapter(new NothingSelectedSpinnerAdapter(adapterMark, R.layout.spinner_show_nothing, this));
//**********************************List View*******************************
list = (ListView) findViewById(R.id.listViewMark);
Cursor cursorM = dbconnection.readMark();
String[] a = new String[]{
DBhelperSubject.MARK_ID,
DBhelperSubject.SUBJECT_NAME,
DBhelperSubject.SUBJECT_TYPE,
DBhelperSubject.MARK_MARKS,
DBhelperSubject.MARK_DESCRIPTION
};
int[] b = new int[]{
R.id.list_mark_id,
R.id.list_mark_name,
R.id.list_mark_type,
R.id.list_mark_mark,
R.id.list_mark_description
};
final SimpleCursorAdapter adapterM = new SimpleCursorAdapter(
AddMark.this, R.layout.row_format_list_mark, cursorM, a, b);
adapterM.notifyDataSetChanged();
list.setAdapter(adapterM);
//*******************************************************************************
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
tv_listmarkId = (TextView) view.findViewById(R.id.list_mark_id);
tv_listmarkName = (TextView) view.findViewById(R.id.list_mark_name);
tv_listmarkType = (TextView) view.findViewById(R.id.list_mark_type);
tv_listmarkMark = (TextView) view.findViewById(R.id.list_mark_mark);
tv_listmarkDescription = (TextView) view.findViewById(R.id.list_mark_description);
String listmarkId = tv_listmarkId.getText().toString();
String listmarkName = tv_listmarkName.getText().toString();
String listmarkType = tv_listmarkType.getText().toString();
String listmarkMark = tv_listmarkMark.getText().toString();
String listmarkDescription = tv_listmarkDescription.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), UpdateMark.class);
modify_intent.putExtra("listmarkId", listmarkId);
modify_intent.putExtra("listmarkName", listmarkName);
modify_intent.putExtra("listmarkType", listmarkType);
modify_intent.putExtra("listmarkMark", listmarkMark);
modify_intent.putExtra("listmarkDescription", listmarkDescription);
startActivity(modify_intent);
}
});
}
}
If i use if(spinnerM.getSelectedItem() != null) on listview it will force to close.
If i want to let user to select a subject, the listview will show the subject's data only, other data which is not selected by the user will not show it out.
I want to get list of items inside my dialog box form database.
I have "mylist" that is on Mainactivity. When I click one list item, I want the lists of
items inside dialogbox.
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
ArrayList<String> getdialoglist = new ArrayList<String>();
final ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getdialoglist);
ListView dialoglist = (ListView) findViewById(R.id.dialogListView);
dialoglist.setAdapter(adapter1);
String[] sColumns = {"_id", "title","description","date","location","trainer_id"};
final Cursor cursor = db.query("training", sColumns, null, null, null, null, null);
mylist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long _id) {
builder.setTitle("Title");
builder.setCursor(cursor, null, null);
builder.setAdapter(adapter1, null);
builder.create();
builder.show();
}
});
I managed to fetch the list of Items from the pre-populated database and onItemClick appears dialogbox with more information about the items. Hope it might help you :)
public class MainActivity extends Activity{
private ListView trainingListView;
private ListAdapter trainingListAdapter;
private ArrayList<Training> trainingArrayList;
//Lists that contain title of trainings
ArrayList<String> titleList = new ArrayList<String>();
DatabaseHelper helper = new DatabaseHelper(this);
//private static final String DB_PATH = "data/data/com.Areva.areva_attendance/databases/";
final Context context = this;
// Database Name
//private static String DB_NAME = "attendance.sqlite";
private Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trainingListView = (ListView) findViewById(R.id.traininglistView);
trainingArrayList = new ArrayList<Training>();
// Create a list that contains only title of the training
trainingListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getTrainingsList());
trainingListView.setAdapter(trainingListAdapter);
trainingListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long id) {
// arg2 = the id of the item in our view (List/Grid) that we clicked
// arg3 = the id of the item that we have clicked
final Training data = trainingArrayList.get(arg2);
Toast.makeText(getApplicationContext(), "You clicked on position : " + arg2 + " and ID : " + id, Toast.LENGTH_LONG).show();
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(data.getTitle());
TextView description = (TextView) dialog.findViewById(R.id.textView1);
description.setText("Description: "+ data.getDescription());
TextView date = (TextView) dialog.findViewById(R.id.textView2);
date.setText("Date: "+ data.getDate());
TextView location = (TextView) dialog.findViewById(R.id.textView3);
location.setText("Location: "+ data.getLocation());
Button back_btn = (Button) dialog.findViewById(R.id.button1);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
Button start_btn = (Button) dialog.findViewById(R.id.button2);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, TraineeActivity.class);
//intent.putExtra("data",trainingListView.getSelectedItem().toString());
intent.putExtra("trainingId", Training.getId());
intent.putExtra("title", data.getTitle().toString());
MainActivity.this.startActivity(intent);
}
});
dialog.show();
}
});
}
#SuppressWarnings("deprecation")
private ArrayList<String> getTrainingsList() {
//Open database helper Class
DatabaseHelper helper = new DatabaseHelper(this);
// Then we need to get a readable database
SQLiteDatabase db = helper.getReadableDatabase();
//Cursor cursor = db.rawQuery("SELECT t.* FROM training t JOIN attendance a ON t._id=a.training_id=?;",
// new String[] {Integer.toString(training_id)});
final String selectQuery = "SELECT * FROM training";
//Getting a cursor to fetch data from the database
final Cursor cursor = db.rawQuery(selectQuery, null);
startManagingCursor(cursor);
while(cursor.moveToNext()){
Training training = new Training();
training.setId(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.TRAINING_ID)));
training.setTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_TITLE)));
training.setDescription (cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_DESCRIPTION)));
training.setDate(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_DATE)));
training.setLocation(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_LOCATION)));
//String Trainer_id = cursor.getString(cursor.getColumnIndex(DatabaseHelper.TRAINING_TRAINER_ID));
//Pass to the arraylist
trainingArrayList.add(training);
// But we need a List of String to display in the ListView also.
//That is why we create "titleList"
titleList.add(training.getTitle());
}
return titleList;
}
}
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");
}
Ok, I'm still kind of new to android and eclipse but the title pretty much says it all. I've got a ListView that I populated from rows in DB. I want to take the selected list view item and delete row from DB when button is clicked and then refresh ListView once this is done. So far my code populates the list, and I'm stuck there. Any help would be greatly appreciated.
public class ViewListingsActivity extends Activity implements OnClickListener {
SQLiteDatabase db;
ListView listview;
Button button;
SimpleCursorAdapter adapter;
String value;
private static final String TAG = DBHelper.class.getSimpleName();
public static final String DB_ADDRESS = BaseColumns._ID;
public static final String DB_DESCRIPTION = "Description";
public static final String DB_URL = "URL";
final String dbTable = "Realtor_SMS_Table";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewlisting);
listview = (ListView) findViewById(R.id.list);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
DBHelper dbhelper = new DBHelper(ViewListingsActivity.this);
db = dbhelper.getWritableDatabase();
Cursor cursor = db.query(dbTable, null, null, null, null, null, null);
startManagingCursor(cursor);
String[] from = new String[] { DB_ADDRESS, DB_DESCRIPTION, DB_URL };
int[] to = new int[] { R.id.textlistaddress, R.id.textlistdescription,
R.id.textlisturl };
adapter = new SimpleCursorAdapter(this, R.layout.rowlist, cursor, from,
to);
listview.setAdapter(adapter);
listview.setChoiceMode(1);
}
public void onClick(View arg0) {
db.delete(dbTable, "_id=" + value, null);
adapter.notifyDataSetChanged();
Log.d("wtf", "deleted: " + value);
}
}
ok, here is my newly edited code:
public class ViewListingsActivity extends Activity implements OnClickListener {
SQLiteDatabase db;
ListView listview;
Button button;
SimpleCursorAdapter adapter;
String value;
OnItemClickListener listener;
Cursor newcursor;
String deleteinfo;
private static final String TAG = DBHelper.class.getSimpleName();
public static final String DB_ADDRESS = BaseColumns._ID;
public static final String DB_DESCRIPTION = "Description";
public static final String DB_URL = "URL";
final String dbTable = "Realtor_SMS_Table";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewlisting);
listview = (ListView) findViewById(R.id.list);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
DBHelper dbhelper = new DBHelper(ViewListingsActivity.this);
db = dbhelper.getWritableDatabase();
Cursor cursor = db.query(dbTable, null, null, null, null, null, null);
startManagingCursor(cursor);
String[] from = new String[] { DB_ADDRESS, DB_DESCRIPTION, DB_URL };
int[] to = new int[] { R.id.textlistaddress, R.id.textlistdescription,
R.id.textlisturl };
adapter = new SimpleCursorAdapter(this, R.layout.rowlist, cursor, from,
to);
listview.setAdapter(adapter);
listview.setChoiceMode(1);
listview.setOnItemClickListener(listener);
}
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
newcursor = ((SimpleCursorAdapter)listview.getAdapter()).getCursor();
deleteinfo = newcursor.getString(1);//getString(0);
}
public void onClick(View arg0) {
db.delete(dbTable, "_id=" + deleteinfo, null);
adapter.notifyDataSetChanged();
Log.d("wtf", "deleted: " + deleteinfo);
}
}
my deleteinfo String keeps returning null, why is it not retrieving the proper column value?
To delete, simply remove the rows from the database via normal querying. Afterwards, update your SimpleCursorAdapter by:
Cursor cursor = ((SimpleCursorAdapter)listview.getAdapter()).getCursor();
cursor.requery();
Note
This must be done on a UI thread
Edit
Set an OnItemClickListener which provides you with a position parameter of the selected item. See Adapter.onItemClickListener | Android Developers
This position can be used to grab a cursor pointing to the row:
Cursor cursor = (Cursor) ((SimpleCursorAdapter)listview.getAdapter()).getItem(position);