This is the code that I use for my Listview which I got reference for some website. It shows a whole list of image. Which area do I have to place in my database to set the text for toptext and bottom text?
public class List_View extends ListActivity {
private DBAdapter db;
private TextView toptext;
private TextView bottomtext;
private ListView lv;
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
db = new DBAdapter(this);
toptext = (TextView) findViewById (R.id.toptext);
bottomtext = (TextView) findViewById (R.id.bottomtext);
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> item;
for (int i = 0; i < 31; i++) {
item = new HashMap<String, String>();
item.put("Date:", "Saved Date" );
item.put("Title:", "Saved Title" );
list.add(item);
}
The SimpleAdapter part:
SimpleAdapter notes = new SimpleAdapter(this, list, R.layout.view_list,
new String[] { "date", "title" },
new int[] {R.id.toptext, R.id.bottomtext });
setListAdapter(notes);
} catch(Throwable e){
Log.e("DBAdapter",e.toString());
}
}
and this is the database part:
public Cursor getAllEntry()
{
return db.query(DATABASE_TABLE_2, new String[] {
KEY_ROWID2,
KEY_TITLE,
KEY_ENTRY,
KEY_MOOD,
KEY_DATE,
KEY_TIME},
null,
null,
null,
null,
null,
null);
}
some modification in your code...and you get result
first declare Cursor, Adapter class in your ListActivity class
private NCursorAdapter adapter = null;
private Cursor mNotesCursor;
mNotesCursor = db.getAllEntry();
startManagingCursor(mNotesCursor);
if (adapter == null) {
adapter = new NCursorAdapter(this, mNotesCursor);
setListAdapter(adapter);
} else {
adapter.changeCursor(mNotesCursor);
adapter.notifyDataSetChanged();
}
you must create NCursorAdapter class in your application.
public class NCursorAdapter extends CursorAdapter {
private Cursor mCursor;
private Context mContext;
private final LayoutInflater mInflater;
public NCursorAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
mInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(cursor.getString(cursor.getColumnIndex("title")));
TextView date = (TextView) view.findViewById(R.id.date);
date.setText(cursor.getString(cursor.getColumnIndex("date")));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
final View view = mInflater.inflate(R.layout.data, parent, false);
return view;
}
}
here data.xml file is your custom layout. which content two textview....
"title" and "date" your database table column name...
Related
I am new to android, In my application i have a list view with image,textview's and button.when i click the button in the listview all the data's of the particular items are stored to the sqlite db and also to the webservice then i get a response string from the webservice, i updated this string in to my one of the field of sqlite DB.here i need to set this string into the button of listview by refreshing the listview..how can i do this below is my code
public class MainActivity extends ListActivity implements RegisterContactToServer.AsyncResponseListener {
ListView lv;
Cursor cursor,cursor1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_contact);
cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from={ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone._ID};
int[] to={R.id.name_entry,R.id.number_entry};
ContactList listadapter=new ContactList(this,R.layout.single_row1,cursor,from,to);
setListAdapter(listadapter);
lv=getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
class ContactList extends SimpleCursorAdapter implements Filterable {
private Context context;
String strfromMobileno="";
private int layout;
public ContactList(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.context=context;
this.layout=layout;
// TODO Auto-generated constructor stub
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
return v;
}
#Override
public void bindView(View v, final Context context, Cursor c) {
int nameCol = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String name = c.getString(nameCol);
int noCol = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String no = c.getString(noCol);
final CheckBox p1 = (CheckBox) v.findViewById(R.id.checkBox1);
final CheckBox p2 = (CheckBox) v.findViewById(R.id.checkBox2);
final CheckBox p3 = (CheckBox) v.findViewById(R.id.checkBox3);
final TextView name_text = (TextView) v.findViewById(R.id.name_entry);
if (name_text != null) {
name_text.setText(name);
}
final TextView no_text = (TextView) v.findViewById(R.id.number_entry);
if (no_text != null) {
no_text.setText(no);
}
final Contact contact=new Contact();
final Button btn=(Button)v.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String contactName = name_text.getText().toString();
String contactNo =no_text.getText().toString();
String statusR=btn.getText().toString();
contact.setFromMobileno(contactName);
contact.setToMobileno(contactNo);
if(p1.isChecked()){
int priority1=Integer.parseInt(p1.getText().toString());
contact.setPriority1(1);
}else{contact.setPriority1(0);}
if(p2.isChecked())
{
int priority2=Integer.parseInt(p2.getText().toString());
contact.setPriority2(1);
}else{contact.setPriority2(0);}
if(p3.isChecked()){
int priority3=Integer.parseInt(p3.getText().toString());
contact.setPriority3(1);
}else{contact.setPriority3(0);}
contact.setStatus(statusR);
if (!contactName.equals("") ){
RegisterConactDBAdapter cdbhelper=new RegisterConactDBAdapter(context);
cdbhelper.open();
cdbhelper.CreateUser(contact);
RegisterContactToServer reg=new RegisterContactToServer(context);
reg.execute(contact);
Intent intent = new Intent(context,ListRefresh.class);
startActivity(intent);
}
}
});
}
}
#Override
public void onresponse(String status, String jsonData) {
// TODO Auto-generated method stub
RegisterConactDBAdapter cdbheler=new RegisterConactDBAdapter(getBaseContext());
cdbheler.open();
cdbheler.UpdateStatus(jsonData);
}
}
in my Application i have an Activity that has a ListView and a button. i am using loader to automatically loading data to listview from my table in the database.and i am using the button to change the table rows.
i want the loader to automatically load the data from table when a change happens to the table.
right now my code loads the data into listview but it doesn't update it when table changes after that.
here are my classes :
item
public class Item {
public int id;
public String name;
}
MainActivity :
public class MainActivity extends Activity implements
LoaderManager.LoaderCallbacks<List<Item>> {
ItemAdapter adapter;
List<Item> items;
Button button;
TextView tv;
ListView listview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
button = (Button) findViewById(R.id.button);
listview = (ListView) findViewById(R.id.listview);
items = new ArrayList<Item>();
adapter = new ItemAdapter(this, items);
listview.setAdapter(adapter);
getLoaderManager().initLoader(0, savedInstanceState, this).forceLoad();
}
//button code for changing db
public void change(View view) {
ItemHelper helper = new ItemHelper(this);
Item item = new Item();
item.name = "Samsung P6800";
helper.insert(item);
}
#Override
public Loader<List<Item>> onCreateLoader(int id, Bundle args) {
final ItemHelper helper = new ItemHelper(getApplicationContext());
return new AsyncTaskLoader<List<Item>>(MainActivity.this) {
#Override
public List<Item> loadInBackground() {
return helper.read();
}
};
}
#Override
public void onLoadFinished(Loader<List<Item>> loader, List<Item> data) {
adapter.addAll(data);
adapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(Loader<List<Item>> loader) {
adapter.clear();
adapter.notifyDataSetChanged();
}
ItemHelper
public class ItemHelper {
public static final String DB_NAME = "Test";
private static Context m_context;
private static SQLiteDatabase m_db;
private static DatabaseHelper m_helper;
String[] columns = { "id", "name" };
public ItemHelper(Context context) {
m_context = context;
m_helper = new DatabaseHelper(m_context, DB_NAME, null, 1);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public void insert(Item item) {
m_db = m_helper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("name", item.name);
m_db.insert("item", null, initialValues);
m_db.close();
}
public List<Item> read() {
List<Item> items = new ArrayList<Item>();
m_db = m_helper.getReadableDatabase();
Cursor cursor = m_db.query("item", columns, null, null, null, null,
null);
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
item.name = cursor.getString(cursor
.getColumnIndexOrThrow("name"));
items.add(item);
} while (cursor.moveToNext());
}
m_db.close();
return items;
}
}
ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> {
private Context context;
private List<Item> items;
private LayoutInflater vi;
public ItemAdapter(Context context, int resource) {
super(context, resource);
// TODO Auto-generated constructor stub
}
public ItemAdapter(Context context, List<Item> items) {
super(context, 0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Item item = items.get(position);
if (item != null) {
view = vi.inflate(R.layout.item_info, parent, false); // custom xml
// for
// desired
// view
TextView tv1 = (TextView) view.findViewById(R.id.tvID);
tv1.setText(""+item.id);
TextView tv2 = (TextView) view.findViewById(R.id.tvName);
tv2.setText(item.name);
}
return view;
}
#Override
public Item getItem(int position) {
return items.get(position);
}
}
how can i do it ? ( i don't want to use content providers )
finally i used ContentProviders to solve this issue.
i created a method inside my database helper class that returns a Cursor according to it's parameters,
and used it inside ContentProvider to get Data.
public Cursor getCursor(int status, boolean isAccepted) {
m_db = m_helper.getReadableDatabase();
String sql = "SELECT id as _id , rid , isaccepted , status FROM torder";
Cursor cursor = m_db.rawQuery(sql, null);
return cursor;
}
also in helper when i insert data to db i notify the content provider :
public void notifyProvider(int status) {
ContentValues values = new ContentValues();
values.put("status", status);
Uri uri = m_context.getContentResolver().insert(
OrderProvider.CONTENT_URI, values);
}
public void insert(Order order) {
int flag = (order.isAccepted()) ? 1 : 0;
String[] args = { String.valueOf(order.getId()),
String.valueOf(order.getR_id()), String.valueOf(flag),
String.valueOf(order.getStatus()) };
m_db.execSQL(
"INSERT OR REPLACE INTO torder(id,rid,isaccepted,status) VALUES(?,?,?,?)",
args);
// save to orderdetails
List<OrderDetails> orderDetailsList = order.getOrders();
OrderDetailsHelper helper = OrderDetailsHelper.getInstance(m_context);
helper.open();
helper.insertAll(orderDetailsList);
helper.close();
notifyProvider(1);
}
Change your change method:
public void change(View view) {
ItemHelper helper = new ItemHelper(this);
Item item = new Item();
item.name = "Samsung P6800";
helper.insert(item);
getLoaderManager().restartLoader(0, null, this);
}
I have a list activity that has a TextView and EditText field per row. Previously I was using simplecursoradapter but to get around the problem of getting values from EditText and using in other activities. As well as recycling moving user inputs around I'm trying to move to a custom one. I've got it to run but when it does it does not display any of my results. At this point its just showing my footer at the bottom.
// custom adapter
public class ItemsAdapter extends ArrayAdapter<Model> {
private LayoutInflater mInflater;
private Cursor cursor;
public ItemsAdapter(Context context, int layout, Cursor cursor, String[] from,
int[] to) {
super(context, layout);
this.cursor = cursor;
mInflater = LayoutInflater.from(context);
}
static class ViewHolder {
protected TextView text;
protected EditText edittext;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.edit_row, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.textType);
holder.edittext = (EditText) convertView.findViewById(R.id.editText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
cursor.moveToPosition(position);
int label_index = cursor.getColumnIndex("userword");
String label = cursor.getString(label_index);
holder.text.setText(label);
return convertView;
}
}
//My list activity
public class editview extends ListActivity {
private dbadapter mydbhelper;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mydbhelper = new dbadapter(this);
mydbhelper.open();
View footer = getLayoutInflater().inflate(R.layout.footer_layout, null);
ListView listView = getListView();
listView.addFooterView(footer);
showResults();
}
private void showResults (){
Cursor cursor = mydbhelper.getUserWord();
startManagingCursor(cursor);
String[] from = new String[] {dbadapter.KEY_USERWORD};
int[] to = new int[] {R.id.textType};
ItemsAdapter adapter = new ItemsAdapter(this, R.layout.edit_row, cursor,
from, to);
adapter.notifyDataSetChanged();
this.setListAdapter(adapter);
}
//footer button
public void onClick(View footer){
final MediaPlayer editClickSound = MediaPlayer.create(this, R.raw.button50);
editClickSound.start();
}
}
//My cursor located in dbadapter class
// retrieves all the descriptions for the edittext fields
public Cursor getUserWord()
{
return myDataBase.query(USER_WORD_TABLE, new String[] {
KEY_ID,
KEY_CATEGORY,
KEY_SOURCE, KEY_TITLE, KEY_USERWORD, KEY_QUICK
},
KEY_CATEGORY+ "=" + categories.categoryClick + " AND " + KEY_SOURCE+ "="
+source.sourceClick + " AND " + KEY_TITLE+ "=" + title.titleClick,
null, null, null, KEY_ID);
}
To give more info on how this works. User will got through a series of Listviews, category->source->title. Then brings them to this activity with the EditText where I will take their inputs and use them in the next activity. I'm pretty new to the custom cursor adapter since I'm new to android and still learning so I'm having trouble understanding what I'm missing.
i have a list with data from my database.
I want to have a button in every list item that onClick will delete this item from the database.
Here is how i get the data from the db and present them in a list:
DB entry=new DB(this);
entry.open();
Cursor cursor = entry.getData();
startManagingCursor(cursor);
ListView list=(ListView)findViewById(R.id.list);
String[] columns = new String[] { DBHelper.NAME, DBHelper.SURNAME};
int[] to = new int[] { R.id.textView01,R.id.textView02};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, columns, to);
list.setAdapter(mAdapter);
entry.close();
So,my problem is : How to create a clickable button in every list item
EDIT:
this is the adapter i created:
public class myAdapter extends BaseAdapter {
private Context mContext;
final Drawable delete_btn;
private ImageButton imageButton;
private LayoutInflater inflater;
private List<ITEMS> items = new ArrayList<ITEMS>();
public myAdapter(Context ctx) {
mContext = ctx;
inflater = LayoutInflater.from(mContext);
delete_btn = ctx.getResources()
.getDrawable(R.drawable.delete_btn);
}
public View getView(final int position, View convertView, ViewGroup parent) {
View btv = null;
try {
btv = inflater.inflate(R.layout.row, null);
TextView name = (TextView) btv.findViewById(R.id.textView01);
name.setText(DBHelper.NAME);
TextView surname = (TextView) btv.findViewById(R.id.textView02);
surname.setText(DBHelper.SURNAME);
imageButton = (ImageButton) btv.findViewById(R.id.delete_btn);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Button pressed", Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
return btv;
}
public void addItem(ITEM it) {
items.add(it);
}
public void setListItems(List<ITEM> lit) {
items = lit;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
}
create your own CustomCursorAdapter instead of SimpleCursorAdapter. Here is an example
Ive been learning about the getview . But i cant get it to display the data in my listview. Can anyone help code is below
//public class OrderProductSearch extends Activity {
public class OrderProductSearch extends Activity {
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> item = new HashMap<String,String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.orderproducts);
}
catch (Exception e) {
//
String shaw="";
shaw = e.getMessage();
}
//Create view of the list where content will be stored
final ListView listContent = (ListView)findViewById(R.id.orderproductlistview);
//Set for fast scrolling
listContent.setFastScrollEnabled(true);
//Create instance of the database
final DbAdapter db = new DbAdapter(this);
//Open the Database and read from it
db.openToRead();
//Routine to call all product sub groups from the database
final Cursor cursor = db.getAllSubGroupProduct();
//Manages the cursor
startManagingCursor(cursor);
int i=0;
cursor.moveToFirst();
while (cursor.getPosition() < cursor.getCount()) {
item.put("ProdName",cursor.getString(2));
item.put("ProdSize", cursor.getString(3));
item.put("ProdPack",cursor.getString(4));
item.put("OrdQty","0");
//list.add(item);
list.add(i, item);
item = new HashMap<String,String>();
cursor.moveToNext();
i = i + 1;
}
String[] from = new String[] {"ProdName", "ProdSize", "ProdPack", "OrdQty"};
int[] to = new int[] { R.id.productlinerow, R.id.productlinerow2, R.id.productlinerow3, R.id.productlinerow4};
//SimpleAdapter notes = new SimpleAdapter(OrderProductSearch.this,list,R.layout.productlinerow,from,to);
NewAdapter notes = new NewAdapter(OrderProductSearch.this,list,R.layout.productlinerow,from,to);
listContent.setAdapter(notes);
//Close the database
db.close();
}
class NewAdapter extends SimpleAdapter{
int resource;
Context cxt;
private Context context;
List<? extends Map<String, ?>> DataList;
public NewAdapter(Context context, List<? extends Map<String, ?>> data,
int _resource, String[] from, int[] to) {
super(context, data, _resource, from, to);
resource = _resource;
this.context = context;
DataList = data;
// TODO Auto-generated constructor stub
}
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.productlinerow, null);
}
// TextView bTitle = (TextView) v.findViewById(R.id.productlinerow);
// bTitle.setText(DataList[position,1][1].toString());
return v;
}
}
}
If you're using a SimpleAdapter, you don't need to extend the class and customize the getView() as the SimpleAdapter handles the mapping of data to your layout via the resource, from and to parameters. Take a look at this tutorial for the idea:
http://vbsteven.com/archives/24
If you want to do more involved customization, use a BaseAdapter, which the SimpleAdapter actually extends. Here's a tutorial with examples of that:
http://android.amberfog.com/?p=296