I have an adapter, which get second parameter from "while" loop, so it must show me a query result in the ListView but it only shows me the last meaning of variable "string_word" instead. But even log.d output what I want line by line. Here is the code :
public class MainActivity extends Activity implements OnClickListener {
final String LOG_TAG = "myLogs";
IdDB idh;
SynDB sqh;
SQLiteDatabase sqdb, iddb;
Button btnOk;
EditText etWord;
String eWord;
ListView lvMain;
public ArrayAdapter<String> adapter;
public String string_word;
public String[] syns;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etWord = (EditText) findViewById(R.id.etWord);
btnOk = (Button) this.findViewById(R.id.btnOk);
lvMain = (ListView) findViewById(R.id.lvMain);
btnOk.setOnClickListener(btnOkListener);
//initialize our class-cover IdDB
idh = new IdDB(this);
// initialize our class-cover SynDB
sqh = new SynDB(this);
// we need db to read and write
sqdb = sqh.getWritableDatabase();
iddb = idh.getWritableDatabase();
}
public void displayListView(){
// создаем адаптер
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, syns);
}
public OnClickListener btnOkListener = new OnClickListener(){
#Override
public void onClick(View v) {
eWord = etWord.getText().toString();
switch (v.getId()){
case R.id.btnOk:
String query = //long SQL query (return "word")
Log.d(LOG_TAG, query);
Log.d(LOG_TAG, "--- Rows in mytable: ---");
// query to get Cursor
Cursor cursor = sqdb.rawQuery(query, null);
int wordColIndex = cursor.getColumnIndex(SynDB.Word);
while (cursor.moveToNext()) {
string_word = cursor.getString(wordColIndex);
Log.d(LOG_TAG, "word = "+ string_word);
syns = new String[] {string_word};
displayListView();
// присваиваем адаптер списку
lvMain.setAdapter(adapter);
}
cursor.close();
break;
default:
break;
} // close switch
} // close onClick
};
protected void onStop() {
super.onStop();
sqdb.close();
sqh.close();
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View view) {
}
}
What it does:
Create an array with one item string_word calls displayListView and set another adapter to the ListView
And do it everytime i gets a value from the list.
To do what you want, you should change your logic a bit.
You will create the adapter only one time.
You will add every string to a List (more flexible than an array since here you don't know how many words you will have)
So:
Delete all displayListView method calls and add one in the onCreate. (and every lvMain.setAdapter(adapter);)
Your displayListView should be the only one which sets the adapter to the ListView
public void displayListView(){
// создаем адаптер
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, syns);
lvMain.setAdapter(adapter);
}
Something like:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etWord = (EditText) findViewById(R.id.etWord);
btnOk = (Button) this.findViewById(R.id.btnOk);
lvMain = (ListView) findViewById(R.id.lvMain);
btnOk.setOnClickListener(btnOkListener);
//initialize our class-cover IdDB
idh = new IdDB(this);
// initialize our class-cover SynDB
sqh = new SynDB(this);
// we need db to read and write
sqdb = sqh.getWritableDatabase();
iddb = idh.getWritableDatabase();
displayListView();
}
Go in the top where is
public String[] syns;
and change it type to List<String> (ArrayAdapter have a constructor with List, so don't worry.)
public List<String> syns;
Here your
int wordColIndex = cursor.getColumnIndex(SynDB.Word);
while (cursor.moveToNext()) {
string_word = cursor.getString(wordColIndex);
Log.d(LOG_TAG, "word = "+ string_word);
syns = new String[] {string_word};
displayListView();
// присваиваем адаптер списку
lvMain.setAdapter(adapter);
}
should look like
int wordColIndex = cursor.getColumnIndex(SynDB.Word);
while (cursor.moveToNext()) {
string_word = cursor.getString(wordColIndex);
Log.d(LOG_TAG, "word = "+ string_word);
syns = new String[] {string_word};
}
Now you should add to the List every word the Cursor return, so you should use .add method.
int wordColIndex = cursor.getColumnIndex(SynDB.Word);
while (cursor.moveToNext()) {
string_word = cursor.getString(wordColIndex);
Log.d(LOG_TAG, "word = "+ string_word);
syns.add(string_word);
}
When ready, call adapter.notifyDataSetChanged() to notify to the Adapter that you finished to change your data and can redraw the items in the ListView
Related
There is a Sqlite database, and I am experiencing problems with paging implementation inside of Expandable list view.
I want to fetch data (ten records at a time) and display these records in Explandable list view.
How can I achieve this goal via AsyncTask, doing background interaction with the server to display the information from the database?
Main Activity
/** The count. */
static int count=0;
listDataHeader = new ArrayList<String>();
childDataHashMap = new HashMap<String, List<ChildInfo>>();
databaseHelper = new DatabaseHelper(this);
// readFromFile();
csvToSqlite();
// get the listview
expListView = (ExpandableListView) findViewById(R.id.expandableListView);
txtViewLoadMore=(TextView) findViewById(R.id.textViewLoadMore);
// LoadMore button
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load More");
// Adding Load More button to lisview at bottom
expListView.addFooterView(btnLoadMore)
txtViewLoadMore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
count = count+1;
//call AsyncTask for loading data in Expandable list view in background
new NearBuyAsyncTask(MainActivity.this).execute();
}
});
getExpandableListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,childDataHashMap);
// setting list adapter
expListView.setAdapter(listAdapter);
}
public void getExpandableListData() {
// Group data//
// databaseHelper = new DatabaseHelper(getApplicationContext());{
Cursor cursor;
if(count==0)
{
cursor = databaseHelper.getGroupData();
}
else{
cursor = databaseHelper.getLoadMoreData(count);
}
cursor.moveToFirst();
Log.i(TAG, "cursor.getCount()" + cursor.getCount());
do {
String categoryDescription = cursor.getString(cursor.getColumnIndex("categorydesc"));
int categoryId = cursor.getInt(cursor.getColumnIndex("CategoryId"));
// Child data//
Cursor cursorChild = databaseHelper.getChildData(categoryId);
List<ChildInfo> childList = new ArrayList<ChildInfo>();
cursorChild.moveToFirst();
while (cursorChild.moveToNext()) {
String businessName = cursorChild.getString(cursorChild .getColumnIndex("BusinessName"));
phoneNumber = cursorChild.getString(cursorChild.getColumnIndex("ph_Phone"));
String landMark = cursorChild.getString(cursorChild .getColumnIndex("LandMark"));
ChildInfo childInfo = new ChildInfo(businessName, phoneNumber, landMark);
childList.add(childInfo);
}
childDataHashMap.put(categoryDescription, childList);
} while (cursor.moveToNext());
cursor.close();
}
NearBuyAsyncTask
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
activity = new MainActivity();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
MainActivity mainActivity = new MainActivity();
mainActivity.getExpandableListData();
}
});
return null;
}
I am getting following error
Caused by: java.lang.RuntimeException: Can't create handler inside
thread that has not called Looper.prepare()
I am using the following code for my main activity:
private TripsData datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new TripsData(this);
datasource.open();
List values = datasource.getAllTrips();
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
Trip trip = null;
//Trip trip_temp;
switch (view.getId()) {
case R.id.add:
trip=newTrip(view);
//trip.setId(trip_temp.getId());
//trip.setName(trip_temp.getName());
adapter.add(trip);
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
trip = (Trip) getListAdapter().getItem(0);
datasource.deleteTrip(trip);
adapter.remove(trip);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
public Trip newTrip(View view){
final Trip trip=new Trip();
//create DialogBox
final Dialog dialog = new Dialog(this);
//modify features BEFORE setting content view
//dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.project_dialog);
//Create EditBoxes for Dialog
final EditText nameEdit=(EditText) dialog.findViewById(R.id.dialog_name_text);
final EditText descEdit=(EditText) dialog.findViewById(R.id.dialog_type_text);
//define button's text
View dialogButton=dialog.findViewById(R.id.dialog_button_create);
TextView text=(TextView) dialogButton;
text.setText("Create");
//Button Creation
Button createButton = (Button) dialogButton;
// if button is clicked, close the custom dialog
createButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Trip trip_temp = datasource.createTrip(nameEdit.getText().toString());
//String[] trips = new String[] { "Cool", "Very nice", "Hate it" };
//int nextInt = new Random().nextInt(3);
// save the new comment to the database
trip.setId(trip_temp.getId());
trip.setName(trip_temp.getName());
//trip = datasource.createTrip(nameEdit.getText().toString());
dialog.dismiss();
}
});
dialog.show();
return trip;
}
The user should be able to input values in the dialog box and the Name would be displayed in the list of created Trips. However, there seems to be a bug when there is only one value in the List because that item is not displayed. I've spent hours on this and can't figure it out.
EDIT:
This is my TripsData code
public class TripsData {
private SQLiteDatabase database;
private TripsDB dbHelper;
private String[] allTrips = { TripsDB.TRIP_COLUMN_ID,
TripsDB.TRIP_COLUMN_TYPE};
public TripsData(Context context){
dbHelper = new TripsDB(context);
}
public void open() throws SQLException{
database = dbHelper.getWritableDatabase();
}
public void close(){
dbHelper.close();
}
public Trip createTrip(String type){
ContentValues values = new ContentValues();
values.put(TripsDB.TRIP_COLUMN_TYPE, type);
long insertId = database.insert(TripsDB.TABLE_TRIPS, null, values);
Cursor cursor = database.query(TripsDB.TABLE_TRIPS,
allTrips, TripsDB.TRIP_COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
Trip newTrip = cursorToTrip(cursor);
cursor.close();
return newTrip;
}
public void deleteTrip(Trip trip){
long id = trip.getId();
System.out.println("Project deleted with id: " + id);
database.delete(TripsDB.TABLE_TRIPS, TripsDB.TRIP_COLUMN_ID
+ " = " + id, null);
}
public List<Trip> getAllTrips(){
List<Trip> trips = new ArrayList<Trip>();
Cursor cursor = database.query(TripsDB.TABLE_TRIPS,
allTrips, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
Trip trip = cursorToTrip(cursor);
trips.add(trip);
cursor.moveToNext();
}
cursor.close();
return trips;
}
private Trip cursorToTrip(Cursor cursor){
Trip trip = new Trip();
trip.setId(cursor.getLong(0));
trip.setName(cursor.getString(1));
return trip;
}
It looks like the issue is with your TripsData class, post that, also try and log the length of the adapter and the data source after you delete an item. I am guessing that those two numbers are getting out of sync somewhere.
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");
}
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