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;
}
}
Related
i fill listview with data from local sqlite database. from my current query I want to get the foodname and protein, have set it in the Textview , adapter and query to get this data, but it only return only the name not the protein.
Here is the adapter class:
public class Db_listView_Adapter extends CursorAdapter {
public Db_listView_Adapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.db_list, viewGroup, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView foodName = (TextView) view.findViewById(R.id.foodNameInListView);
TextView foodProtein = (TextView) view.findViewById(R.id.foodProteinInListView);
TextView foodCarbs = (TextView) view.findViewById(R.id.foodCarbsInListView);
TextView foodFat = (TextView) view.findViewById(R.id.foodFatsInListView);
TextView foodCalories = (TextView) view.findViewById(R.id.foodCaloriesInListView);
TextView foodFibers = (TextView) view.findViewById(R.id.foodFibersInListView);
TextView foodVitA = (TextView) view.findViewById(R.id.foodVitAInListView);
TextView foodVitB = (TextView) view.findViewById(R.id.foodVitBInListView);
TextView foodCalcium = (TextView) view.findViewById(R.id.foodCalciumInListView);
TextView foodMagnesium = (TextView) view.findViewById(R.id.foodMagnesiumInListView);
String foodNameString = cursor.getString(cursor.getColumnIndexOrThrow("_FoodName"));
String foodProteinString = cursor.getString(cursor.getColumnIndexOrThrow("_FoodProtein"));
foodName.setText(foodNameString);
foodProtein.setText(foodProteinString);
}
}
Here is the xml for the layout of the listview:
<?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="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/foodNameInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodProteinInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodCarbsInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodFatsInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodCaloriesInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodFibersInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodVitAInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodVitBInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodCalciumInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/foodMagnesiumInListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Here I try to get the data from the database and fill the listview:
public class Db_fragment extends Fragment {
View view;
ListView listView;
Db_listView_Adapter db_listView_adapter;
public Db_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.db_fragment, container, false);
listView = (ListView) view.findViewById(R.id.dbView);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final MyDatabaseOpenHelper mDbHelper = new MyDatabaseOpenHelper(view.getContext());
final EditText foodName = (EditText) view.findViewById(R.id.nameForDb);
Button enterData = (Button) view.findViewById(R.id.enterData);
Button showData = (Button) view.findViewById(R.id.showData);
final TextView errorTextNameMissing = (TextView) view.findViewById(R.id.errorTextNameMissing);
showData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (foodName.getText().toString().trim().length() != 0) {
errorTextNameMissing.setText("");
SQLiteDatabase myDb = mDbHelper.getReadableDatabase();
String[] projection = {TableFoodMacros.FoodMacros._ID, TableFoodMacros.FoodMacros.FOOD_NAME, TableFoodMacros.FoodMacros.FOOD_PROTEIN};
String rawQuery = "SELECT _ID, _Foodname , _FoodProtein FROM FoodMacros where _FoodName = " + "'" + foodName.getText().toString() + "'";
Cursor c = myDb.rawQuery(rawQuery, null);
if(c.getCount() == 0){
Intent goToSaveFood = new Intent(getActivity(),Save_Food.class);
goToSaveFood.putExtra("FoodName", foodName.getText().toString());
myDb.close();
startActivity(goToSaveFood);
}else {
db_listView_adapter = new Db_listView_Adapter(view.getContext(), c);
listView.setAdapter(db_listView_adapter);
myDb.close();
}
} else {
errorTextNameMissing.setText(getResources().getString(R.string.errorTextNameMissing));
}
}
});
}
}
So i found that the problem was in the activity that add data in the DB, i was doing in onCreate instead of onClick... ;x
I'm working with Java and XML in Android Studio to populate a ListView with CursorAdapter. I'm kinda new to this and trying to solv a problem. I'm really green so any tips would also help.
My DBHandler looks like that:
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 10;
private static final String DATABASE_NAME = "jogging.db";
public static final String TABLE_TRIP = "Trip";
public static final String TUR_COLUMN_ID = "_id";
public static final String TUR_COLUMN_DISTANCE = "Ditance";
public static final String TUR_COLUMN_SCORE = "Fastest";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TRIP + "(" +
TUR_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TUR_COLUMN_DISTANCE + " TEXT, " +
TUR_COLUMN_SCORE + " TEXT " +
");";
db.execSQL(query);
}
CursorAdapter I'm trying to use to get data to ListView:
public class TripCursorAdapter extends CursorAdapter {
public TripCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.content_trips, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tripId = (TextView) view.findViewById(R.id.tripIdView);
TextView tripDistance = (TextView) view.findViewById(R.id.tripDistanceView);
TextView tripScore = (TextView) view.findViewById(R.id.tripScoreView);
String id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String distance = cursor.getString(cursor.getColumnIndexOrThrow("Ditance"));
String score = cursor.getString(cursor.getColumnIndexOrThrow("Fastest"));
tripId.setText(id);
tripDistance.setText(distance);
tripScore.setText(score);
}
And the activity to set up ListView
public class TripsActivity extends AppCompatActivity {
DBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trips);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbHandler = new DBHandler(this);
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor tripCursor = db.rawQuery("SELECT * FROM Trip", null );
ListView lvItems = (ListView) findViewById(R.id.listView);
TripCursorAdapter tripAdapter = new TripCursorAdapter(this, tripCursor, 0);
lvItems.setAdapter(tripAdapter);
}
XML Files:
trips_content.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="hmk.fitness_app.TripsActivity"
tools:showIn="#layout/activity_trips">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
And I have also item_trip.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:id="#+id/tripIdView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distance"
android:id="#+id/tripDistanceView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:id="#+id/tripScoreView"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
Not quite sure why I get error msg about null object referances. Any tips what I should do?
Change
return LayoutInflater.from(context).inflate(R.layout.content_trips, parent, false);
to
return LayoutInflater.from(context).inflate(R.layout.item_trip, parent, false);
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.
I have a SQLite Database connection to my application, I have followed a Tutorial and that tutorial show the database in a SimpleCursorAdapter, this does the whole class to this adapter and my buttons can not fit in this class.
I would therefore reduce this adapter to to fit with my buttons.
Or is there any other better solution?
For me the SimpleCursorAdapter Mix all my pictures an button to his adapter,
I dont know but i think that the SCadapter makes the whole view into a list view and i dont want that.
I have four classes.
DBAdapter,
Produkter (View)
Car is the SimpleCursorAdapter ViewBinder
and Bus is the Bitmap get, class
enter code here
public class DBhelper {
public static final String KEY_ID = BaseColumns._ID;
public static final String KEY_NAME = "name";
public static final String KEY_KCAL = "kcal";
public static final String KEY_VC = "vitaminc";
public static final String KEY_IMG = "image";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "FruitDB";
private static final int DATABASE_VERSION = 1;
public static final String FRUITS_TABLE = "fruits";
private static final String CREATE_FRUITS_TABLE = "create table "+FRUITS_TABLE+" ("
+KEY_ID+" integer primary key autoincrement, "
+KEY_IMG+" blob not null, "
+KEY_NAME+" text not null unique, "
+KEY_KCAL+" integer not null, "
+KEY_VC+" integer not null);";
private final Context mCtx;
private boolean opened = false;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_FRUITS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+FRUITS_TABLE);
onCreate(db);
}
}
public void Reset() {
openDB();
mDbHelper.onUpgrade(this.mDb, 1, 1);
closeDB();
}
public DBhelper(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}
private SQLiteDatabase openDB() {
if(!opened)
mDb = mDbHelper.getWritableDatabase();
opened = true;
return mDb;
}
public SQLiteDatabase getHandle() { return openDB(); }
private void closeDB() {
if(opened)
mDbHelper.close();
opened = false;
}
public void createFruitEntry(Bus fruit) {
openDB();
ByteArrayOutputStream out = new ByteArrayOutputStream();
fruit.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
ContentValues cv = new ContentValues();
cv.put(KEY_IMG, out.toByteArray());
cv.put(KEY_NAME, fruit.getName());
cv.put(KEY_KCAL, fruit.getKcal());
cv.put(KEY_VC, fruit.getVitaminC());
mDb.insert(FRUITS_TABLE, null, cv);
closeDB();
}
} enter code here
public class produkter extends ListActivity {
private DBhelper mDB;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDB = new DBhelper(this);
mDB.Reset();
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
mDB.createFruitEntry(new Bus(img, "Banane", 92, 10));
mDB.createFruitEntry(new Bus(img, "Kiwi", 56, 71));
mDB.createFruitEntry(new Bus(img, "Pfirsich", 41, 10));
mDB.createFruitEntry(new Bus(img, "Zitrone", 40, 51));
String[] columns = {mDB.KEY_ID, mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_KCAL,
mDB.KEY_VC};
String table = mDB.FRUITS_TABLE;
Cursor c = mDB.getHandle().query(table, columns, null, null, null, null,
null);
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.produkterx,
c,
new String[] {mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_KCAL, mDB.KEY_VC},
new int[] {R.id.img, R.id.txt, R.id.rating});
adapter.setViewBinder(new Car());
setListAdapter(adapter);
enter code here
public class Car implements SimpleCursorAdapter.ViewBinder {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(view instanceof ImageView) {
ImageView iv = (ImageView) view;
byte[] img = cursor.getBlob(columnIndex);
iv.setImageBitmap(BitmapFactory.decodeByteArray(img, 0,
img.length));
return true;
}
if(view instanceof RatingBar) {
RatingBar rb = (RatingBar) view;
int kcal = cursor.getInt(cursor.getColumnIndex(DBhelper.KEY_KCAL));
int vitc = cursor.getInt(cursor.getColumnIndex(DBhelper.KEY_VC));
rb.setRating((float) (kcal * ((float) vitc/1000.0)));
return true;
}
return false;
}
}
enter code here
public class Bus {
private Bitmap bmp;
private String name;
private int kcal;
private int vitaminc;
public Bus(Bitmap b, String n, int k, int v) {
bmp = b;
name = n;
kcal = k;
vitaminc = v;
}
public Bitmap getBitmap() { return bmp; }
public String getName() { return name; }
public int getKcal() { return kcal; }
public int getVitaminC() { return vitaminc; }
}
enter code here` XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/Blue"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1" >
<Button
android:id="#+id/btnE"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="E" />
<ImageView
android:id="#+id/image1"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginTop="-7dp"
android:contentDescription="#drawable/header2"
android:src="#drawable/header2" />
<Button
android:id="#+id/btnkontakt"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="k" />
<Button
android:id="#+id/btnprodukter"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btnE"
android:text="p" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
<Button
android:id="#+id/btnSok"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/btnprodukter"
android:text="s" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="-7dp"
android:contentDescription="#drawable/sok"
android:src="#drawable/produkter" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:layout_weight="1" >
<ImageView
android:id = "#+id/img"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignParentLeft = "true"
>
</ImageView>
<TextView
android:id = "#+id/txt"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerVertical = "true"
>
</TextView>
<RatingBar
style="?android:attr/ratingBarStyleSmall"
android:id = "#+id/rating"
android:numStars = "5"
android:stepSize = "0.5"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignParentRight = "true"
android:layout_centerVertical = "true"
android:layout_marginRight = "5px">
</RatingBar>
</LinearLayout>
</LinearLayout>
> Blockquote
This XML is all in a simpelCA that i dont want!!
I'm a little confused as to the question. Your simple Cursor Adapter is meant to send the data to a listview for populating your screen.
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.produkterx,
c,
new String[] {mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_KCAL, mDB.KEY_VC},
new int[] {R.id.img, R.id.txt, R.id.rating});
You will want a match for the String[]/int[]. If you don't want to show something don't include it in here.
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.