THIS gives me a string value that I can use:
Cursor vTypeChose = (Cursor)(vTypeSpinner.getSelectedItem());
if (vTypeChose != null) {
typePicked = vTypeChose.getString(
vTypeChose.getColumnIndex(DataBaseHelper.POWERSPORTS_TYPE));
}
THIS gives me null:
vTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
pos, long id) {
if(pos!=0){
Cursor vTypeChose = (Cursor)(vTypeSpinner.getSelectedItem());
if (vTypeChose != null) {
typePicked = vTypeChose.getString(
vTypeChose.getColumnIndex(DataBaseHelper.POWERSPORTS_TYPE));
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Using a Log.e and a toast with the typePicked variable within the OnItemSelectedListener shows me that it is firing, just not passing me the correct value.
Without the OnItemSelectedListener it populates the second spinner with the related data. Once the OnItemSelectedListener is added, the 2nd spinner gets populated with nothing because the string value is null.
(EDIT) Added code:
public class PowersportsEquivalent extends Activity {
DataBaseHelper myDbHelper;
String typePicked = null;
String makePicked = null;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_powersports_equivalent);
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
// TODO Auto-generated catch block
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
final Cursor vType;
final Cursor vMake;
final Spinner vTypeSpinner;
final Spinner vMakeSpinner;
//POWERSPORTS TYPE Cursor
vType = (Cursor) DataBaseHelper.getPowersportsType();
startManagingCursor(vType);
SimpleCursorAdapter scaType = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vType,
new String [] {DataBaseHelper.POWERSPORTS_TYPE},
new int[] {android.R.id.text1});
scaType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vTypeSpinner = (Spinner) findViewById(R.id.typeSpinner);
vTypeSpinner.setAdapter(scaType);
//POWERSPORTS MAKE Cursor
vTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
pos, long id) {
if(pos!=0){
Cursor vTypeChose = (Cursor)(vTypeSpinner.getSelectedItem());
if (vTypeChose != null) {
typePicked = vTypeChose.getString(
vTypeChose.getColumnIndex(DataBaseHelper.POWERSPORTS_TYPE));
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
startManagingCursor(vMake);
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vMake,
new String [] {DataBaseHelper.POWERSPORTS_MAKE},
new int[]{android.R.id.text1});
scaMake.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vMakeSpinner = (Spinner) findViewById(R.id.makeSpinner);
vMakeSpinner.setAdapter(scaMake);
Your code edited:
public class PowersportsEquivalent extends Activity {
DataBaseHelper myDbHelper;
String typePicked = null;
String makePicked = null;
final SimpleCursorAdapter scaMake;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_powersports_equivalent);
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
// TODO Auto-generated catch block
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
final Cursor vType;
final Cursor vMake;
final Spinner vTypeSpinner;
final Spinner vMakeSpinner;
//POWERSPORTS TYPE Cursor
vType = (Cursor) DataBaseHelper.getPowersportsType();
startManagingCursor(vType);
SimpleCursorAdapter scaType = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vType,
new String [] {DataBaseHelper.POWERSPORTS_TYPE},
new int[] {android.R.id.text1});
scaType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vTypeSpinner = (Spinner) findViewById(R.id.typeSpinner);
vTypeSpinner.setAdapter(scaType);
//POWERSPORTS MAKE Cursor
vTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int pos, long id) {
if(pos!=0){
TextView picked = (TextView)selectedItemView;
if(picked != null){
typePicked = picked.getText().toString();
vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
scaMake.changeCursor(vMake);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
//vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
//startManagingCursor(vMake);
scaMake = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
null,
new String [] {DataBaseHelper.POWERSPORTS_MAKE},
new int[]{android.R.id.text1});
scaMake.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vMakeSpinner = (Spinner) findViewById(R.id.makeSpinner);
vMakeSpinner.setAdapter(scaMake);
Maybe try to use the pos in parameter of onItemSelected, and get the item via the adapter, like this :
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
pos, long id) {
if(pos!=0){
Cursor vTypeChose = (Cursor) scaType.getItem(pos);
if (vTypeChose != null) {
typePicked = vTypeChose.getString(
vTypeChose.getColumnIndex(DataBaseHelper.POWERSPORTS_TYPE));
}
}
}
In order to update spin2 accordingly with spin1 selection you must reload spin2 data at onItemSelected. Try this:
vTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
pos, long id) {
TextView picked = (TextView)selectedItemView;
if(picked != null){
typePicked = picked.getText().toString();
vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
scaMake.changeCursor(vMake);
}
}
}
Also change. (this code is run before onItemSelected this is why typePicked is null)
vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
startManagingCursor(vMake);
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vMake,
new String [] {DataBaseHelper.POWERSPORTS_MAKE},
new int[]{android.R.id.text1});
to
//vMake = (Cursor) DataBaseHelper.getPowersportsMake(typePicked);
//startManagingCursor(vMake);
SimpleCursorAdapter scaMake = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
null,
new String [] {DataBaseHelper.POWERSPORTS_MAKE},
new int[]{android.R.id.text1});
I think after these changes you can use your original code.
Another possible way is to use the id passed to this method and get the value directly from database
Related
I got code from stack overflow to bring up a mesg box.
When I call up a mesga box in activty ActGetKey, it goes back to the starting acticty MainActivity, after the exit button is pressed.
mesg box code:
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
code for MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
keyDB db;
db = new keyDB(this);
db.setUp();
cPassKey mPassKey = new cPassKey("mysec","mypublic","myphase");
db.updateExchange("ted2", mPassKey);
Cursor cursor =db.selectKey("ted2");
// get keys in current pos of database
cPassKey mret=db.loadRecord(cursor);
String name;
Cursor test =db.selectKey("ted1");
name = test.getString(2);
name = test.getString(3);
cursor = db.selectRecords();
int id; String ted;
if (cursor != null)
{
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
} while (cursor.moveToNext());
cursor.close();
}
}
public void sendMessage(View view) {
// Intent intent = new Intent(this, ActGetKey.class);
Intent intent = new Intent(this, ActGetKey.class);
startActivity(intent);
}
}
code for ActGetKey Activity
public class ActGetKey extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String selItem=null;
long d=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_get_key);
keyDB db;
db= new keyDB(this);
Cursor cursor=db.selectRecords();
String ted="na";
int id=0;
if (cursor != null) {
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
// fill up spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
if (cursor != null) {
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
categories.add(ted);
} while (cursor.moveToNext());
cursor.close();
}
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// set selected item
spinner.setSelection(0);
}
}
public void Update3(View view)
{
d++;
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey=(String)temp.getText().toString();
if (isValidString(strPublicKey))
{
msbox( getString(R.string.badtext), "Text for publick key is invalid");
return;
}
temp = findViewById(R.id.publicKey);
String strPrivetKey=(String)temp.getText().toString();
temp = findViewById(R.id.publicKey);
String strKeyPhrase=(String)temp.getText().toString();
// check for bad dada
}
boolean isValidString( String test)
{
if (test==null)
return false;
return true;
}
public void Update2(View view) {
// put keys in keyclass
msbox("kkk","kjjh");
if (true)
return;
keyDB db;
db= new keyDB(this);
cPassKey mPassKey = getKeys();
db.updateExchange(selItem, mPassKey);
// pus keyclass in data base
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
selItem = parent.getItemAtPosition(position).toString();
keyDB db;
db= new keyDB(this);
Cursor cursor =db.selectKey(selItem);
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
boolean loadKeys(cPassKey mPassKey)
{
EditText temp;
temp = findViewById(R.id.publicKey);
temp.setText(mPassKey.publickKey);
temp = findViewById(R.id.secretKey);
temp.setText(mPassKey.secretKey);
temp = findViewById(R.id.phraseKey);
temp.setText(mPassKey.phraseKey);
return true;
}
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
cPassKey getKeys()
{
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey= temp.getText().toString();
temp = findViewById(R.id.secretKey);
String StrSecretKey= temp.getText().toString();
temp = findViewById(R.id.phraseKey);
String StrPhraseKey= temp.getText().toString();
cPassKey mPassKey = new
cPassKey( StrSecretKey,strPublicKey, StrPhraseKey);
return mPassKey;
}
}
public class ActGetKey extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String selItem=null;
long d=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act_get_key);
keyDB db;
db= new keyDB(this);
Cursor cursor=db.selectRecords();
String ted="na";
int id=0;
if (cursor != null) {
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
// fill up spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
if (cursor != null) {
do {
id = cursor.getInt(0);
ted = cursor.getString(1);
categories.add(ted);
} while (cursor.moveToNext());
cursor.close();
}
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// set selected item
spinner.setSelection(0);
}
}
public void Update3(View view)
{
d++;
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey=(String)temp.getText().toString();
if (isValidString(strPublicKey))
{
msbox( getString(R.string.badtext), "Text for publick key is invalid");
return;
}
temp = findViewById(R.id.publicKey);
String strPrivetKey=(String)temp.getText().toString();
temp = findViewById(R.id.publicKey);
String strKeyPhrase=(String)temp.getText().toString();
// check for bad dada
}
boolean isValidString( String test)
{
if (test==null)
return false;
return true;
}
public void Update2(View view) {
// put keys in keyclass
msbox("kkk","kjjh");
if (true)
return;
keyDB db;
db= new keyDB(this);
cPassKey mPassKey = getKeys();
db.updateExchange(selItem, mPassKey);
// pus keyclass in data base
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
selItem = parent.getItemAtPosition(position).toString();
keyDB db;
db= new keyDB(this);
Cursor cursor =db.selectKey(selItem);
// get keys in current pos of database
cPassKey mPassKey=db.loadRecord(cursor);
// displkay the keys on app
loadKeys(mPassKey);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
boolean loadKeys(cPassKey mPassKey)
{
EditText temp;
temp = findViewById(R.id.publicKey);
temp.setText(mPassKey.publickKey);
temp = findViewById(R.id.secretKey);
temp.setText(mPassKey.secretKey);
temp = findViewById(R.id.phraseKey);
temp.setText(mPassKey.phraseKey);
return true;
}
public void msbox(String str,String str2)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setTitle(str);
dlgAlert.setMessage(str2);
dlgAlert.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
cPassKey getKeys()
{
EditText temp;
temp = findViewById(R.id.publicKey);
String strPublicKey= temp.getText().toString();
temp = findViewById(R.id.secretKey);
String StrSecretKey= temp.getText().toString();
temp = findViewById(R.id.phraseKey);
String StrPhraseKey= temp.getText().toString();
cPassKey mPassKey = new
cPassKey( StrSecretKey,strPublicKey, StrPhraseKey);
return mPassKey;
}
}
That is because of the finish() method inside the onClickListener. Finish() doesn't cancel the dialog, it finishes the activity. Use dismiss() if you are trying to hide the dialog
I populated my ListView with data from my database table.
How can I get data from selected item?
This is how I populate ListView:
SimpleCursorAdapter SimpleCursorAdapter;
ListView listCategories = (ListView) findViewById(R.id.categoryList);
categoryRepo categoryRepo = new categoryRepo(this);
TextView textview= (TextView) findViewById(R.id.textView);
private void displayCategories()
{
Cursor cursor = categoryRepo.getCategories();
if (cursor == null)
{
textview.setText("Error");
return;
}
if (cursor.getCount() == 0)
{
textview.setText("No categories.");
return;
}
String[] from = new String[] {category.KEY_CATEGORY_NAME};
int[] to = new int[] {android.R.id.text1};
SimpleCursorAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,from,to,0);
listCategories.setAdapter(SimpleCursorAdapter);
}
I know that I can do this by using listCategories.setOnItemClickListener , but I do not know how. Thank you for help.
I want to get CATEGORY_NAME value.
listCategories.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Cursor cursor = (Cursor) SimpleCursorAdapter.getItem(position);
}
});
How to get string from selected item of SimpleCursorAdapter?
Try this :
listCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor.moveToFirst()){
String selectedValue = cursor.getString(cursor.getColumnIndex(category.KEY_CATEGORY_NAME));
// do what ever you want here
}
cursor.close();
}
});
I am trying to implement a search function inside one of my fragment, as the users types the list will become more defined and match the users input.
I had the code working in an activity but I am getting an error when trying to implement it within a fragment. I am getting an error with the below code snippet, saying that .setFilterQueryProvidercannot be resolved.
Can anyone point out where I may have gone wrong?
Code Snippet
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchRecipes(constraint.toString());
}
});
Fragment containing snippet
public class SearchRecipes extends ListFragment{
private ListView lv;
private static int finalHeat;
private static String finalDietary;
private static int finalTime;
private static Cursor filterCursor;
private static Cursor timeAnddietaryFilterCursor;
private static Cursor heatAnddietaryFilterCursor;
private static Cursor heatAndtimeFilterCursor;
private static Cursor cursor;
private static boolean filter;
EditText inputSearch;
SimpleCursorAdapter myCustomAdaper;
public SearchRecipes() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_search_recipes, container, false);
final DBMain db = new DBMain(getActivity());
db.open();
cursor = db.getAllRecipes();
String[] values = new String[cursor.getCount()];
cursor.moveToFirst();
for(int i = 0; i < cursor.getCount(); i++)
{
String row = cursor.getString(cursor.getColumnIndex("recipe_name"));
values[i] = row;
cursor.moveToNext();
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs);
//myCursorAdapter.getFilter().filter(cs);
//dynamicSearch.this.myCustomAdaper.getFilter().filter(cs);
//dynamicSearch.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchRecipes(constraint.toString());
}
});
FloatingActionButton filterButton = (FloatingActionButton) rootView.findViewById(R.id.filterButton);
filterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// custom ingredient_dialog
filter = false;
final Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.filter_dialog);
dialog.setTitle("Add Ingredient");
final Spinner heat = (Spinner) dialog.findViewById(R.id.heatSpinner);
heat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String heat2 = heat.getSelectedItem().toString();
finalHeat = Integer.parseInt(heat2);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
finalHeat = 0;
}
});
final Spinner dietary = (Spinner) dialog.findViewById(R.id.dietarySpinner);
dietary.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
finalDietary = dietary.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
finalDietary = "";
}
});
final Spinner time = (Spinner) dialog.findViewById(R.id.timeSpinner);
time.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String time2 = time.getSelectedItem().toString();
finalTime = Integer.parseInt(time2);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
finalTime = 0;
}
});
Button dialogButtonOk = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom ingredient_dialog
dialogButtonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHeat != 0 && finalTime != 0 && finalDietary != "") {
//full filter search
filterCursor = db.fullFilter(finalHeat, finalDietary, finalTime);
String[] columns = new String[]{db.KEY_RECIPE_NAME, db.KEY_ID};
int[] to = new int[]{R.id.recipeName};
final SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.possible_recipe_row, filterCursor, columns, to, 0);
//myCursorAdapter.getFilter().filter();
//lv.setAdapter(myCursorAdapter);
//ListView lv = (ListView) rootView.findViewById(R.id.list_view);
//lv.setAdapter(myCursorAdapter);
setListAdapter(adapter);
}
if (finalHeat == 0 && finalTime != 0 && finalDietary != "") {
//filter for final time and dietary
timeAnddietaryFilterCursor = db.timeAnddietaryFilter(finalTime, finalDietary);
String[] columns = new String[]{db.KEY_RECIPE_NAME, db.KEY_ID};
int[] to = new int[]{R.id.recipeName};
final SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.possible_recipe_row, timeAnddietaryFilterCursor, columns, to, 0);
//myCursorAdapter.getFilter().filter();
//lv.setAdapter(myCursorAdapter);
//ListView lv = (ListView) rootView.findViewById(R.id.list_view);
//lv.setAdapter(myCursorAdapter);
setListAdapter(adapter);
}
if (finalHeat != 0 && finalTime == 0 && finalDietary != "") {
//filter for heat and dietary
heatAnddietaryFilterCursor = db.heatAnddietaryFilter(finalHeat, finalDietary);
String[] columns = new String[]{db.KEY_RECIPE_NAME, db.KEY_ID};
int[] to = new int[]{R.id.recipeName};
final SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.possible_recipe_row, heatAnddietaryFilterCursor, columns, to, 0);
//myCursorAdapter.getFilter().filter();
//lv.setAdapter(myCursorAdapter);
//ListView lv = (ListView) rootView.findViewById(R.id.list_view);
//lv.setAdapter(myCursorAdapter);
setListAdapter(adapter);
}
if (finalHeat != 0 && finalTime != 0 && finalDietary.length() > 1) {
//filter for heat and time
heatAndtimeFilterCursor = db.heatAndtimeFilter(finalHeat, finalTime);
String[] columns = new String[]{db.KEY_RECIPE_NAME, db.KEY_ID};
int[] to = new int[]{R.id.recipeName};
final SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.possible_recipe_row, heatAndtimeFilterCursor, columns, to, 0);
//myCursorAdapter.getFilter().filter();
//lv.setAdapter(myCursorAdapter);
//ListView lv = (ListView) rootView.findViewById(R.id.list_view);
//lv.setAdapter(myCursorAdapter);
setListAdapter(adapter);
} else {
String[] columns = new String[]{db.KEY_RECIPE_NAME, db.KEY_ID};
int[] to = new int[]{R.id.recipeName};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.possible_recipe_row, cursor, columns, to, 0);
//ListView recipeList = (ListView) rootView.findViewById(R.id.possibleRecipeList);
//recipeList.setAdapter(myCursorAdapter);
setListAdapter(adapter);
}
dialog.dismiss();
}
});
dialog.show();
}
});
return rootView;
}
}
Error Log
Error:(101, 16) error: cannot find symbol method setFilterQueryProvider(<anonymous FilterQueryProvider>)
I have a spinner that show my data list from a database SQLite.. I want to remove a row from Spinner and db when selected then clicked button btn. How can I do this? Thanks
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_wf2);
mDB = new MyDatabase(getApplicationContext());
mDB.open();
spin = (Spinner)findViewById(R.id.wf_spinner);
c = mDB.fetchWfs();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{WfMetaData.WF_NAME_KEY};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
spinnerPos = pos;
mRowId = id; // database row id
}
});
//fillSpinner(spin);
Button btn = (Button)findViewById(R.id.button11);
btn.setText("Rimuovi");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDB.delete_byID(mRowId);
c.requery();
}
});
/*
Spinner spin = (Spinner)findViewById(R.id.wf_spinner);
Cursor cur = mDB.fetchWfs();
startManagingCursor(cur);
String[] from = new String[] { WfMetaData.WF_NAME_KEY };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter spinAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cur, from, to);
spinAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(spinAdapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Cursor c = (Cursor)parent.getItemAtPosition(pos);
mSpinnerWF = c.getInt(c.getColumnIndexOrThrow(WfMetaData.WF_NAME_KEY));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});*/
//mDB.close();
}
My delete method is this:
public boolean delete_byID(long rowId) {
return mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "=" + rowId, null) > 0;
CharSequence text = "Il Workflow "+ n +" è stato rimosso con successo!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(mContext, text, duration);
toast.show();
}
I don't find any delete method from ID. Is this a db method?
I've modified my app like this:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_wf2);
mDB = new MyDatabase(getApplicationContext());
mDB.open();
spin = (Spinner)findViewById(R.id.wf_spinner);
c = mDB.fetchWfs();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{WfMetaData.WF_NAME_KEY};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
spinnerPos = pos;
mRowId = id; // database row id
}
});
//fillSpinner(spin);
mDB.close();
Button btn = (Button)findViewById(R.id.button11);
btn.setText("Rimuovi");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.getItem(spinnerPos);
mDB.delete_byName((String)adapter.getItem(spinnerPos));
c.requery();
}
});
but I get this error in LogCat(Cast exception):
05-10 15:46:38.586: D/RadioSignalLevel(1758): Gsm Radio Signal level: 4
05-10 15:46:38.586: D/StatusBarPolicy(1758): ERI alert sound is disabled.
05-10 15:46:38.606: D/NetworkService(1939): handle message:800
05-10 15:46:38.606: D/NetworkService(1939): getRawGPRSRegistrationState
05-10 15:46:38.616: I/TransactionService(29090): MMS-STATUS - start transaction service, app version=STABLE4.5.user.4.5.2A-74_OLE-31.2.3.4.Blur_Version.45.31.0.MB860.TIM.en.IT.Thu Sep 22 04:02:02 CST 2011 (log=false) (apn=false) (config=false)
05-10 15:46:38.626: I/SmsReceiverService(29090): MMS-STATUS - start sms receiver service, app version=STABLE4.5.user.4.5.2A-74_OLE-31.2.3.4.Blur_Version.45.31.0.MB860.TIM.en.IT.Thu Sep 22 04:02:02 CST 2011 (log=false) (apn=false) (config=false)
05-10 15:46:38.636: I/TelephonyRegistry(1610): notifyDataConnection: state=0 isDataConnectivityPossible=false reason=nwTypeChanged interfaceName=null networkType=10
05-10 15:46:38.636: I/SYS_MPP(1965): WebtopStatusHandler updateDataIcon()
05-10 15:46:38.646: D/NetworkService(1939): handle message:800
05-10 15:46:38.646: D/NetworkService(1939): getRawGPRSRegistrationState
05-10 15:46:38.646: I/CBStartup(1939): onServiceStateChanged
05-10 15:46:38.656: I/CBSettings(1939): Reading database: KEY_NAME= db_key_language
05-10 15:46:38.656: I/CBSettings(1939): Reading database: KEY_NAME= db_key_channel
public class MyDatabase {
SQLiteDatabase mDb;
DbHelper mDbHelper;
Context mContext;
private static final String DEBUG_TAG = "WFListDatabase";
private static final String DB_NAME="WFListdb";//nome del db
private static final int DB_VERSION=1; //numero di versione del nostro db
public MyDatabase(Context ctx) {
mContext = ctx;
mDbHelper = new DbHelper(ctx, DB_NAME, null, DB_VERSION); //quando istanziamo questa classe, istanziamo anche l'helper (vedi sotto)
}
public void open(){ //il database su cui agiamo è leggibile/scrivibile
mDb=mDbHelper.getWritableDatabase();
}
public void close(){ //chiudiamo il database su cui agiamo
mDb.close();
}
public void insertWf(String name,String cls){ //metodo per inserire i dati
ContentValues cv=new ContentValues();
cv.put(WfMetaData.WF_NAME_KEY, name);
cv.put(WfMetaData.WF_CLASS_KEY, cls);
mDb.insert(WfMetaData.WF_TABLE, null, cv);
}
/*public void removeWf(String name,String cls){ //metodo per inserire i dati
ContentValues cv=new ContentValues();
cv.remove(WfMetaData.WF_NAME_KEY);
cv.remove(WfMetaData.WF_CLASS_KEY);
mDb.(WfMetaData.WF_TABLE, null, cv);
}*/
public Cursor fetchAllWfs(){ //metodo per fare la query di tutti i dati
return mDb.query(WfMetaData.WF_TABLE, new String[]{WfMetaData.WF_NAME_KEY, WfMetaData.WF_CLASS_KEY},null,null,null,null,null);
}
static class WfMetaData { // i metadati della tabella, accessibili ovunque
static final String WF_TABLE = "wfs";
static final String ID = "_id";
static final String WF_NAME_KEY = "name";
static final String WF_CLASS_KEY = "class";
}
private static final String WF_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " //codice sql di creazione della tabella
+ WfMetaData.WF_TABLE + " ("
+ WfMetaData.ID+ " integer primary key autoincrement, "
+ WfMetaData.WF_NAME_KEY + " text not null, "
+ WfMetaData.WF_CLASS_KEY + " text not null);";
public Cursor fetchWfs(){ //metodo per fare la query di tutti i dati
return mDb.query(WfMetaData.WF_TABLE, null,null,null,null,null,null);
}
public void delete_byName(String n){
mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "='" +n + "'", null);
//mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "=?", new String[] { n });
CharSequence text = "Il Workflow "+ n +" è stato rimosso con successo!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(mContext, text, duration);
toast.show();
}
public void delete_byID(long rowId) {
mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "=" + rowId, null);
CharSequence text = "Il Workflow è stato rimosso con successo!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(mContext, text, duration);
toast.show();
}
private class DbHelper extends SQLiteOpenHelper { //classe che ci aiuta nella creazione del db
public DbHelper(Context context, String name, CursorFactory factory,int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase _db) { //solo quando il db viene creato, creiamo la tabella
_db.execSQL(WF_TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(DEBUG_TAG, "Upgrading database. Existing contents will be lost. ["
+ oldVersion + "]->[" + newVersion + "]");
_db.execSQL("DROP TABLE IF EXISTS " + WF_TABLE_CREATE);
onCreate(_db);
}
}
public boolean isEmpty(){
boolean isEmpty = true;
Cursor cursor = mDb.query(WfMetaData.WF_TABLE, new String[] { WfMetaData.WF_NAME_KEY }, null, null, null, null, null);
if (cursor != null && cursor.getCount() > 0)
{
isEmpty = false;
}
return isEmpty;
}
}
public class RemoveWorkflow2 extends Activity {
private EditText nameEditText;
private EditText classEditText;
//private EditText idEditText;
//private int mSpinnerWF;
Spinner spin;
WorkflowChoice wf = new WorkflowChoice();
MyDatabase mDB;
SimpleCursorAdapter adapter;
private long mRowId;
private int spinnerPos;
private String delString;
Cursor c;
//MyDatabase mDB = wf.getDb();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.remove_wf2);
mDB = new MyDatabase(getApplicationContext());
mDB.open();
spin = (Spinner)findViewById(R.id.wf_spinner);
c = mDB.fetchWfs();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{WfMetaData.WF_NAME_KEY};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Cursor c = (Cursor)(parent.getAdapter().getItem(pos));
delString = c.getString(c.getColumnIndex(mDB.);
//spinnerPos = pos;
//mRowId = id; // database row id
}
});
//fillSpinner(spin);
Button btn = (Button)findViewById(R.id.button11);
btn.setText("Rimuovi");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDB.delete_byID(mRowId);
mDB.delete_byName(delString);
c.requery();
}
});
}
private void fillSpinner(Spinner s){
Cursor c = mDB.fetchWfs();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{WfMetaData.WF_NAME_KEY};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
s.setAdapter(adapter);
}
}
I have a problem in method:
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Cursor c = (Cursor)(parent.getAdapter().getItem(pos));
delString = c.getString(c.getColumnIndex(mDB.);
//spinnerPos = pos;
//mRowId = id; // database row id
}
How can I set delString? I don't have YOUR_COLUMN_ID.. How can I resolve it? THANKS
I'm assuming the button is outside the spinner...
You don't really need the position. Set a class variable:
private int spinnerPos;
private long mRowId;
Add this for your spinner:
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
spinnerPos = pos;
mRowId = id; // database row id
}
});
Then for your button:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code to get the string from the adapter
mDB.delete_byName(yourString);
c.requery();
});
By the way, you should leave your DB open until you are exiting the app.
I see you asking a question about deleting by id. In your database class you would have something like this:
public boolean delete(long rowId) {
return mDb.delete(TABLE_NAME, TABLE_ROWID + "=" + rowId, null) > 0;
}
Hope this helps!
EDIT
Better method:
Private String delString;
Add this for your spinnerListener
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Cursor c = (Cursor) (parent.getAdapter().getItem(pos));
delString = c.getString(c.getColumnIndex(YourDB.YOUR_COLUMN_ID)); }
});
Button:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDB.delete_byName(delString);
c.requery();
});
EDIT 2
First Method for delete (by RowId):
public boolean delete_byID(long rowId) {
return mDb.delete(WfMetaData.WF_TABLE, WfMetaData.ID + "=" + rowId, null) > 0;
}
Second Method for delete (by name):
public boolean delete_byName(String name) {
return mDb.delete(WfMetaData.WF_TABLE, WfMetaData.WF_NAME_KEY + "= '" + name + "'", null) > 0;
}
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