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
Related
Don't know how to ask the question or maybe the title is wrong too . I have tried to find the answer everywhere but didn't get . Help .
I am getting data from SQLite database in a ListView which contains four TextViews .
final String[] from = new String[] { DatabaseHelper._ID, DatabaseHelper.TITLE, DatabaseHelper.USERNAME, DatabaseHelper.PASSWORD };
final int[] to = new int[] { R.id.id, R.id.dataTitle, R.id.dataUsername, R.id.dataPassword };
DBManager dbManager = new DBManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
ListView dataList = findViewById(R.id.dataList);
dataList.setEmptyView(findViewById(R.id.emptyData));
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contents, cursor, from, to, 0);
adapter.notifyDataSetChanged();
dataList.setAdapter(adapter);
Where fetch() is :
public Cursor fetch() {
String[] columns = new String[] {
DatabaseHelper._ID,
DatabaseHelper.TITLE,
DatabaseHelper.USERNAME ,
DatabaseHelper.PASSWORD
};
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Now the problem is I have stored String data in database in encrypted format. I want to decrypt the Strings before showing in the ListView .
Please help me .
Thanks .
you should use AysncTask for retrieving data from database because if data is larger then UI may be unresponsive and hang and decrypt the string in fetch() method.
You should Load listview in onPostExecute method()
Example:
private class GetData extends AsyncTask<Void, Void, Void> {
ArrayList<YourModel> youArray=null;
#Override
protected Void doInBackground(Void... voids) {
youArray=dbManager.fetch() // Return decrypted array from fetch method.
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
// Load your listview here...
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contents, cursor, from, to, 0);
dataList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
Your ListView Adapter
public class LazyAdapter extends BaseAdapter {
private Context context=null;
ArrayList<YourModel> data=new ArrayList<>;
private static LayoutInflater inflater=null;
public LazyAdapter(Context context, ArrayList<YourModel> data) {
this.context = a;
this.data=data;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.your_view, null);
// Your subviews which needed to be initialized and set.
TextView email = (TextView)vi.findViewById(R.id.email); // email
TextView password = (TextView)vi.findViewById(R.id.password); // password
User user = data.get(position);
// Setting all values in listview
email.setText(user.getEmail());
password.setText(user.getPassword());
return vi;
}}
if i have understood your point correctly you can add encrypted data to ArrayList then encrypt in array list and next add to listview
In my database I am storing data on various tourist attractions. I'm also storing the name of an image for each attraction, e.g. caste.jpg. The following method adds all written data to the text fields but I don't know how to add the image to the ImageView. Any help?
public void updateDisplay()
{
// get the comments
attractions = db.getAttractions();
// create a List of Map<String, ?> objects
ArrayList<HashMap<String, String>> data =
new ArrayList<HashMap<String, String>>();
for (Attraction attraction : attractions) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", attraction.getName());
map.put("times", attraction.getOpeningTimes());
map.put("descr", attraction.getDesc());
map.put("price", attraction.getPrice());
data.add(map);
}
// create the resource, from, and to variables
int resource = R.layout.listview_attraction;
String[] from = {"name", "times", "descr", "price", "web"};
int[] to = {R.id.name, R.id.times, R.id.descr, R.id.price, R.id.web};
// create and set the adapter
SimpleAdapter adapter =
new SimpleAdapter(this, data, resource, from, to);
attractionListListView.setAdapter(adapter);
}
String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
// Then use this for setting the drawable in either case:
Imageview.setBackground(drawable)
You could refer to the image with a path (local or remote)
for (Attraction attraction : attractions) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", attraction.getName());
map.put("times", attraction.getOpeningTimes());
map.put("descr", attraction.getDesc());
map.put("price", attraction.getPrice());
-> map.put("imagePath", attraction.getPath());
data.add(map);
}
And then, instead of using ther built in adapter, make a customer adapter
and load the image from the path in the adapter's getView() method. For example, the below code is a custom adapter I use in one of my apps:
private class ViewHolder {
TextView mItem;
ImageView mStore;
}
public class MyDataAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
int layout;
public MyDataAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.layout = layout;
this.context = context;
}
public View getView(final int pos, View inView, ViewGroup parent) {
ViewHolder holder = null;
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(layout, null);
holder = new ViewHolder();
holder.mItem = (TextView) inView.findViewById(R.id.item);
holder.mStore = (ImageView)
inView.setTag(holder);
} else {
holder = (ViewHolder) inView.getTag();
}
final VisitProfile visit = VisitProvider.getProfile(c, pos);
if (visit != null) {
final int store = visit.getStore();
RetailStoreProfile rsp = RetailStoreProvider.fetchStore(ShowEventDetail.this, store);
if (rsp != null) {
holder.mStore.setDrawable(rsp.getPath());
} else {
Log.d(TAG, "Bogus Store in adapter " + store);
}
} else {
Log.d(TAG, "Bogus visit in adapter " + visit);
}
return inView;
}
}
I've got a ListActivity filled by an adapter extending SimpleCursorAdapter. Some category buttons can be clicked, which fills the listview with a list of articles in the corresponding category. When clicking on an item in the list a new activity is launched which shows the detail of the article.
Now, when pressing the back button in that article detail page, no data is shown. Does it have to reload the data from the DB? Isn't the data supposed to be cached?
Moreover, when going back to the myListActivity, onCreate is not called. Only onResume is called. Shall I do everything in onResume? In that case what's the best way to keep the value of the current category and retrieve it when going back to the ListActivity from the article detail?
Thanks
public class Home extends ListActivity implements OnItemClickListener{
private DBAdapter dbAdapter;
private HomeListAdapter adapter; //extends SimpleCursorAdapter
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// open database
dbAdapter = new DBAdapter(this);
dbAdapter.open();
/* more stuff */
getArticlesbyCat(category);
/* more stuff */
}
private void getArticles(int category){
Cursor c = dbAdapter.fetchArtByCat(category);
c.moveToFirst();
startManagingCursor(c);
String[] from = new String[] {};
int[] to = new int[] {};
setListAdapter(new HomeListAdapter(this, R.layout.article_row, c, from, to));
adapter.notifyDataSetChanged();
c.close();
}
#Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
/* Go to article page */
}
#Override
protected void onPause() {
super.onPause();
// close database
dbAdapter.close();
}
}
EDIT
public class HomeListAdapter extends SimpleCursorAdapter {
private int mLayout;
private Cursor mCursor;
private Resources mResources;
// Column index
private int mCatInd;
private int mURLPicInd;
private int mIntroInd;
private int mTitleInd;
private LayoutInflater mLayoutInflater;
private final ImageDownloader mImageLoader;
private final class ViewHolder {
public TextView category;
public ImageView image;
public TextView intro;
public TextView title;
}
public HomeListAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mLayout = layout;
this.mCursor = c;
this.mCatInd = mCursor.getColumnIndex(DBAdapter.KEY_CATEGORY_NAME);
this.mURLPicInd = mCursor.getColumnIndex(DBAdapter.KEY_URL_PIC);
this.mIntroInd = mCursor.getColumnIndex(DBAdapter.KEY_INTRO);
this.mTitleInd = mCursor.getColumnIndex(DBAdapter.KEY_TITLE);
this.mLayoutInflater = LayoutInflater.from(context);
mResources = context.getResources();
mImageLoader = new ImageDownloader(mResources,
((BitmapDrawable)mResources.getDrawable(R.drawable.default_row_pic)).getBitmap(), 1);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.category = (TextView) convertView.findViewById(R.id.cat);
viewHolder.image = (ImageView) convertView.findViewById(R.id.picture);
viewHolder.title = (TextView) convertView.findViewById(R.id.title);
viewHolder.intro = (TextView) convertView.findViewById(R.id.intro);
viewHolder.intro.setMaxLines(3);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
String category = mCursor.getString(mCatInd);
String title = mCursor.getString(mTitleInd);
String intro = mCursor.getString(mIntroInd);
String url_pic = mCursor.getString(mURLPicInd);
viewHolder.category.setText(category);
viewHolder.title.setText(title);
viewHolder.intro.setText(intro);
if(!url_pic.equals("")){
mImageLoader.download(url_pic, (ImageView) viewHolder.image);
}
else {
viewHolder.image.setImageResource(R.drawable.default_row_pic);
}
}
return convertView;
}
}
i am using spinner in some application in spinner item list array this text replaced in drawable images how can its implemented
personalinformation = (Spinner) findViewById(R.id.SpinnerCategory);
ArrayAdapter<?> adapterDefaultpersonal = ArrayAdapter.createFromResource(Animals.this, R.array.Animalinformation, android.R.layout.simple_spinner_item);
adapterDefaultpersonal.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
personalinformation.setAdapter(adapterDefaultpersonal);
How can the R.array.Animalinformation array list items replaced in drawable images be implemented?
Yes it is look at the code below..
array of data
//stores the image database icons
private static Integer[] imageIconDatabase = { R.drawable.ball, R.drawable.catmouse, R.drawable.cube, R.drawable.fresh, R.drawable.guitar, R.drawable.orange, R.drawable.teapot };
//stores the image database names
private String[] imageNameDatabase = { "ball", "catmouse", "cube", "fresh", "guitar", "orange", "teapot" };
creating List of hashmaps
private void initializeImageList() {
// TODO Auto-generated method stub
ArrayList<HashMap<String, Object>> spinnerList = new ArrayList<HashMap<String,Object>>();
for (int i = 0; i < imageNameDatabase.length; i++) {
HashMap map = new HashMap();
map.put("Name", imageNameDatabase[i]);
map.put("Icon", imageIconDatabase[i]);
spinnerList.add(map);
}
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource((spinnerList.get(0).get("Icon"));
spinnerList.get(0).get("Name");
}
// assigning spinner to adapter
public void createAddDialog() { // TODO
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list_editoradd_dialog);
Spinner spin = (Spinner) findViewById(R.id.spinnerAddImageList);
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, spinnerData, R.layout.spinner_view, new String[] { "Name", "Icon" }, new int[] { R.id.imageNameSpinner, R.id.imageIconSpinner });
spin.setAdapter(adapter);
}
the adapter used above is as given below..
class CustomSpinnerAdapter extends SimpleAdapter {
LayoutInflater mInflater;
private List<? extends Map<String, ?>> dataRecieved;
public CustomSpinnerAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
dataRecieved = data;
mInflater = LayoutInflater.from(context);
}
#SuppressWarnings("unchecked")
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null) {
convertView = mInflater.inflate(R.layout.spinner_view,null);
}
HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);
((TextView) convertView.findViewById(R.id.imageNameSpinner)).setText((String) dataRecieved.get(position).get("Name"));
((ImageView) convertView.findViewById(R.id.imageIconSpinner)).setBackgroundResource(dataRecieved.get(position).get("Icon")));
return convertView;
}
}
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...