I have two tables with names disease_table and sysmptoms_table. I retrieved the data from disease_table from the DB and displayed on the listview and when the listitem is clicked, I have to select and display disease category symptoms accordingly and I did that successfully but my code has redundancy, I had to write two methods in the datahelper class to retrieve the symptoms as per the disease in another listview. and I am retrieving the symptom data in list view with the query with the condition of WHERE "disease_id=1" with foreign key reference
the code for the methods is as follows,
//getting pain symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,symptompain));
public List<String> getAllSymptomPain() {
List<String> symptompain = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=1", null, null, null, null);
if(null != cr){
symptompain = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptompain.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptompain;
}
//getting colorchange symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,symptomcolorchange));
public List<String> getAllSymptomColorChange() {
List<String> symptomcolorchange = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=2", null, null, null, null);
if(null != cr){
symptomcolorchange = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptomcolorchange.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptomcolorchange;
}
How can I write these two in a single method and then call it in class which extends listactivity under onListItemclick method?
And my OnListItemClick() method is as follows :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String item=(String)getListAdapter().getItem(position);
if(item.equals("Pain in Teeth")){
// passing the method here
}
else if(item.equals("Pain in Gums")){
// passing the method here
}
else if(item.equals("Pain in Mucosa")){
// passing the method here
}
else if(item.equals("Pain in TMJoint")){
// passing the method here
}
else if(item.equals("Non-Specific Pain")){
// passing the method here
}
}
Try this:
public List<String> getSymptomsByDiseaseId(long diseaseId) {
List<String> symptomsList = new ArrayList<String>();
String selection = "diseaseid=?";
String[] selectionArgs = { String.valueOf(diseaseId) };
Cursor cursor = db.query(false, SYMPTOM_TABLE_NAME, null, selection, selectionArgs, null, null, null, null);
if (cursor.moveToFirst()) {
do {
symptomsList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
return symptomsList;
}
Related
i am new to android, how to get phone numbers of selected contacts from MultiAutocompleteTextview when clicks on button ?
method to read contacts for multi-autocomplete textview
private void readContactData() {
// TODO Auto-generated method stub
String phoneNumber = "";
String phoneName = "";
phoneValueArr.clear();
nameValueArr.clear();
try{
ContentResolver content = getContentResolver();
cursor = content.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PEOPLE_PROJECTION, null, null, null);
if(null != cursor && cursor.moveToFirst()){
do{
// Get Phone number
phoneNumber =""+cursor.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneName = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
phoneValueArr.add(phoneNumber.toString());
nameValueArr.add(phoneName.toString());
}while(cursor.moveToNext());
}
//cursor.close();
}catch(Exception e){
Log.i("AutocompleteContacts","Exception : "+ e);
}finally {
//if (null != cursor)
//cursor.close();
}
ContactListAdapter adapter = new ContactListAdapter(this, cursor);
mAuto.setAdapter(adapter);
}
my ContactsListAdapter
public static class ContactListAdapter extends CursorAdapter implements Filterable {
public ContactListAdapter(Context context, Cursor c) {
super(context, c);
mContent = context.getContentResolver();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View retView = inflater.inflate(R.layout.schedule_msg_custcontview,parent,false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//((TextView) view).setText(cursor.getString(2));
TextView pname = (TextView)view.findViewById(R.id.ccontName);
TextView pnum = (TextView)view.findViewById(R.id.ccontNo);
pname.setText(cursor.getString(2));
pnum.setText(cursor.getString(1));
}
#Override
public String convertToString(Cursor cursor) {
return cursor.getString(2);
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (getFilterQueryProvider() != null) {
return getFilterQueryProvider().runQuery(constraint);
}
StringBuilder buffer = null;
String[] args = null;
if (constraint != null) {
buffer = new StringBuilder();
buffer.append("UPPER(");
buffer.append(ContactsContract.Contacts.DISPLAY_NAME);
buffer.append(") GLOB ?");
args = new String[] { constraint.toString().toUpperCase() + "*" };
}
return mContent.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PEOPLE_PROJECTION,
buffer == null ? null : buffer.toString(), args,
null);
}
private ContentResolver mContent;
}
private static final String[] PEOPLE_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.Contacts.DISPLAY_NAME,
};
and how can i get my selected contact numbers into an object to store in database while pressing the button. And while loading contacts its giving an exception saying that
12-11 12:39:11.422: I/AutocompleteContacts(17735): Exception : android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 188
can any one help me ?
This is my multi auto complete OnItemClick Listener and its always giving index of selected name index -1
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
// Get Array index value for selected name
int i = nameValueArr.indexOf(""+parent.getItemAtPosition(position));
// If name exist in name ArrayList
if (i >= 0) {
// Get Phone Number
toNumberValue = phoneValueArr.get(i);
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
// Show Alert
Toast.makeText(getBaseContext(), "Position:"+position+" Name:"+parent.getItemAtPosition(position)+" Number:"+toNumberValue,
Toast.LENGTH_LONG).show();
Log.d("AutocompleteContacts", "Position:"+position+" Name:"+parent.getItemAtPosition(position)+" Number:"+toNumberValue);
}
}
I solved the multi-autocomplete OnItemclickListener issue by changing the code as below
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView temp = (TextView) view.findViewById(R.id.ccontNo);
TextView temp2 = (TextView) view.findViewById(R.id.ccontName);
final String selectedNumber = temp.getText().toString();
final String selectedName = temp2.getText().toString();
if (selectedNumber != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
// Show Alert
Toast.makeText(getBaseContext(), " Name:"+selectedName+" Number:"+selectedNumber, Toast.LENGTH_LONG).show();
}
}
Now i am getting the selected contact name and number. Then store those values in HashMap and while button click split the selected contacts by "," and iterate the loop for each name to get the contact number.
In this way i solved my problem hope it is helpful !! if so up Vote the answer!!!
im a newbie to android and i have this problem here hope you guys can help me with this :)
anyways, i want to get the id of a selected item in the spinner from sqlite database so that i can save it to another table later on.
here's my code:
in my DB.java :
public List<String> getSemesterList() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SEMESTER;
Cursor c = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
List.add((c.getString(1)));
} while (c.moveToNext());
}
return List;
}
public String getSemesterId() {
String[] columns = new String[] { KEY_SEMESTER_ID, KEY_SEMESTER };
Cursor c = ourDatabase.query(TABLE_SEMESTER, columns, null, null, null, null, null, null);
int id = c.getColumnIndex(KEY_SEMESTER_ID);
String semId = "";
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
semId = semId + c.getInt(id) + " "
+ "\n";
}
return semId ;
}
and in my createSYAttended.class
// TODO Auto-generated method stub
DB entry = new DB(this);
entry.open();
final List<String> all = entry.getSemesterList();
if(all.size()>0) // check if list contains items.
{
sqlSem = (Spinner) findViewById(R.id.sprSemester);
arrayAdapter = new ArrayAdapter<String>(CreateSyAttended.this,android.R.layout.simple_spinner_dropdown_item, all);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sqlSem.setAdapter(arrayAdapter);
entry.close();
sqlSem.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
} }
use a mapping for the index of your List<String> all = entry.getSemesterList(); to the spinner item
so when you get below callback
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
you can then use the position you get in the callback to map to the item in the semesterList all
I have an External Database into assets folder. I have been successful into loading it on my Emulator and performing operations on it.
I also know how to fill data using queries in Spinner and ListView.
The main issue: I am running a query which gives me all data from the table. I store them in a Bean class. Now i have successfully filled one of the column data into a spinner.
BUT, when i open the spinner, i don't get Database values but object name into spinner
FOR e.g -- com.mypackageName.BeanPackage.BeanClass#411da123
I get the whole spinner full of this, not the Data which is in Database( e.g 13, 13/1) .
My Code :
Query in DBHelper Class :
public Cursor getBusNumbers() {
// date="21-10-2013";
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
return db.rawQuery("select * from table", null);
}
In My Main Activity :
Adapter code :
adapter = new Adapter(MainActivity.this,android.R.layout.simple_spinner_item, array);
route.setAdapter(adapter);
adapter.notifyDataSetChanged();
My GetView method:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(layout, null);
}
final Bean item = items.get(position);
final TextView km = (TextView) convertView
.findViewById(android.R.id.text1);
km.setText(item.getRouteNumber());
km.setTextSize(22);
return convertView;
}
}
Method which fills the Array :
private void loadFieldDatabase() {
Cursor c = dbhelper.getBusNumbers();
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int count = 0; count < c.getCount(); count++) {
Bean detail = new Bean();
detail.setRouteNumber(c.getString(c
.getColumnIndex("route_number")));
array.add(detail);
c.moveToNext();
}
c.close();
//dbhelper.close();
}
Here in your code your setting the Bean object into the Text view insted of which item you need to set that.
Try this code this may help you.
private void loadSpinnerCourse() {
// TODO Auto-generated method stub
List<String> lables = getAllCourse();
// Creating adapter for spinner
dataAdapterCourse = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapterCourse
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
mLesson_course.setAdapter(dataAdapterCourse);
}
private List<String> getAllCourse() {
// TODO Auto-generated method stub
List<String> labels = new ArrayList<String>();
mCoureseIdList = new ArrayList<String>();
ExamDatabaseConnector dbConnector = new ExamDatabaseConnector(
getActivity());
dbConnector.open();
String selectQuery = "SELECT * FROM courses_stud";
Cursor cursor = dbConnector.database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
mCoureseIdList.add(cursor.getString(0));
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
dbConnector.database.close();
// returning lables
return labels;
}
Cursor cursor = db.getAllBhashat();
SpinnerArr = new String[cursor.getCount()+1];
SpinnerArr[0] = "<-SELECT->";
if(cursor.moveToNext()){
int i = 1;
do {
SpinnerArr[i] = cursor.getString(cursor
.getColumnIndex("LocalityTitle_E"));
i++;
} while (cursor.moveToNext());
}if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
ArrayAdapter<String> adapter_sorCat = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, SpinnerArr);
Spinner.setAdapter(adapter_sorCat);
adapter_sorCat
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
I have retrieved data and successfully shown it in text view.
What do I have to modify in my code to make it look like a list view?
And also how do modify my listview programatically(adding size and padding)?
Here is a part of my DBclass in selecting the items that I've displayed
getFAData() {
// TODO Auto-generated method stub
String [] columns = new String[]{Row_Name};
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
String res = "";
int iRow = c.getColumnIndex(Row_Name);
//int iDesc = c.getColumnIndex(Row_Desc);
//int iID = c.getColumnIndex(Row_id);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
res = res + c.getString(iRow) + "\n";
}
return res;
}
And here is the class file:
public class FirstAid extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.firstaid);
displayresult();
}
public void displayresult (){
TextView tvFa = (TextView) findViewById(R.id.tvFA);
tvFa.setMovementMethod(new ScrollingMovementMethod());
DbHelper tblFa = new DbHelper(this);
tblFa.open();
String result = tblFa.getFAData();
tblFa.close();
tvFa.setText(result);
}
}
Create ArrayList int the get data function of database
public ArrayList<String> getFAData() {
ArrayList<String> comments = new ArrayList<String>();
Cursor c = ourDB.query(db_Table, columns, null, null, null, null, null);
int iRow = c.getColumnIndex(Row_Name);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
comments.add(c.getString(iRow ));
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
in your activity retrieve data like this.
ArrayList<String> array = new ArrayList<String>();
array = tblFa.getFAData();
you need to implement a method in your dbhelper class like this
public List<String> selectAll_data() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME_2, new String[] { "str" },
null , null, null, null, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
Now in your activity
List<String> events = dh.selectAll_data();
String[] arr = new String[events.size()];
arr = events.toArray(arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
If you want to see a real time example check this url
I am getting the from the database using cursor but when i am trying to show the data in list, it is not showing..
the below code is for accessing the data using cursor from database:
protected void showCustomerdetails() {
try
{
Cursor cursor = m_dbManager.getValues("customer", new String[]{"name","mobile_phone" }, null, null, null, null);
if(cursor != null)
{
cursor.moveToFirst();
int i = 0;
while(cursor.isAfterLast() == false)
{
m_uname = cursor.getString(cursor.getColumnIndex("name"));
Log.d("debug","getting the name from cursor");
m_mobnum = cursor.getString(cursor.getColumnIndex("mobile_phone"));
cursor.moveToNext();
i++;
}
}
cursor.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
now the below code is for adding the data in the list---
class IconicAdapter extends ArrayAdapter<String>
{
Activity context;
IconicAdapter(Activity context)
{
super(context, R.layout.custoemrs_list);
this.context=context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = null;
try
{
LayoutInflater inflater=context.getLayoutInflater();
row=inflater.inflate(R.layout.custoemrs_list, null);
TextView des=(TextView)row.findViewById(R.id.custusername);
des.setText(m_uname);
TextView qty=(TextView)row.findViewById(R.id.custmobnum);
qty.setText(m_mobnum);
}
catch(Exception e)
{
e.printStackTrace();
}
return row;
}
}
Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor))
You are iterating through the Cursor and setting the same variable over and over with a different value, until it finally reaches the end of the cursor.
Instead, you need to read it once per call in the getView() method.
look into this part:
while(cursor.isAfterLast() == false)
{
m_uname = cursor.getString(cursor.getColumnIndex("name")); // <-- BAD!
Log.d("debug","getting the name from cursor");
m_mobnum = cursor.getString(cursor.getColumnIndex("mobile_phone")); // <-- BAD!
cursor.moveToNext();
i++; // <-- UNUSED!
}
You are not using i for anything here. Rather, you are replacing the values of m_uname and m_mobnum constantly. A simple way to make it to work is to create a couple of ArrayList and do
ArrayList<String> m_uname = new ArrayList<String>();
//
while(cursor.isAfterLast() == false)
{
m_uname.add(cursor.getString(cursor.getColumnIndex("name")));
Log.d("debug","getting the name from cursor");
m_mobnum.add(cursor.getString(cursor.getColumnIndex("mobile_phone")));
cursor.moveToNext();
}
You would then use it as
des.setText(m_uname.get(position));