autocompletetextview not working - android

I have a contact list and when I want to make a search in my list I want to use an autocompletetext view but it is not working.
When I start typing in autocomplete text view nothing appears, but when I click on the search button it finds me the contact I want.
here is my .java:
public class Search extends ListActivity {
private static int[] TO = {R.id.rowid,R.id.name, R.id.mobilephone, R.id.email };
private static String[] FROM = {_ID,DbConstants.NAME, DbConstants.PHONE, DbConstants.EMAIL, };
private Button sButton;
private ListView lv1;
private static SQLiteDatabase db;
private DbCreate contacts;
private Cursor cursor;
private EditText searchText;
protected SimpleCursorAdapter adapter;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchText=(EditText)findViewById(R.id.searchtext);
sButton=(Button)findViewById(R.id.searchButton);
sButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
showDatabaseContent();
lv1 = getListView();
lv1.setTextFilterEnabled(true);
}
});
}
private Cursor getContacts() {
db = contacts.getReadableDatabase();
cursor = db.rawQuery("SELECT _id,name, phone, email FROM contactTest1 WHERE name LIKE ?",
new String[]{searchText.getText().toString()+"%"});
startManagingCursor(cursor);
return cursor;
}
public void showDatabaseContent(){
contacts = new DbCreate(this);
try {
cursor = getContacts();
showContacts(cursor);
} finally {
contacts.close();
db.close();
}
}
private void showContacts(Cursor cursor) {
//set up data binding
adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Intent abaintent = new Intent(this,Detalii.class);
Cursor cursor = (Cursor) adapter.getItem(position);
abaintent.putExtra("Contact_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(abaintent);
}
}
here is my search.xml:
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk//android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/searchtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="searchDefault" >
<requestFocus />
</AutoCompleteTextView>
<Button android:id="#+id/searchButton"
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Why do you have there
android:layout_weight="1"
?
I would remove it.

Related

how to getting strings from sqlite database to autocompletetextview

I am working on a sqlite database project on android. And it's my first sqlite project. I read lots of article and created my app but there's a problem that I can't find a way to solve it.i want to get NAME_FILTER table to autoCompleteTextView
here is my layout code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="#string/customers_name"
android:textSize="16sp" />
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"/>
<EditText
android:id="#+id/edt_filter_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:imeOptions="actionNext"
style="#style/EditText.Input"
android:theme="#style/EditText.Input"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20dp"
android:paddingBottom="20dp">
<Button
android:id="#+id/btn_submit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/btn_submit"
android:textColor="#333333"
android:background="#drawable/buttonshape"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textSize="18sp"
android:drawableStart="#drawable/ic_check_black_24dp"/>
<Button
android:id="#+id/btn_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/btn_cancel"
android:textColor="#333333"
android:background="#drawable/red_button_background"
android:textSize="18sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:drawableStart="#drawable/ic_cancel_black_24dp"/>
</LinearLayout>
</LinearLayout>
and here is my Activity
public class FiltersActivity extends AppCompatActivity implements ActionMode.Callback{
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
private static int Filter_list_position = -1;
private Button btnSubmit;
private Button btnCancel;
private ListView listView;
private FilterListAdapter adapter;
private EditText edtName;
private int seletcedFilterId;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.filters_title);
setContentView(R.layout.activity_filters);
btnCancel = (Button) findViewById(R.id.btn_cancel);
btnSubmit = (Button) findViewById(R.id.btn_submit);
edtName = (EditText) findViewById(R.id.edt_filter_name);
btnCancel.setOnClickListener(onCancelbuttonClicked);
listView = (ListView) findViewById(R.id.listView);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapterr = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, NAME_FILTER);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapterr);//setting the adapter data into the AutoCompleteTextView
refreshList();
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
DataBaseHelper Cllas
public class DatabaseHelper {
private SQLiteDatabase mydb;
public DatabaseHelper(Context context){
mydb = new MyDatabase(context).getWritableDatabase();
}
public void addNewFilter(filter filter){
ContentValues values = new ContentValues();
values.put("name", filter.getName());
mydb.insert(MyDatabase.tableFilters, null, values);
mydb.close();
}
public List<filter> getListOfFilters(){
Cursor c = mydb.rawQuery("select * from " + MyDatabase.tableFilters, null);
List<filter> filters = new ArrayList<>();
while (c.moveToNext()){
filter em = new filter();
em.setId(c.getInt(c.getColumnIndex(MyDatabase.ID_FILTER)));
em.setName(c.getString(c.getColumnIndex(MyDatabase.NAME_FILTER)));
filters.add(em);
}
c.close();
mydb.close();
return filters;
}
public void editFilter(filter filter){
ContentValues values = new ContentValues();
values.put("name", filter.getName());
mydb.update(MyDatabase.tableFilters, values, "id = " + filter.getId(), null);
mydb.close();
}
public void deleteFilter(filter filter){
mydb.delete(MyDatabase.tableFilters, "id = " + filter.getId(), null);
mydb.close();
}
public List<filter> searchFilterByName(String name){
Cursor c = mydb.rawQuery("select * from " + MyDatabase.tableFilters + " where name like '%" + name + "%'", null);
List<filter> filters = new ArrayList<>();
while (c.moveToNext()){
filter em = new filter();
em.setId(c.getInt(c.getColumnIndex(MyDatabase.ID_FILTER)));
em.setName(c.getString(c.getColumnIndex(MyDatabase.NAME_FILTER)));
filters.add(em);
}
c.close();
mydb.close();
return filters;
}
}
and this is my ListAdapter Class
class FilterListAdapter extends BaseAdapter {
private Context context;
private List<filter> filters;
FilterListAdapter(Context context, List<filter> filters){
this.context = context;
this.filters = filters;
}
#Override
public int getCount() {
return filters.size();
}
#Override
public Object getItem(int i) {
return filters.get(i);
}
#Override
public long getItemId(int i) {
return filters.get(i).getId();
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
View rowView = LayoutInflater.from(context).inflate(R.layout.filter_list_item, viewGroup, false);
TextView txtName = (TextView) rowView.findViewById(R.id.txt_filter_name);
txtName.setText(filters.get(position).getName());
return rowView;
}
}

Cant get id in custom listview

Main Activity
public class MainActivity extends AppCompatActivity {
Button b1,b2;
DBHelper mydb;
TextView id;
ListView listView;
SimpleCursorAdapter adapter;
String[] from = new String[] { mydb.ID,
mydb.NAME, mydb.ADDRESS };
int[] to = new int[] { R.id.id, R.id.name, R.id.address };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
Cursor cursor = mydb.fetch();
listView = (ListView) findViewById(R.id.listView);
adapter = new SimpleCursorAdapter(this, R.layout.list, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
id=(TextView) findViewById(R.id.id);
int id_To_Search = Integer.valueOf(id.getText().toString());
Bundle dataBundle = new Bundle();
dataBundle.putInt("_id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), AddPatient.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
Add class
if (extras != null) {
b2.setVisibility(View.INVISIBLE);
b3.setVisibility(View.VISIBLE);
b4.setVisibility(View.VISIBLE);
int Value = extras.getInt("_id");
if (Value > 0) {
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
name.setText(rs.getString(rs.getColumnIndex(DBHelper.NAME)));
address.setText(rs.getString(rs.getColumnIndex(DBHelper.ADDRESS)));
mobile.setText(rs.getString(rs.getColumnIndex(DBHelper.MOBILE)));
if(rs.getString(rs.getColumnIndex(DBHelper.GENDER)) != "female")
{
male.setChecked(true);
}
else
{
female.setChecked(true);
}
}
}
DBHelper
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery("select * from patients where _id=" + id + "", null);
}
Main.xml
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="65dp" />
list.xml
<TextView
android:id="#+id/id"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dp"
android:padding="3dp"
android:visibility="invisible" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:padding="3dp"
android:fontFamily="sans-serif"
android:textSize="18sp"
android:layout_toEndOf="#+id/id"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:padding="3dp"
android:visibility="visible"
android:layout_marginTop="25dp"
android:textSize="18sp"
android:layout_toEndOf="#+id/id"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
How can i get the id of the clicked list and show those details for edit in the next page.?How can i do it. Please help me. The next page is used to edit and delete purposes
You need to use the view to find view id for list elements.
Change below line in onItemClick()
id=(TextView) findViewById(R.id.id);
to
id=(TextView) arg1.findViewById(R.id.id);
you shouldn't rely on view id to access data.
you should have a separate model (let's say an ArrayList) containing the data shown in the listview. when the user select an item you grab the position of the item listed and pick the corresponding item in the array where you could find all information

Alphabet Index in ListView with SimpleCursorAdapter very slow

I am trying to implement the Alphabet-Index in ListView with SimpleCursorAdapter.
It is working but it is very slow, when i am trying to scroll the list up and down the phone is getting strucked. I think its is happening because of my way of coding due to lack of knowledge. so that I need to know what is the mistake or what is the wrong of this code. And also if there is any other way than this way, please let me know.
This is set of code of fragment which has the above problem.
public class EnFragment extends Fragment {
private TestAdapter dbHelper;
private myCursorAdapter dataAdapter;
public EnFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new TestAdapter(getContext());
dbHelper.createDatabase();
dbHelper.open();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_en, container, false);
setListView(view);
return view;
}
private void setListView(View view) {
Cursor cursor = dbHelper.getAllWord("enDic");
String[] columns = new String[]{
"word",
"definition",
"_id",
"favourite"
};
int[] to = new int[]{
R.id.txt_word,
R.id.txt_def,
R.id.txt_id
};
dataAdapter = new myCursorAdapter(
getContext(), en_word_row,
cursor,
columns,
to,
0);
Button btnSubmitEng = (Button) view.findViewById(R.id.btnSubmitEng);
final ListView listView = (ListView) view.findViewById(R.id.listView);
listView.setAdapter(dataAdapter);
listView.setEmptyView(btnSubmitEng);
listView.setFastScrollEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
final String word = cursor.getString(cursor.getColumnIndexOrThrow("word"));
Toast.makeText(getContext(), word, Toast.LENGTH_SHORT).show();
}
});
}
public void textSearch(String searchTxt){
String newStr = searchTxt.replace(" ","");
dataAdapter.getFilter().filter(newStr);
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.getWordByName("enDic",constraint.toString());
}
});
}
private class myCursorAdapter extends SimpleCursorAdapter implements SectionIndexer {
private final AlphabetIndexer mAlphabetIndexer;
public myCursorAdapter(Context context, int layout,
Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
mAlphabetIndexer = new AlphabetIndexer(c, 1, "අBCDEFGHIJKLMNOPQRSTUVWXYZ");
}
public View newView(Context _context, Cursor _cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(en_word_row, parent, false);
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
super.bindView(view, context, cursor);
final ImageButton imgFav = (ImageButton) view.findViewById(R.id.img_fav);
final String _id = cursor.getString(cursor.getColumnIndex("_id"));
final Integer fav = Integer
.valueOf(cursor.getString(cursor.getColumnIndex("favourite")));
if (fav == 1)
imgFav.setImageResource(R.drawable.fav_on);
else
imgFav.setImageResource(R.drawable.fav_off);
imgFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (dbHelper.isFavourite("enDic", _id)){
imgFav.setImageResource(R.drawable.fav_off);
dbHelper.favUpdate("enDic", _id,0);
}
else{
imgFav.setImageResource(R.drawable.fav_on);
dbHelper.favUpdate("enDic", _id,1);
}
}
});
}
#Override
public Object[] getSections() {
return mAlphabetIndexer.getSections();
}
#Override
public int getPositionForSection(int sectionIndex) {
return mAlphabetIndexer.getPositionForSection(sectionIndex);
}
#Override
public int getSectionForPosition(int position) {
return mAlphabetIndexer.getSectionForPosition(position);
}
}
}
fragment_en.xml (layout of the above fragment)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sldroid.mecdic_v21.fragment.EnFragment"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/transparent"
android:listSelector="#android:color/transparent"
android:scrollbarStyle="outsideOverlay"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit new word"
android:layout_marginTop="55dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:id="#+id/btnSubmitEng"/>
</LinearLayout>
en_word_row.xml
<LinearLayout
android:id="#+id/cardView"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:descendantFocusability="blocksDescendants">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false"
android:paddingLeft="20dp"
android:paddingRight="20dp">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="3"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="25dp"
android:orientation="horizontal">
<TextView
android:id="#+id/txt_word"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Word"
android:textSize="18dp"
android:textColor="#424242"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txt_def"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="definition"
android:textSize="10dp"
android:paddingTop="5dp"
android:paddingLeft="10dp"
android:textColor="#FF757575"
android:lines="1"/>
</LinearLayout>
<TextView
android:id="#+id/txt_id"
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="invisible"/>
</LinearLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.5">
<ImageButton
android:id="#+id/img_fav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/fav_off"
android:scaleType="centerInside"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
style="#style/Base.Widget.AppCompat.Button.Borderless"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
method of TestAdapter
public Cursor getAllWord(String table)
{
Cursor mCursor = mDb.query(table, new String[] {"_id","word","definition","favourite"},
null, null, null,null, " word COLLATE NOCASE");
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor getWordByName(String table, String inputText) throws SQLException {
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(table, new String[] {"_id","word","definition","favourite"},
null, null, null,null, " word COLLATE NOCASE");
}
else {
mCursor = mDb.query(true, table, new String[] {"_id","word","definition","favourite"},
"word" + " like '" + inputText + "%'", null,
null, null, " word COLLATE NOCASE",null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
GetAllWord and getWordByName should be called in the doInBackground method and in the postExecute you shoul update your adapter.
private class GetAllWord extends AsyncTask<Object, Object, Cursor> {
#Override
protected Cursor doInBackground(Object... params) {
return GetAllWord("your text");
}
#Override
protected void onPostExecute(Cursor result) {
if (result != null) {
//update the adapter with the result
}
}
}

how to add button in custom row listview i want to delete database selected entry in listview

xml for save database please help me to## i want add delete button in listview's each row when button is pressed delete that data from listview and database ##
here is first xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3CAE5"
android:orientation="vertical"
android:padding="5dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/frst_txtV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First name"
android:textColor="#000" />
<EditText
android:id="#+id/frst_editTxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/frst_txtV" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/lst_txtV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Last name"
android:textColor="#000" />
<EditText
android:id="#+id/last_editTxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/lst_txtV" />
</LinearLayout>
<Button
android:id="#+id/save_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Save"
android:textColor="#000" />
</LinearLayout>
display_activty.xml list view xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B58897"
android:gravity="center_horizontal" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="Add" />
<View
android:id="#+id/a"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/btnAdd"
android:background="#8DB3E1" />
<ListView
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/a"
android:divider="#8DB3E1"
android:dividerHeight="2dp" />
</RelativeLayout>
displayadapter.java here i add button if i press button than record is will delete from database as well from listview
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private SQLiteDatabase dataBase;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.btn = (Button) child.findViewById(R.id.Button1);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
}
});
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
Button btn;
//ImageView img;
}
}
listcell.xml this is to display custom listview xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3CAE5"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp" >
<TextView
android:id="#+id/txt_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
<TextView
android:id="#+id/txt_fName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<TextView
android:id="#+id/txt_lName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<Button android:text="Button"
android:id="#+id/Button1"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
DisplayActivty.java here is listview adding class
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Addactivty.java add database class
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
edit_first.setText(fname);
edit_last.setText(lname);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
if(fname.length()>0 && lname.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
Create Custom Array Adapter like this
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.inflatelistview, null);
TextView text=(TextView)vi.findViewById(R.id.textView1);
ImageView image=(ImageView)vi.findViewById(R.id.imageView1);
Button btn=(Button)vi.findViewById(R.id.button1);
btn.setTag(position);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
//items.remove(index.intValue());
data.remove(position);
notifyDataSetChanged();
}
});
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
As you're inserting (Addactivty.java add database class) and fetching (DisplayActivty.java here is listview adding class) data from database similarly you can delete.
For example :
public static boolean Delete(Context context, int id) {
SQLiteDatabase db = new MyDataBase(context).getWritableDatabase();
int res = db.delete(CATEGORY, ID + " = " + id, null);
if (db.isOpen())
db.close();
return (res == 0 ? false : true);
}
You need to delete data from database and listView inside the click listener,like :
mHolder.btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
//1. get the clicked item's *ID*
// (as you did id.get(pos), in your adapter class).
//2. delete data from database using this *ID*.
// (see above function).
//3. remove position from your list.
// list.remove(position);
// (in your case you've multiple lists remove position from all)
//4. notifyDataSetChanged();
}
});
Helping link :
notifyDataSetChanged();
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.

Android listView - format specific items

So I'm relatively new to android programming, and currently working on a custom listView. What I'm trying to achieve is the following:
Retrieve a list of articles from a database.
Get all unique values from the 'category' column to create a list of
categories.
Populate a listView with these categories
Add a listener for each category click which takes the user to the
first article in that category.
I've managed to do all of the above, but now want to take it further. I have a status column in the database, where the value is either 'read' or 'unread'. What I want to do is the following:
If all articles in a category are 'read', to grey-out that category
in the listview, and to ignore clicks on that particular item.
I have absolutely no idea how to format individual items within a listview...any suggestions? My code is as follows:
start.java:
public class Start extends Activity {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
public static final String MYDATABASE_NAME = "questions.db";
public static final String MYDATABASE_TABLE = "questions";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT = "category";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
// Query database
SQLiteDatabase db;
db = openOrCreateDatabase(
"questions.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
ArrayList<String> categoryList = new ArrayList<String>();
Cursor cur = db.query("questions", null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
if (categoryList.contains(cur.getString(11))) {
// do nothing
} else {
// add to list
categoryList.add(cur.getString(11));
}
cur.moveToNext();
}
cur.close();
Collections.sort(categoryList);
categoryList.add(0, "All");
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// Create ArrayAdapter using the category list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, categoryList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
mainListView.setTextFilterEnabled(true);
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
String clickedCat = (String) mainListView.getItemAtPosition(position);
finish();
Intent myIntent = new Intent(getApplicationContext(), NextClass.class);
myIntent.putExtra("passedCategory", clickedCat);
myIntent.putExtra("startTrigger", "go");
startActivity(myIntent);
}
});
}
}
start.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/black">
<TextView
android:text="#string/categories"
android:layout_width="fill_parent"
android:layout_height="#dimen/topbar_container"
android:background="#drawable/topgradient"
android:gravity="center_vertical|center_horizontal"
android:textColor="#color/primarytext"
android:textSize="#dimen/topbar_font"
android:textStyle="bold"
android:shadowColor="#000000"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="2"></TextView>
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainListView"></ListView>
</LinearLayout>
simplerow.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" android:textStyle="bold">
</TextView>
You need to set up a ViewBinder, then call listAdapter.setViewBinder.
You need to create a custom adapter for this:
CustomAdapter.class:
public class CustomAdapter extends SimpleCursorAdapter{
Cursor dataCursor;
LayoutInflater mInflater;
Context context;
ArrayList<String[]> arrayList;
public static HashMap<Integer,String> myList=new HashMap<Integer,String>();
public CustomAdapter(Context context, int layout, Cursor dataCursor, String[] from,
int[] to) {
super(context, layout, dataCursor, from, to);
this.context=context;
this.dataCursor = dataCursor;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.custom_listitem, null);
holder = new ViewHolder();
holder.textview=(TextView)convertView.findViewById(R.id.textview);
holder.layout=(LinearLayout)findViewById(R.id.layout);
convertView.setTag(holder);
}
else
{
holder=(ViewHolder)convertView.getTag();
}
dataCursor.moveToPosition(position);
String id=Integer.toString(dataCursor.getInt(dataCursor.getColumnIndexOrThrow("_id")));
myList.put(position, id);
holder.textview.setText(dataCursor.getString(11));
if(dataCursor.getString(dataCursor.getColumnIndex("index")).equals("read"))
{
holder.layout.setBackgroundColor(Color.GRAY);
}
// other code according to the functionality you want
return convertView;
}
static class ViewHolder
{
TextView textview;
LinearLayout layout;
}
}
custom_listitem.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="#+id/layout"
android:padding="5dip"
>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:gravity="left"
android:padding="5dip"
android:id="#+id/textview"
/>
</LinearLayout>
Now,use it in activity like:
MainActivity.class:
...
mainListView = (ListView) findViewById( R.id.mainListView );
Cursor cursor = db.query("questions", null, null, null, null, null, null);
CustomAdapter ca=new CustomsAdapter(context,R.layout.custom_listitem,cursor,new String[]{"id","index"},new int[]{R.id.textview,R.id.textview});
mainListView.setAdapter(ca);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
String id=CustomAdapter.myList.get(position);
Cursor findIndex=db.query("questions", null, "_id="+id, null, null, null, null);
findIndex.moveToFirst();
if(findIndex.getString(findIndex.getColumnIndex("index").equals("unread"))
{
// do something for "unread" categories
}
}
});
...
I don't know the way,you can disable click on a particular listitem but yes,you can do the stuff under certain condition to let user feel like some of the items are unclickable.

Categories

Resources