Hi I have an app that display the name and gender of the students. In my query, I limit the display to 20. How will I apply the display of 21-40 by clicking the next button. Also it will go back if i click previous.
MainActivity class
public class MainActivity extends Activity {
List<Students> GetAll;
DatabaseHelper db = new DatabaseHelper(this);
ListView lv;
Context context = this;
DatabaseHelper dbhelper;
Button btnprevious,btnnext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbhelper = new DatabaseHelper(MainActivity.this);
//Add below lines to your original code
try{
dbhelper.createDataBase();
}
catch(IOException e){
e.printStackTrace();
}
try {
dbhelper.openDataBase();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Till here
GetAll = dbhelper.getAll();
lv = (ListView) findViewById(R.id.list);
lv.setAdapter(new ViewAdapter());
}
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return GetAll.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item,null);
}
final TextView names = (TextView) convertView.findViewById(R.id.doctorlist_name);
final TextView gender = (TextView) convertView.findViewById(R.id.doctorlist_gender);
names.setText(GetAll.get(position).getname());
gender.setText(GetAll.get(position).getgender());
return convertView;
}
}
}
DatabaseHelper class
public List<Students> getAll() {
final int maxCount = 20;
List<Students> sList = new ArrayList<Students>();
{
String selectQuery =
"SELECT id,full_name,gender FROM students LIMIT " +maxCount+" ";
Log.e("students query: ", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Students si = new Students();
si.setid(Integer.parseInt(cursor.getString(0)));
si.setname(cursor.getString(1));
si.setgender(cursor.getString(2));
sList.add(si);
} while (cursor.moveToNext());
}
db.close();
}
return sList;
}
On next Button click increase index with 20 and on previous button click decrease the index to 20, You can achieve with below query.
String selectQuery = "SELECT id,full_name,gender FROM students LIMIT 20, "+index;
Edit:
public List<Students> getStudent(int index) {
final int maxCount = 20;
List<Students> sList = new ArrayList<Students>();{
String selectQuery = "SELECT id,full_name,gender FROM students LIMIT "+maxCount+", "+index;;
Log.e("students query: ", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Students si = new Students();
si.setid(Integer.parseInt(cursor.getString(0)));
si.setname(cursor.getString(1));
si.setgender(cursor.getString(2));
sList.add(si);
} while (cursor.moveToNext());
}
db.close();
}
return sList;
}
private int currentPageIndex=0;
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.prevBtn;
currentPageIndex -=20;
GetStudent.clear();
GetStudent.addAll(dbhelper.getStudent(int index));
adapter.notifyDataSetChanged();
break;
case R.id.nextBtn;
currentPageIndex +=20;
GetStudent.clear();
GetStudent.addAll(dbhelper.getStudent(int index));
adapter.notifyDataSetChanged();
break;
}
}
You can change the whereCluse:
for example next page: (page = 2)
id> 20*(page - 1) and LIMIT 20*(page)
Related
Main Activity code
I want to insert this
public void method() {
name = LoginActivity.name;
score = GameView.valueCurrent;
ContentValues values = new ContentValues();
values.put("name", name);
values.put("score", score);
}
And dont " myDB.execSQL("INSERT INTO scores (name, score) VALUES ('Marie', '4');");"
public class MainActivity extends AppCompatActivity {
private List<Items> itemsList = new ArrayList<Items>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase myDB = null;
try {
//Create a Database if doesnt exist otherwise Open It
myDB = this.openOrCreateDatabase("leaderboard", MODE_PRIVATE, null);
//Create table in database if it doesnt exist allready
myDB.execSQL("CREATE TABLE IF NOT EXISTS scores (name TEXT, score TEXT);");
//Select all rows from the table
Cursor cursor = myDB.rawQuery("SELECT * FROM scores", null);
//If there are no rows (data) then insert some in the table
if (cursor != null) {
if (cursor.getCount() == 0) {
/*** In this case i want to put the values of the Users that are playing my app
myDB.execSQL("INSERT INTO scores (name, score) VALUES ('Andy', '7');");
myDB.execSQL("INSERT INTO scores (name, score) VALUES ('Marie', '4');");
myDB.execSQL("INSERT INTO scores (name, score) VALUES ('George', '1');");
**//
}
}
} catch (Exception e) {
} finally {
//Initialize and create a new adapter with layout named list found in activity_main layout
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, itemsList);
listView.setAdapter(adapter);
Cursor cursor = myDB.rawQuery("SELECT * FROM scores", null);
if (cursor.moveToFirst()) {
//read all rows from the database and add to the Items array
while (!cursor.isAfterLast()) {
Items items = new Items();
items.setName(cursor.getString(0));
items.setScore(cursor.getString(1));
itemsList.add(items);
cursor.moveToNext();
}
}
//All done, so notify the adapter to populate the list using the Items Array
adapter.notifyDataSetChanged();
}
}
}
CustomListAdapter code
public class CustomListAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater inflater;
private List<Items> itemsItems;
public CustomListAdapter(Context context, List<Items> itemsItems) {
this.mContext = context;
this.itemsItems = itemsItems;
}
#Override
public int getCount() {
return itemsItems.size();
}
#Override
public Object getItem(int location) {
return itemsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View scoreView, ViewGroup parent) {
ViewHolder holder;
if (inflater == null) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (scoreView == null) {
scoreView = inflater.inflate(R.layout.list_row, parent, false);
holder = new ViewHolder();
holder.name = (TextView) scoreView.findViewById(R.id.name);
holder.score = (TextView) scoreView.findViewById(R.id.score);
scoreView.setTag(holder);
} else {
holder = (ViewHolder) scoreView.getTag();
}
final Items m = itemsItems.get(position);
holder.name.setText(m.getName());
holder.score.setText(m.getScore());
return scoreView;
}
static class ViewHolder {
TextView name;
TextView score;
}
}
Items Code
public class Items {
private String name, score;
public Items() {
}
public Items(String name, String score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
Couple of more things.
How to show the current Leaderboard using this code of Database?
I dont know how to use on that.
Use Google Play: https://developers.google.com/games/services/android/leaderboards
Create Google Play Game In Developer Console
1)Add the BaseGameUtils SDK from here https://github.com/playgameservices/android-basic-samples
2) In app gradle:
dependencies {
compile 'compile project(':BaseGameUtils')'
}
3) Update Score: Games.Leaderboards.submitScore(mGoogleApiClient, LEADERBOARD_ID, 1337);
4)
Display Leaderboard: startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
LEADERBOARD_ID), REQUEST_LEADERBOARD);
Make sure you successfully connect to googleApiClient/Google Play Games Services
I'm trying to fill spinner item from sqlite table
i have no idea how to do it , i tried to follow other example but i think its different than mine
what is the easiest way to do it and how can i set onclicklistener for each item
Thanks in advance
MainActivity + sqliteopenhelper
public ArrayList<String> getTableValues() {
ArrayList<String> my_array = new ArrayList<String>();
try {
SQLiteDatabase db = this.getWritableDatabase();
Cursor resultPPNAME = db.rawQuery("select NAMEPPL from " + Table_name2, null);
if (resultPPNAME.moveToFirst()) {
String PPLNAMESPIN = resultPPNAME.getString(0);
my_array.add(PPLNAMESPIN);
}
while (resultPPNAME.moveToNext()) ;
} catch (Exception e) {
}
return my_array;
}
MainActivity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
DB db;
Button addmed,addpl;
TextView PPLNAMERES;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PPLNAMERES = (TextView)findViewById(R.id.PPLNAMEGETNAME);
db = new DB(this);
listView();
String spinValue = db.getMainData().toString();
ArrayList<String> my_array= new ArrayList<String>();
my_array = db.getTableValues();
Spinner spinner = (Spinner)findViewById(R.id.spin1);
ArrayAdapter<String> my_adapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,my_array);
spinner.setAdapter(my_adapter);
}
public void addmedView(View view){
Intent ADDMEDVIEW = new Intent(this,ADDMEDCINEVIEW.class);
startActivity(ADDMEDVIEW);
}
public void addpplview(View view){
Intent ADDPPLVIEWS = new Intent(this,ADDPPLVIEW.class);
startActivity(ADDPPLVIEWS);
}
public void listView(){
Cursor res= db.getMainData();
if(res.moveToFirst()){
PPLNAMERES.setText(res.getString(0));
} else{
Toast.makeText(MainActivity.this,"No Data",Toast.LENGTH_LONG).show();
return;
}}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}}
adapter code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PPLNAMERES = (TextView)findViewById(R.id.PPLNAMEGETNAME);
db = new DB(this);
ArrayList<String> my_array= new ArrayList<String>();
my_array = db.getTableValues();
Spinner spinner = (Spinner)findViewById(R.id.spin1);
ArrayAdapter<String> my_adapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,my_array);
spinner.setAdapter(my_adapter);
}
onitemselected methods
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) { }
// try like this.
public ArrayList<String> getTableValues() {
ArrayList<String> my_array = new ArrayList<String>();
try {
SQLiteDatabase db = this.getWritableDatabase();
Cursor resultPPNAME = db.rawQuery("select NAMEPPL from " + Table_name2, null);
// Change Made HERE
resultPPNAME.moveToFirst();
while (cur.isAfterLast() == false) {
String PPLNAMESPIN = resultPPNAME.getString(0);
cur.moveToNext();
my_array.add(PPLNAMESPIN);
}
} catch (Exception e) {
}
return my_array;
}
Can anybody please have a look at my code and tell me where I am wrong? I don't get errors, unfortunately the row that is long pressed and new value is provided is not being updated unless I specify exact row number. I need to be able to update the row that is clicked. I tried everything and up to today I didn't manage to get any help. I am beginner in Android development.
Here is the code of MyDB:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
db.beginTransaction();
db.setTransactionSuccessful();
db.endTransaction();
return db.update(Constants.TABLE_NAME , newValue , Constants.KEY_ID + "= ?" ,
new String[]{ Double.valueOf(rowId).toString() })>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the code with the dialog, where I should update the row:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
private long rowId;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
long rowId = adapter.getItemId(position); //Will return the clicked item
saveItToDB(rowId);
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
// public void notifyDataSetChanged();
dismiss();
try {
saveItToDB(rowId);
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB(long rowId) {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), rowId);
dba.close();
((TextView) editText).setText("");
}
}
And here is the Diary Adapter:
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
i found first problem at your DB class
update this method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
To
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, new String[]{Constants.TITLE_NAME ,Constants.CONTENT_NAME}, null,
null, null, null, null);
return c;
}
After a long time I figured out that changing argument from 0 to different number allows me to update row with corresponding id to this number:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
In above code I changed 0 to 2 and I was able to update content of row no 2. Here is full class code:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
Now, what do I need to do in order to tell it that I want to update row that is clicked, not row number 2? Any help would be appreciated.
Here is MyDB code:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the Adapter:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Implement getItemId(int position) in your adapter. In your onListItemClick method, call this method with the given position.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long itemId = adapter.getItemId(position);
saveItToDB(itemId);
}
private void saveItToDB(long itemId) {
String text = editText.getText().toString();
editText.setText("");
dba.open();
dba.updateDiaryEntry(text, itemId);
dba.close();
}
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