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;
}
Related
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)
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 have stored three values into the database and i want to make search on button click, after clicking on search button it will be move on search screen and there is only search box is presented.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DATABASENAME = "Aadhaar";
public static String PRODUCTTABLE = "Enrolled";
private ArrayList<CandidateModel> cartList = new ArrayList<CandidateModel>();
Context c;
public DatabaseHelper(Context context) {
super(context, DATABASENAME, null, 33);
c = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE if not exists Enrolled(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "_id"
+ " TEXT ,"
+ "FirstName"
+ " TEXT,"
+ "LastName"
+ " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + PRODUCTTABLE);
onCreate(db);
}
public void addProduct(CandidateModel productitem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("_id", productitem.idno);
contentValues.put("FirstName", productitem.productname);
contentValues.put("LastName", productitem.productprice);
db.insert("Enrolled", null, contentValues);
db.close();
}
// update
public void updateProduct(CandidateModel productList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("FirstName", productList.productname);
contentValues.put("LastName", productList.productprice);
db.update("Enrolled", contentValues, "_id=" + productList.idno, null);
db.close();
}
public void emptyProduct() {
try {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from Enrolled");
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeProduct(String productid, String pname, String pprice) {
try {
// SQLiteDatabase db = this.getWritableDatabase();
// db.execSQL("delete from producttable where productidno="
// + productid);
// db.close();
String[] args = { productid };
getWritableDatabase().delete("Enrolled", "_id=?", args);
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<CandidateModel> getProudcts() {
cartList.clear();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from Enrolled", null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
CandidateModel item = new CandidateModel();
item.idno = cursor.getString(cursor.getColumnIndex("_id"));
item.productname = cursor.getString(cursor
.getColumnIndex("FirstName"));
item.productprice = cursor.getString(cursor
.getColumnIndex("LastName"));
cartList.add(item);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}
}
Aadhar.java
public class Aadhar extends Activity implements OnClickListener {
private Button btn_add, btn_view, btn_search;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_add = (Button) findViewById(R.id.btn_add);
btn_view = (Button) findViewById(R.id.btn_view);
btn_search = (Button) findViewById(R.id.btn_search);
btn_add.setOnClickListener(this);
btn_view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Intent addintent = new Intent(Aadhar.this, AddRecord.class);
startActivity(addintent);
break;
case R.id.btn_view:
Intent viewintent = new Intent(Aadhar.this, ViewRecord.class);
startActivity(viewintent);
break;
case R.id.btn_search:
Intent searchIntent = new Intent (Aadhar.this, SearchRecord.class);
startActivity(searchIntent);
default:
break;
}
}
}
SearchRecord.java
public class SearchRecord extends Activity implements OnClickListener {
String TAG = "SearchRecord";
private ListView lv;
// Button searchButton;
private EditText search;
CandidateModel cm;
DatabaseHelper db;
public ArrayList<CandidateModel> _candidatelist = new ArrayList<CandidateModel>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_candidate);
Log.v(TAG, "Searching Candidates");
lv = (ListView) findViewById(R.id.search_listview);
search = (EditText) findViewById(R.id.edit_search);
Log.v(TAG, "Going to enter into TextWatcher");
lv.setTextFilterEnabled(true);
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.v(TAG, "Entered into the Text Changed Method");
((Filterable) _candidatelist).getFilter().filter(s.toString());
Log.v(TAG, "Finished Filtering");
lv.setAdapter((android.widget.ListAdapter) _candidatelist);
}
});
}
CandidateModel.java
public class CandidateModel {
public String getFirstname() {
return fname;
}
public void setFirstname(String fname) {
this.fname = fname;
}
public String getLastname() {
return lname;
}
public void setLastname(String lname) {
this.lname = lname;
}
public String idno="", fname="", lname="";
public String getIdno() {
return idno;
}
public void setIdno(String idno) {
this.idno = idno;
}
}
ViewRecord.java
public class ViewRecord extends Activity {
private ListView listview;
// private EditText search;
String TAG = "ViewRecord";
TextView totalrecords;
DatabaseHelper db;
public ArrayList<CandidateModel> _candidatelist = new ArrayList<CandidateModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_candidates);
totalrecords = (TextView) findViewById(R.id.totalrecords);
listview = (ListView) findViewById(R.id.listview);
}
#Override
protected void onResume() {
super.onResume();
_candidatelist.clear();
db = new DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<CandidateModel> cand_list = db.getCandidates();
for (int i = 0; i < cand_list.size(); i++) {
String tidno = cand_list.get(i).getIdno();
System.out.println("tidno>>>>>" + tidno);
String tname = cand_list.get(i).getFirstname();
String tprice = cand_list.get(i).getLastname();
CandidateModel _CandidateModel = new CandidateModel();
_CandidateModel.setIdno(tidno);
_CandidateModel.setFirstname(tname);
_CandidateModel.setLastname(tprice);
_candidatelist.add(_CandidateModel);
}
totalrecords.setText("Total Enrollments :-" + _candidatelist.size());
listview.setAdapter(new ListAdapter(this));
db.close();
}
public class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return _candidatelist.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
viewHolder = new ViewHolder();
viewHolder._id = (TextView) convertView
.findViewById(R.id.txtdisplaypname);
viewHolder.fname = (TextView) convertView
.findViewById(R.id.txtdisplaypprice);
viewHolder.lname = (TextView) convertView
.findViewById(R.id.txtdisplaypid);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder._id.setText(_candidatelist.get(position).getFirstname()
.trim());
viewHolder.fname.setText(_candidatelist.get(position).getLastname()
.trim());
viewHolder.lname.setText(_candidatelist.get(position).getIdno()
.trim());
final int temp = position;
(convertView.findViewById(R.id.btn_update))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String _id = String.valueOf(_candidatelist
.get(temp).getIdno());
String _fname = _candidatelist.get(temp)
.getFirstname();
String _lname = _candidatelist.get(temp)
.getLastname();
Intent intent = new Intent(ViewRecord.this,
AddUpdateValues.class);
Bundle bundle = new Bundle();
bundle.putString("id", _id);
bundle.putString("name", _fname);
bundle.putString("price", _lname);
intent.putExtras(bundle);
startActivity(intent);
}
});
(convertView.findViewById(R.id.btn_delete))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
ViewRecord.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Log.i(">>>TEMP>>>", temp + "");
Log.i(">>>getIdno>>>>>>",
_candidatelist.get(temp)
.getIdno().trim()
+ "");
System.out
.println(">>>getIdno>>>>>>"
+ _candidatelist
.get(temp)
.getIdno()
.trim());
db.removeCandidate(
_candidatelist.get(temp)
.getIdno().trim(),
"", "");
ViewRecord.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
}
});
alertbox.show();
}
});
return convertView;
}
}
public class ViewHolder {
TextView _id;
TextView fname;
TextView lname;
}
}
ArrayList is not Filterable. It says in the Filterable documentation :
Defines a filterable behavior. A filterable class can have its data
constrained by a filter. Filterable classes are usually Adapter
implementations.
I think you should replace your ArrayList by an ArrayAdapter
i have a list of medicine, when user click one of the medicine, it will go to next activity which show the details of the medicine..
below code is the activity with list of medicine.. i know i have to use onclicklistener.. but i dont know how to write
public class MedicineView extends Activity
{
private SQLiteDatabase database;
private ArrayList<String> result = new ArrayList<String>();
private ArrayList<Long> idList = new ArrayList<Long>();
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.medicine_view);
ListView listContent = (ListView)findViewById(R.id.listView1);
DBHelper helper = new DBHelper(this);
database = helper.getWritableDatabase();
// view data
try{
String query = "select * from " + DBHelper.TABLE_MEDICINE;
Cursor c = database.rawQuery(query, null);
if(c!=null)
{
c.moveToFirst();
int getIndex = c.getColumnIndex(DBHelper.MED_ID);
int getNameIndex = c.getColumnIndex(DBHelper.MED_NAME);
int getDosageIndex = c.getColumnIndex(DBHelper.DOSAGE);
int getFrequencyIndex = c.getColumnIndex(DBHelper.FREQUENCY);
if(c.isFirst())
{
do{
idList.add(c.getLong(getIndex));
result.add(c.getString(getNameIndex)+" | " + c.getString(getDosageIndex)
+" | " + c.getString(getFrequencyIndex)+"\n" );
}while(c.moveToNext());
}
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,result);
listContent.setAdapter(adapter);
listContent.setTextFilterEnabled(true);
c.close();
}
catch(SQLException e){
}
listContent.setOnItemClickListener(this);
}
public void onClickHome(View v){
startActivity (new Intent(getApplicationContext(), MenuUtama.class));
}
public void onClickAdd(View v){
startActivity (new Intent(getApplicationContext(), MedicineAdd.class));
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent myIntent = new Intent(v.getContext(), MedicineDetail.class);
myIntent.putExtra("position", position);
startActivityForResult(myIntent, 0);
}
} // end class
then here is my detailsactivity
public class MedicineDetail extends Activity
{
private SQLiteDatabase database;
private ArrayList<Long> idList = new ArrayList<Long>();
ArrayList<String> list = new ArrayList<String>();
Button btnEdit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.medicine_detail);
int id = getIntent().getIntExtra("id", 2); //i don't know how to do here
btnEdit = (Button)findViewById(R.id.imageButton2);
DBHelper helper = new DBHelper(this);
database = helper.getWritableDatabase();
String sql = "select * from " + DBHelper.TABLE_MEDICINE + " WHERE id = " + id;
Cursor cursor = database.rawQuery(sql, null);
try{
if( cursor != null ){
if (cursor.moveToFirst()) {
do {
idList.add(cursor.getLong(0));
list.add(cursor.getString(1));
list.add(cursor.getString(2));
list.add(cursor.getString(3));
list.add(cursor.getString(4));
list.add(cursor.getString(5));
list.add(cursor.getString(6));
} while (cursor.moveToNext());
}
}
}
catch(SQLException e){
}
cursor.moveToFirst();
TextView StartDate = (TextView) findViewById(R.id.textView8);
TextView EndDate = (TextView)findViewById(R.id.textView9);
TextView MedName = (TextView)findViewById(R.id.textView10);
TextView Dosage = (TextView)findViewById(R.id.textView11);
TextView Frequency = (TextView)findViewById(R.id.textView12);
TextView Instruction = (TextView)findViewById(R.id.textView13);
StartDate.setText(cursor.getString(1));
EndDate.setText(cursor.getString(2));
MedName.setText(cursor.getString(3));
Dosage.setText(cursor.getString(4));
Frequency.setText(cursor.getString(5));
Instruction.setText(cursor.getString(6));
cursor.close();
}
public void onClickHome(View v){
startActivity (new Intent(getApplicationContext(), MedicineView.class));
}
} // end class
i dont know what how to do, anyone plz help
You should let you class implement the onItemClickListener
implements AdapterView.OnItemClickListener
and in onCreate add the following line:
listContent.setOnItemClickListener(this);
and then overwrite:
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Intent intent = createIntentwithExtra(v, position);
startActivity(intent);
}
UPDATE:
public Intent createIntentwithExtra(View v, int position)
{
Intent intent = new Intent(getApplicationContext(), TaskDetailsActivity.class);
intent.putExtra(KEY_USERNAME, username);
intent.putExtra(KEY_ID, tasksRepository.get(position).getId());
return intent;
}
use onItemSelectedListener: arg0 would be the listview and arg2 would be the item position in the adapter
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
}
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