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);
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.
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);
}
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 add edit function to my database, read and write function working perfectly. First step i want, is to show record clicked from my listview in another layout (the same layout I use for add new record)
in show_activity I've this code
show_activity
///ON CREATE
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
datasource = new DBAdapter(this);
datasource.open();
Cursor cursor = datasource.Query(filter);
String[] columns = new String[] { "swimm_pos", "swimm_date","swimm_lap", "swimm_stroke", "swimm_time", "swimm_media", "swimm_efficiency", "swimm_note" };
int[] to = new int[] { R.id.swimm_pos, R.id.swimm_date, R.id.swimm_lap, R.id.swimm_stroke, R.id.swimm_time, R.id.swimm_medialap, R.id.swimm_efficiency, R.id.swimm_note};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.list_layout,
cursor,
columns,
to);
this.setListAdapter(adapter);
datasource.close();
'''''
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent("com.poolper.Edit_Activity");
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("idContacto",cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
this is extract from my Edit Activity
public class Edit_Activity extends Activity {
int idContacto;
DBAdapter datasource;
GetSet details;
EditText edtSwimm_pos;
.....
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_layout);
edtSwimm_pos = (EditText) findViewById(R.modificacontatto.edswimm_date);
......
LoadDetails();
...
private void LoadDetails(){
idContacto = getIntent().getIntExtra("idContacto", 0);
datasource = new DBAdapter(this);
datasource.open();
details = datasource.getContacto(idContacto);
datasource.close();
edtSwimm_pos.setText(contacto.getswimm_pos());
.....
and from my DBAdapter
public class DBAdapter {
private SQLiteDatabase database;
private DBHelper DBHelper;
private String[] allColumns = {
DBHelper.ID,
DBHelper.SWIMM_POS,
DBHelper.SWIMM_DATE,
DBHelper.SWIMM_LAP,
DBHelper.SWIMM_STROKE,
DBHelper.SWIMM_TIME,
DBHelper.SWIMM_MEDIA,
DBHelper.SWIMM_EFFICIENCY,
DBHelper.SWIMM_NOTE
};
....
private GetSet cursorToContacto(Cursor cursor) {
GetSet contacto = new GetSet(cursor.getLong(0),cursor.getString(1),cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8));
return contacto;
}
public GetSet getContacto (int idContacto){
Cursor cursor = database.query(DBHelper.TABLE_NAME, allColumns, DBHelper.ID + " = " + idContacto, null,null, null, null);
cursor.moveToFirst();
return cursorToContacto(cursor);
}
and this GetSet class
public class GetSet {
private long _id;
private String swimm_pos;
private String swimm_media;
private String swimm_note;
private String swimm_date;
private String swimm_lap;
private String swimm_stroke;
private String swimm_time;
private String swimm_efficiency;
public GetSet(long id, String swimm_pos, String swimm_date, String swimm_lap,String swimm_stroke, String swimm_time, String swimm_media, String swimm_efficiency, String swimm_note){
this._id=id;
this.swimm_pos=swimm_pos;
this.swimm_date=swimm_date;
this.swimm_lap=swimm_lap;
this.swimm_stroke=swimm_stroke;
this.swimm_media=swimm_media;
this.swimm_time=swimm_time;
this.swimm_efficiency=swimm_efficiency;
this.swimm_note=swimm_note;
}
public long getId() {
return _id;
}
public void setId(long id) {
this._id = id;
}
public String getswimm_pos() {
return swimm_pos;
}
public void setswimm_pos(String swimm_pos) {
this.swimm_pos = swimm_pos;
}
But when i click on record debug show the NullPointException at this line
Cursor cursor = (Cursor) adapter.getItem(position)
Change your code as:
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
cursor.moveToPosition(position);
Intent intent = new Intent(Current_Activity.this,Edit_Activity.class);
intent.putExtra("idContacto",cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
I've one listView with multiple choice and checkbox.
I get the values from listview executing a query in sqlite3.
When i click a button, I need to insert the selected items in another table but i don't know how can i do it.
Before doing insert i'm trying to know if it works showing one console log (Log.v). in this code there is not insert statement.
Any suggestions? Thanks in advance and sorry about my english,
Alex.
I paste the code:
public class productos extends Activity {
SQLiteDatabase db;
Spinner prodSpinner;
ArrayAdapter<String> prodAdapter;
Spinner catSpinner;
ArrayAdapter<String> catAdapter;
Cursor catCursor;
Cursor prodCursor;
String Value2;
String valor2;
SparseBooleanArray sp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productos);
Bundle extras = getIntent().getExtras();
//final String Value = extras.getSerializable("Lista").toString();
//final String Value2 = extras.getSerializable("Super").toString();
Button CatText2 = (Button) findViewById(R.id.textCategoria);
CatText2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.v("valor4:", "AAAAA");
recCatSpinner();
}
});
Button btSelecciona = (Button) findViewById(R.id.btSelecciona);
btSelecciona.setOnClickListener(new OnClickListener() {
public void onClick (View arg0) {
Toast.makeText(getBaseContext(),"AAAA",Toast.LENGTH_SHORT).show();
}
});
Button btComanda = (Button) findViewById(R.id.btComanda);
btComanda.setOnClickListener(new OnClickListener() {
public void onClick (View arg0) {
EscriuComanda();
}
private void EscriuComanda() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
int count = 0;
//
sp = new SparseBooleanArray();
//SparseBooleanArray sp=prodSpinner.getCheckedItemPositions();
sp.clear();
sp = prodSpinner.getCheckedItemPositions();
for(int i = 0; i < sp.size(); i++)
{
if ( sp.valueAt(i)==true)
{
Log.v("400", "SI: " + valor2);
}
else
{
Log.v("500", "No: " + valor2);
}
}
}
});
//Toast.makeText(getBaseContext(),Value2,Toast.LENGTH_SHORT).show();
recCatSpinner();
}
public class UsuariosSQLiteHelper extends SQLiteOpenHelper {
public UsuariosSQLiteHelper(Context contexto, String nombre,
CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
public void onCreate(SQLiteDatabase db) {
Log.v("OnClickV", "1");
}
public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva) {
Log.v("OnClickV", "1");
}
}
public Cursor recuperaCategoria()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "Categorias";
String[] columns = {"_id","Nombre"};
return db.query(tableName, columns, null, null, null, null, null);
}
public Cursor recuperaProductos()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "ArtSuperV";
String[] columns = {"_id","NombreA"};
String where = "NombreC='" + valor2 + "'";
return db.query(tableName, columns, where, null, null, null, null);
}
public void recCatSpinner() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
catCursor = recuperaCategoria();
catCursor.moveToPosition(1);
catAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); //.simple_list_item_multiple_choice);// .simple_spinner_item);
catAdapter.setDropDownViewResource (android.R.layout.simple_list_item_multiple_choice); //.simple_spinner_dropdown_item);
prodSpinner.setAdapter(catAdapter);
if (catCursor.moveToFirst()) {
do {
catAdapter.add(catCursor.getString(1));
}
while (catCursor.moveToNext());
if (db != null) {
Toast.makeText(getBaseContext(),catCursor.getString(1),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(catCursor);
catCursor.close();
prodSpinner.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view2, int pos, long id) {
valor2 = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(),valor2,Toast.LENGTH_SHORT).show();
Log.v("valor2:", valor2);
recProdSpinner();
}
});
}
public void recProdSpinner() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
prodCursor = recuperaProductos();
prodCursor.moveToPosition(1);
prodAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice); //.simple_list_item_multiple_choice);// .simple_spinner_item);
prodSpinner.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
prodAdapter.setDropDownViewResource (android.R.layout.simple_list_item_multiple_choice); //.simple_spinner_dropdown_item);
prodSpinner.setAdapter(prodAdapter);
if (prodCursor.moveToFirst()) {
do {
prodAdapter.add(prodCursor.getString(1));
}
while (prodCursor.moveToNext());
if (db != null) {
Toast.makeText(getBaseContext(),prodCursor.getString(1),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(prodCursor);
prodCursor.close();
prodSpinner.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view2, int pos, long id) {
valor2 = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(),valor2,Toast.LENGTH_SHORT).show();
Log.v("valor2:", valor2);
}
});
}
}
Cant figure out some of the code flow due to language issue.But scheme should be:1. Set the adapters for both the lists (even if the lists are empty on launch, set the adapter with the empty but initialised array lists and make the array list as the global variables of the class so that they can be accessed from anywhere in the activity.) 2. Now select the items from the list1 and get their index in the first list.3. Add those items in the second array list. 4. Call the "notifyDataSetChanged()" for the adapter of the second list view.Link to know about proper use of "notifyDataSetChanged()" are notifyDataSetChanged example