passing id to next activity through bundle - android

All i tried is to pass the listview selected items id to the next activity and show the id in a TextView on another page. I receive a number format exception when i click on list item. Any suggestions please.
DataBaseWrapper is the class where database is created.
DishOperation
public class DishOperation {
// Database fields
private DataBaseWrapper dbHelper;
private String[] DISHES_TABLE_COLUMNS = { DataBaseWrapper.DISHES_ID, DataBaseWrapper.DISHES_NAME,DataBaseWrapper.DISHES_INGREDIENTS };
private SQLiteDatabase database;
public DishOperation(Context context) {
dbHelper = new DataBaseWrapper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public Dish addDishes(String name,String ingredients) {
ContentValues values = new ContentValues();
values.put(DataBaseWrapper.DISHES_NAME, name);
values.put(DataBaseWrapper.DISHES_INGREDIENTS, ingredients);
long dishId = database.insert(DataBaseWrapper.DISHES, null, values);
// now that the student is created return it ...
Cursor cursor = database.query(DataBaseWrapper.DISHES,
DISHES_TABLE_COLUMNS, DataBaseWrapper.DISHES_ID + " = "
+ dishId, null, null, null, null);
cursor.moveToFirst();
Dish newComment = parseDishes(cursor);
cursor.close();
return newComment;
}
public void deleteDishes(Dish comment) {
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(DataBaseWrapper.DISHES, DataBaseWrapper.DISHES_ID + " = " + id, null);
}
public List getAllDishes() {
List dishes = new ArrayList();
Cursor cursor = database.query(DataBaseWrapper.DISHES,
DISHES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Dish dish = parseDishes(cursor);
dishes.add(dish);
cursor.moveToNext();
}
cursor.close();
return dishes;
}
public String getInformation(Dish i)
{
long id=i.getId();
String ing= i.getIngredients();
return ing;
}
private Dish parseDishes(Cursor cursor) {
Dish dish = new Dish();
dish .setId((cursor.getInt(0)));
dish .setName(cursor.getString(1));
dish .setIngredients(cursor.getString(2));
return dish ;
}
}
Activity 1
public void onCreate(Bundle savedInstanceState) {
Button btListe;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dishDBoperation = new DishOperation(this);
dishDBoperation.open();
final List values = dishDBoperation.getAllDishes();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("key",id);
startActivity(intent);
}
});
Activity 2
int value;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView text = (TextView) findViewById(R.id.editText3);
Bundle extras = getIntent().getExtras();
if (extras != null) {
long value = extras.getLong("key");
text.setText(String.valueOf(value));// updated!!
}
}

Change
value =Integer.parseInt( extras.getString("key"));
with
long value = extras.getLong("key");
also in your Activity2 you should move
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
in the very beginning of onCreate otherwise your findViewById will return null.
Edit.
Accordingly to the code you posted you have an ArrayAdapter of Dish. Your dataset and your ArrayAdapter should reflect it, and this can be done with Generics.
To get the id of your row as argument of onItemClick, you have to override getItemId. E.g.
setListAdapter(new ArrayAdapter<Dish>(this, android.R.layout.simple_list_item_1, values ) {
#Override
public long getItemId(int position) {
return getItem(position).getId();
}
}));

You should use value = extras.getLong("key"));

In Activity 1, id is of type long and in Activity 2, you try to retrieve it as a String.
Retrieve it by extras.getLong("key");

Related

Showing a single field from SQLite Database in an EditText

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.

load contact query in listview

I'm trying to show contact data in a listview. I think all it's ok but when I execute the app I have the follow error java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView.
The code is this:
public class BuscaContactos extends Activity {
ListView listContactos;
String opcion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_busca_contactos);
listContactos=(ListView)findViewById(R.id.listContactos);
ArrayList<String> listagente = consultaAgenda();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(BuscaContactos.this, R.layout.activity_busca_contactos,listagente);
listContactos.setAdapter(adapter);
listContactos.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
private ArrayList<String> consultaAgenda() {
ArrayList<String> datos = new ArrayList<String>();
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String ContactID = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String nombre = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
datos.add(ContactID);
datos.add(nombre);
}
c.close();
return datos;
}
}
R.layout.activity_busca_contactos should contain a TextView nothing else.
If you want to use other View then you need to create a CustomAdapter

OnItemClickListener to view details of the list

i have a list of medicine, when user click one of the medicine, it will go to next activity which show the details of the medicine..
below code is the activity with list of medicine.. i know i have to use onclicklistener.. but i dont know how to write
public class MedicineView extends Activity
{
private SQLiteDatabase database;
private ArrayList<String> result = new ArrayList<String>();
private ArrayList<Long> idList = new ArrayList<Long>();
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.medicine_view);
ListView listContent = (ListView)findViewById(R.id.listView1);
DBHelper helper = new DBHelper(this);
database = helper.getWritableDatabase();
// view data
try{
String query = "select * from " + DBHelper.TABLE_MEDICINE;
Cursor c = database.rawQuery(query, null);
if(c!=null)
{
c.moveToFirst();
int getIndex = c.getColumnIndex(DBHelper.MED_ID);
int getNameIndex = c.getColumnIndex(DBHelper.MED_NAME);
int getDosageIndex = c.getColumnIndex(DBHelper.DOSAGE);
int getFrequencyIndex = c.getColumnIndex(DBHelper.FREQUENCY);
if(c.isFirst())
{
do{
idList.add(c.getLong(getIndex));
result.add(c.getString(getNameIndex)+" | " + c.getString(getDosageIndex)
+" | " + c.getString(getFrequencyIndex)+"\n" );
}while(c.moveToNext());
}
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,result);
listContent.setAdapter(adapter);
listContent.setTextFilterEnabled(true);
c.close();
}
catch(SQLException e){
}
listContent.setOnItemClickListener(this);
}
public void onClickHome(View v){
startActivity (new Intent(getApplicationContext(), MenuUtama.class));
}
public void onClickAdd(View v){
startActivity (new Intent(getApplicationContext(), MedicineAdd.class));
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent myIntent = new Intent(v.getContext(), MedicineDetail.class);
myIntent.putExtra("position", position);
startActivityForResult(myIntent, 0);
}
} // end class
then here is my detailsactivity
public class MedicineDetail extends Activity
{
private SQLiteDatabase database;
private ArrayList<Long> idList = new ArrayList<Long>();
ArrayList<String> list = new ArrayList<String>();
Button btnEdit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.medicine_detail);
int id = getIntent().getIntExtra("id", 2); //i don't know how to do here
btnEdit = (Button)findViewById(R.id.imageButton2);
DBHelper helper = new DBHelper(this);
database = helper.getWritableDatabase();
String sql = "select * from " + DBHelper.TABLE_MEDICINE + " WHERE id = " + id;
Cursor cursor = database.rawQuery(sql, null);
try{
if( cursor != null ){
if (cursor.moveToFirst()) {
do {
idList.add(cursor.getLong(0));
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
list.add(cursor.getString(6));
} while (cursor.moveToNext());
}
}
}
catch(SQLException e){
}
cursor.moveToFirst();
TextView StartDate = (TextView) findViewById(R.id.textView8);
TextView EndDate = (TextView)findViewById(R.id.textView9);
TextView MedName = (TextView)findViewById(R.id.textView10);
TextView Dosage = (TextView)findViewById(R.id.textView11);
TextView Frequency = (TextView)findViewById(R.id.textView12);
TextView Instruction = (TextView)findViewById(R.id.textView13);
StartDate.setText(cursor.getString(1));
EndDate.setText(cursor.getString(2));
MedName.setText(cursor.getString(3));
Dosage.setText(cursor.getString(4));
Frequency.setText(cursor.getString(5));
Instruction.setText(cursor.getString(6));
cursor.close();
}
public void onClickHome(View v){
startActivity (new Intent(getApplicationContext(), MedicineView.class));
}
} // end class
i dont know what how to do, anyone plz help
You should let you class implement the onItemClickListener
implements AdapterView.OnItemClickListener
and in onCreate add the following line:
listContent.setOnItemClickListener(this);
and then overwrite:
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent intent = createIntentwithExtra(v, position);
startActivity(intent);
}
UPDATE:
public Intent createIntentwithExtra(View v, int position)
{
Intent intent = new Intent(getApplicationContext(), TaskDetailsActivity.class);
intent.putExtra(KEY_USERNAME, username);
intent.putExtra(KEY_ID, tasksRepository.get(position).getId());
return intent;
}
use onItemSelectedListener: arg0 would be the listview and arg2 would be the item position in the adapter
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
}

Android, SQLite rawQuery does not send any results after select a item in a listView

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");
}

Inserting checked values from listView multiple choice

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

Categories

Resources