autocompletetextview filter dropdown data - android

I have created custom autocompletetextview component.In that I have also created a populateList method for autocompletetext data.
final com.example.admin.ctronhot.autocomleteclass autocomplete=(com.example.admin.ctronhot.autocomleteclass)findViewById(R.id.abc);
final String sql="select * from g101 where desc LIKE '%" + autocomplete.getText().toString() + "%'";
final String[] mfieldsa=new String[]{"desc"};
final int[] mobjectsa=new int[]{R.id.desc};
autocomplete.populateList(R.layout.brow_g101_layout, sql, "desc", aa, mfieldsa, mobjectsa, order.this);
It is showing drop down data but it is not filtering data as per typed in autocomplete.getText.toString()
Here is my function populateList
public void populateList(Integer _layoutfile, final String sqlaa, String mfieldget, com.example.admin.ctronhot.autocomleteclass mauto,
String[] mfields, int[] mobjects, Context mcontext) {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(co.mcurd_data_path_, null);
Cursor cursor = db.rawQuery(sqlaa null);
int layoutResourceId = 0;
final SimpleCursorAdapter adapter = new SimpeCursorAdapter(
mcontext, // Context
_layoutfile, // Row layout template
cursor, // cursor (set of DB records to map)
mfields, // DB Column names
mobjects // View IDs to put information in
, layoutResourceId
);
adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
#Override
public CharSequence convertToString(Cursor cursor) {
final int colIndex = cursor.getColumnIndexOrThrow("desc");
return cursor.getString(colIndex);
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence description) {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(co.mcurd_data_path_, null);
Cursor managedCursor = db.rawQuery(sqlaa, null);
return managedCursor;
}
});
mauto.setThreshold(1);
mauto.setAdapter(adapter);
}
Please help Me.
Thanks in advance.

Related

Get and select contacts in android

I'm trying get all contacts and select it.
I completed get all contacts in my phone. But when i try to select a few contacts and get their names or numbers, I faced nullpointer error.
public class ContactListFragment extends ListFragment implements LoaderCallbacks<Cursor> {
private CursorAdapter mAdapter;
final HashMap<String,String> hashMap = new HashMap<String,String>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private Uri uriContact;
private String contactID;
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create adapter once
Context context = getActivity();
int layout = android.R.layout.simple_list_item_multiple_choice;
Cursor c = null; // there is no cursor yet
int flags = 0; // no auto-requery! Loader requeries.
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// each time we are started use our listadapter
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// and tell loader manager to start loading
getLoaderManager().initLoader(0, null, this);
***getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursorID = getActivity().getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(contactID);
}
});
}***
// columns requested from the database
private static final String[] PROJECTION = {
Contacts._ID, // _ID is always required
Contacts.DISPLAY_NAME_PRIMARY // that's what we want to display
};
// and name should be displayed in the text1 textview in item layout
private static final String[] FROM = { Contacts.DISPLAY_NAME_PRIMARY };
private static final int[] TO = { android.R.id.text1 };
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Once cursor is loaded, give it to adapter
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// on reset take any old cursor away
mAdapter.swapCursor(null);
}
I think problem is my onItemClickListener.
How can i fix this?
Thanks from now :)
The main problem is that uriContact is null when you make the query.
The other problem is that you are only using ContactsContract.Contacts._ID as the projection, so the ID is the only thing returned.
I got it working by using null for the projection so that it returns all rows.
I also added functionality to find the currently selected contact, and display a Toast with their phone number.
This is not optimal code, since it just queries all rows and then iterates through them until it finds the currently selected contact, but it works:
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cur = mAdapter.getCursor();
cur.moveToPosition(position);
String curName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
System.out.println(curName);
uriContact = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursorID = getContentResolver().query(uriContact,
null,
null, null, null);
for (cursorID.moveToFirst(); !cursorID.isAfterLast(); cursorID.moveToNext() ) {
String testName = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
if (testName != null && testName.equals(curName)) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
if (contactID != null) {
System.out.println(contactID);
Toast.makeText(MainActivity.this, "contact Phone: " + contactID, Toast.LENGTH_LONG).show();
}
}
});
Edit: I got a more optimized version working, which uses the selection and selectionArgs in the query to return just the current contact info:
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cur = mAdapter.getCursor();
cur.moveToPosition(position);
String curName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
System.out.println(curName);
uriContact = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursorID = getContentResolver().query(uriContact,
null,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " = ?", new String[]{curName}, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
if (contactID != null) {
System.out.println(contactID);
Toast.makeText(MainActivity.this, "contact Phone: " + contactID, Toast.LENGTH_LONG).show();
}
}
});

Reapeated columns using setFilterQueryProvider

I have a listview with a problem. I want to implement the classic search with the edittext, i am using the addTextChangedListener with TextWatcher(). The Listview gets the elements from a database so I use cursor and simplecursoradapter so i have to use the setFilterQueryProvider. The problem appears when I write something in the edittext, if I write the name of a product it changes all the names of the elements in the list.So i dont know what to do. Appreciate the help.
here is my java code with the listview:
public class Lista_general extends ListActivity {
SimpleCursorAdapter adapter;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_general);
list = getListView();
EditText edit =(EditText)findViewById(R.id.edit);
// open database
AdminSQLiteOpenHelper dbhelper = new AdminSQLiteOpenHelper(
getBaseContext());
SQLiteDatabase db = dbhelper.getReadableDatabase();
// array for SimpleCursorAdapter
String columns[] = new String[] { "PRODUCTO._id",
"nombre","category","CATEGORIAS._id","categoryid" };
String orderBy = "category";
// query database
Cursor c = db.query("PRODUCTO, CATEGORIAS WHERE CATEGORIAS._id = categoryid ",
columns,null,null, null, null, orderBy);
c.moveToFirst();
// array for SimpleCursorAdapter
String from[] = new String[] { "nombre", "category", };
//String from[] = new String[] { "nombre", "categoria", };
int to[] = new int[] { R.id.name, R.id.cate, };
// Adapter
adapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.productos, c, from, to,
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
list.setTextFilterEnabled(true);
//Listener edit text
edit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
adapter.getFilter().filter(s.toString());
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
// TODO Auto-generated method stub
AdminSQLiteOpenHelper dbhelper = new AdminSQLiteOpenHelper(
getBaseContext());
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor mCursor = null;
if (constraint == null || constraint.length () == 0) {
mCursor = db.query("PRODUCTO, CATEGORIAS", new String[] {
"PRODUCTO._id", "nombre","CATEGORIAS._id","category"},
null, null, null, null, null);
}
else {
mCursor = db.query(true,"PRODUCTO, CATEGORIAS", new String[]
{"PRODUCTO._id", "nombre", "category","CATEGORIAS._id"},
"nombre" + " like '%" + constraint + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
});
}
Here is a visual of my error:
first my normal list:
http://i40.tinypic.com/2111k0p.png
after I wrote:
http://i44.tinypic.com/23j04kg.png
It looks like the queries generated in the FilterQueryProvider are not joining the tables properly, so that you end up with every possible combination of PRODUCTO and CATEGORIAS (which are then filtered by PRODUCTO.nombre to give the impression that all the names have changed).
There's also a potential security risk with inserting constraint directly into the query, this opens the door to SQL injection attacks. I'm not sure how serious this is in the context of Android apps, but in for example a PHP web application this would allow anyone to execute any SQL they wished by entering a carefully crafted constraint.
From the answers to this question it looks like a rawQuery() call is needed in order to use SQL JOIN so I would change your queries as follows...
For querying with no filter (i.e. in onCreate(); and in runQuery() where there is no constraint):
cursor = db.rawQuery("SELECT PRODUCTO._id, nombre, category, CATEGORIAS._id FROM PRODUCTO INNER JOIN CATEGORIAS ON PRODUCTO.categoryid = CATEGORIAS._id", null);
For querying with a filter:
String[] params = { constraint.toString() };
cursor = db.rawQuery("SELECT PRODUCTO._id, nombre, category, CATEGORIAS._id FROM PRODUCTO INNER JOIN CATEGORIAS ON PRODUCTO.categoryid = CATEGORIAS._id WHERE nombre LIKE ('%' || ? || '%')", params);

display data from sqlite according to value

i need your help, i did display data in a list view but the problem is that i
want the data to be according to a specific value, that means if the id = 1, only the rows
concerned will be displayed, if you have any suggestions i would be very thankful :
here the code of :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
String[] databaseColumnNames = new String[] { DBAdapter.col_region, };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
And my DBAdapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id, col_region,
}, null, null, null,
null, null);
}
list.setAdapter(myCursordapter);
} }
As you may check in query documentation, function accepts a selection and selectionArgs parameters, corresponding to SQL WHERE clause.
So, to make a query limited to a specific id, just use:
db.query(MENAGE, new String[] { _id, col_region}, "id = ?", new String[] {_id}, null, null, null);

Android - Custom AutoCompleteTextView CursorAdaptor - Suggestion Behavior

I am trying to implement a custom AutoCompleteTextView for choosing a contact's phone number from a list of suggestions that display the contact name, phone number type, and phone number. I created a custom CursorAdapter that defines and sets my Layout and TextViews for each suggestion and queries contacts based on the user-entered text via runQueryOnBackgroundThread. I'm running into an issue where the suggestions seem correct for the first two values entered (e.g. "ab" suggests "abcd" and "abyz") but not for anything beyond that (e.g. "abc" suggests "abyz"). For the latter, when the "abyz" suggestion is selected, the values for "abcd" are returned.
Code for the main activity:
final ContactInfo cont = new ContactInfo(ctx);
Cursor contacts = cont.getContacts2(null);
startManagingCursor(contacts);
ContactsAutoCompleteCursorAdapter adapter = new ContactsAutoCompleteCursorAdapter(this, contacts);
mPersonText.setAdapter(adapter);
mPersonText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Cursor cursor = (Cursor) arg0.getItemAtPosition(arg2);
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
mPersonNum.setText(number);
}
});
Code for my contacts class that returns a cursor for all contacts:
public Cursor getContacts2(String where)
{
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = ctx.getContentResolver().query(uri, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
return people;
}
Code for my CursorAdapter:
public class ContactsAutoCompleteCursorAdapter extends CursorAdapter implements Filterable {
private TextView mName, mType, mNumber;
private ContentResolver mContent;
public ContactsAutoCompleteCursorAdapter(Context context, Cursor c) {
super(context, c);
mContent = context.getContentResolver();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater mInflater = LayoutInflater.from(context);
final View ret = mInflater.inflate(R.layout.contacts_auto_list, null);
mName = (TextView) ret.findViewById(R.id.name);
mType = (TextView) ret.findViewById(R.id.phonetype);
mNumber = (TextView) ret.findViewById(R.id.phonenum);
return ret;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int numberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name = cursor.getString(nameIdx);
int type = cursor.getInt(typeIdx);
String number = cursor.getString(numberIdx);
mName.setText(name);
if (type == 1) {mType.setText("Home");}
else if (type == 2) {mType.setText("Mobile");}
else if (type == 3) {mType.setText("Work");}
else {mType.setText("Other");}
mNumber.setText(number);
}
#Override
public String convertToString(Cursor cursor) {
int nameCol = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = cursor.getString(nameCol);
return name;
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
// this is how you query for suggestions
// notice it is just a StringBuilder building the WHERE clause of a cursor which is the used to query for results
if (getFilterQueryProvider() != null) { return getFilterQueryProvider().runQuery(constraint); }
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER};
return mContent.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
"UPPER(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") LIKE '" + constraint.toString().toUpperCase() + "%'", null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
}
As I said above, when the user enters "ab" into the AutoCompleteTextView the suggestions are "abcd" and "abyz", however when the user types "abc" the suggestion is just "abyz". When the user selects "abyz" in that case, the values for "abcd" are returned. Here are two screenshots that show what I'm trying to describe:
I've read every question I could find here and elsewhere but can't seem to figure this out. I'm fairly new to Android development so I apologize in advance if my mistake is a simple one. Thanks in advance!
I seem to have answered my own question after more research. Moving the setting of the views for my textViews from the newView function to the bindView function seems to have done the trick, which I think makes sense...
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater mInflater = LayoutInflater.from(context);
final View ret = mInflater.inflate(R.layout.contacts_auto_list, null);
return ret;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int numberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name = cursor.getString(nameIdx);
int type = cursor.getInt(typeIdx);
String number = cursor.getString(numberIdx);
mName = (TextView) view.findViewById(R.id.name);
mType = (TextView) view.findViewById(R.id.phonetype);
mNumber = (TextView) view.findViewById(R.id.phonenum);
mName.setText(name);
if (type == 1) {mType.setText("Home");}
else if (type == 2) {mType.setText("Mobile");}
else if (type == 3) {mType.setText("Work");}
else {mType.setText("Other");}
mNumber.setText(number);
}
you have already public Cursor runQueryOnBackgroundThread function in your adapter so you do not need call second time cursor in activity
you do not need to use getContacts2 function
Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_send);
Cursor contacts = null;
mAdapter= new ContactsAutoCompleteCursorAdapter(this, contacts);
mTxtPhoneNo = (AutoCompleteTextView) findViewById(R.id.mmWhoNo);
mTxtPhoneNo.setAdapter(mAdapter);
mTxtPhoneNo.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Cursor cursor = (Cursor) arg0.getItemAtPosition(arg2);
String number = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
mTxtPhoneNo.setText(number);
}
});
}
Adapter
public class ContactsAutoCompleteCursorAdapter extends CursorAdapter implements Filterable {
private TextView mName, mType, mNumber;
private ContentResolver mContent;
public ContactsAutoCompleteCursorAdapter(Context context, Cursor c) {
super(context, c);
mContent = context.getContentResolver();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater mInflater = LayoutInflater.from(context);
final View ret = mInflater.inflate(R.layout.custcontview, null);
return ret;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int numberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name = cursor.getString(nameIdx);
int type = cursor.getInt(typeIdx);
String number = cursor.getString(numberIdx);
mName = (TextView) view.findViewById(R.id.ccontName);
mType = (TextView) view.findViewById(R.id.ccontType);
mNumber = (TextView) view.findViewById(R.id.ccontNo);
mName.setText(name);
if (type == 1) {mType.setText("Home");}
else if (type == 2) {mType.setText("Mobile");}
else if (type == 3) {mType.setText("Work");}
else {mType.setText("Other");}
mNumber.setText(number);
}
#Override
public String convertToString(Cursor cursor) {
int nameCol = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = cursor.getString(nameCol);
return name;
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
// this is how you query for suggestions
// notice it is just a StringBuilder building the WHERE clause of a cursor which is the used to query for results
if (constraint==null)
return null;
if (getFilterQueryProvider() != null) { return getFilterQueryProvider().runQuery(constraint); }
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER};
return mContent.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
"UPPER(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") LIKE '%" + constraint.toString().toUpperCase() + "%' or UPPER(" + ContactsContract.CommonDataKinds.Phone.NUMBER + ") LIKE '%" + constraint.toString().toUpperCase() + "%' ", null,
ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
}
i also add query for phone number search in query

Null Pointer Exception while Retriving Data from Sqlite

I am retrieving data from sqlite to base adapter by cursor.
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
String[] v0 = new String[] { tes0 };
String[] v01 = new String[] { tes1 };
String[] v02 = new String[] { tes2 };
String[] v03 = new String[] { tes3 };
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}
Then, Adapter_listView.java
public class Adapter_ListView extends BaseAdapter {
private int count;
private Context context;
private String[] string1;
private String[] string2;
private String[] string3;
private String con1;
private String con2;
private String con3;
public Adapter_ListView(Context baseContext, String[] v01, String[] v02, String[] v03, int theTotal) {
this.count = theTotal;
this.context = baseContext;
this.string1 = v01;
this.string2 = v02;
this.string3 = v03;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup arg2) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
contentView = inflater.inflate(R.layout.layout_inflate_list2, null);
TextView title = (TextView)contentView.findViewById(R.id.inflate_title);
TextView body = (TextView)contentView.findViewById(R.id.inflate_body);
TextView sub = (TextView)contentView.findViewById(R.id.inflate_sub);
title.setText(string1[position]);
body.setText(string2[position]);
sub.setText(string3[position]);
return contentView;
}
}
from this code always error --> ArrayOuOfBound if execute this code
title.setText(string1[position]);
how i can solve it?
You need to open your database in the activity you retrieve or insert data into your SQLite database. Also make sure you close it when your finished.
final DatabaseHelper m = new DatabaseHelper(this);
m.open();
In your onDestroy or pause. Call
m.close();
This may be the issue, because i dont see where you open your database in the code.
EDIT :
In your DatabaseHelper class. Create a method.
public void open(){
db.open();
}
public void close(){
db.close()
}
Then you will have the method to close and open the database in your activities where you need to insert and retrieve information.
To retrive data from cursor, first you must go to first row data in cursor.
Some code like this:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
...
}
good luck!! :D
It seems you want to load resultset into list, if so please change your code to set adapter outside of loop:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
int theTotal=c.getCount();
String[] v0 = new String[theTotal];
String[] v01 = new String[theTotal];
String[] v02 = new String[theTotal];
String[] v03 = new String[theTotal];
int i=0;
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i] =tes0 ;
v01[i] = tes1 ;
v02[i] = tes2 ;
v03[i] = tes3 ;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
Try this:
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if(c.getCount()>0)
{
int i=0;
int clength=c.getCount();
String[] v0=new String[clength];
String[] v1=new String[clength];
String[] v2=new String[clength];
String[] v3=new String[clength];
while (c.moveToNext())
{
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i]=tes0;
v01[i]=tes1;
v01[i]=tes2;
v01[i]=tes3;
i++;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}

Categories

Resources