İ am using this custom adapter for showing youtube thumbnail.
public class MyMedyaAdapter extends SimpleAdapter {
Context context;
int layout;
List<? extends Map<String, ?>> data;
String[] from;
int[] to;
String resimURL = "http://img.youtube.com/vi/{0}/0.jpg";
public MyMedyaAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
this.context = context;
this.layout = resource;
this.data = data;
this.from = from;
this.to = to;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(layout, parent, false);
TextView metin = (TextView) rowView.findViewById(R.id.row_medya_text);
String baslik = data.get(position).get(from[0]) + "";
baslik = baslik.replace(".pdf", "");
metin.setText(baslik);
if (from.length > 1) {
final ImageView resim = (ImageView) rowView.findViewById(R.id.row_medya_image);
final int p2 = position;
String resimID = data.get(p2).get(from[1])+"";
String rowImage = resimURL.replace("{0}", resimID);
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(rowImage).getContent());
resim.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO: handle exception
}
}
return rowView;
}
}
adding adapter to listview with this code;
public class VideoThered extends AsyncTask<Void, Void, MyMedyaAdapter> {
#Override
protected MyMedyaAdapter doInBackground(Void... params) {
List<HashMap<String, String>> response = new ArrayList<HashMap<String, String>>();
try {
//JSON request
response = new JsonHelper().GetVideoEntitys();
} catch (Exception e) {
response = null;
}
if (response != null) {
adapter = new MyMedyaAdapter(ctx, response, R.layout.row_medya, from, to);
}
else
{
adapter = null;
}
return adapter;
}
#Override
protected void onPostExecute(MyMedyaAdapter result) {
if (result != null) {
//StrictMode$AndroidBlockGuardPolicy.onNetwork() error with this line on honeycomb
listVideolar.setAdapter(adapter);
}
}
}
i am getting /StrictMode$AndroidBlockGuardPolicy.onNetwork() error.
How can i manage to show row images from web and not getting this error?
i am using listview main data from AsyncTask.
in this data list, each item has a unique youtube video id. with this id i am getting video thumbnails from web. but on my custom adapter did not use AsyncTask. i know that's the problem.
But how can i manage to my custom adaptor to use AsyncTask?
You are getting the error because you do network access in the UI thread. This is considered bad, because network access takes a long time and thus blocks the UI.
To solve this, you can write an AsyncTask that pulls the data from the net within its doInBackground method and then in onPostExecute fills the view with the bitmap/drawable.
I think the Android documentation has an example for this scenario, but I can't find it right now.
You can also have a look at this source code snippet, DownloadUserImageTask from my Zwitscher app; the url is retrieved from the passed User object. The picture is then added to the view in
userPictureView.setImageBitmap(result);
Related
I am working on android projects. In my application I am getting the data from php webservice. I added my data to different arraylists and set them to listadapter. But my problem is it is taking very long time to display the data in list. Hence now I want to display first 10 items and want to keep a loadmore button at the bottom of the screen. Once the load more button is clicked the next 10 items need to display. Please can anybody help me in this regard. I would really appreciate for this help.
Thank you in advance.
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Longop op = new Longop();
op.execute("");
}
public void loadSomeDummyData() {
try {
response = CustomHttpClient
.executeHttpPost(
"http://website.com/folder/testfile.php",
postParameters);
for (int i = 1; i < arr1.length - 1; i++) {
id.add(new String(arr[0]));
name.add(new String(arr[1]));
dateofbirth.add(new String(arr[2]));
status.add(new String(arr[3]));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class Longop extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
loadSomeDummyData();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
mdialog.dismiss();
myListView.setAdapter(new MyArrayAdapter(Sample.this,
R.layout.list, id, name, dateofbirth,
status));
}
#Override
protected void onPreExecute() {
mdialog = ProgressDialog.show(Sample.this, "Please wait...",
"Retrieving data ...", true);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private class MyArrayAdapter extends ArrayAdapter<String> {
// this list hold the data that we will see in listview
private List<String> myData = new ArrayList<String>();
private List<String> myData1 = new ArrayList<String>();
private List<String> myData2 = new ArrayList<String>();
private List<String> myData3 = new ArrayList<String>();
public MyArrayAdapter(Context context, int textViewResourceId,
List<String> objects, List<String> objects1,
List<String> objects2, List<String> objects3) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
context = getContext();
myData = objects;
myData1 = objects1;
myData2 = objects2;
myData3 = objects3;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list, null);
// Log.d(EKSI, "Getting the inflater from the system context");
}
String sid = myData.get(position);
String sname = myData1.get(position);
String dob = myData2.get(position);
String sstatus = myData3.get(position);
TextView entryTextView = (TextView) v.findViewById(R.id.id1);
entryTextView.setText(sid);
TextView entryTextView1 = (TextView) v
.findViewById(R.id.id2);
entryTextView1.setText(sname);
TextView entryTextView2 = (TextView) v
.findViewById(R.id.id3);
entryTextView2.setText(dob);
TextView entryTextView3 = (TextView) v
.findViewById(R.id.id4);
entryTextView3.setText(sstatus);
return v;
}
}
You could also use this lib
https://github.com/chrisbanes/Android-PullToRefresh.
I implement this function not base ListView that can do this;
Custom loading view,override onDraw menthod
Add loading view at the end of LinearLayout view. When loading view is show, it should call some methods to get data from server by HTTP.
you just need to inflate an xml in
lstView.addFooterView(R.layout.footer);
and handle onclick of the button residing in footer
I'm having some troubles with correct identification of items in a ListView.
There are 4 classes that matter, it's a lot of code so at first I'm going to explain the logic of those classes.
Enter the ListActivity and initialize its ListView
execute an AsyncTask that downloads JSON response from the server, parses it, populates the ListView with Objects and sets the adapter while showing a ProgressDialog
the PlaylistItem class includes methods which simply get the data from a single JSONObject. It is used to parameterize the ArrayList with its Objects
after the AsyncTask is done the list is filled with items and looks like |Button| Artist(TextView) - Title(TextView)
UPDATE
resolved 1st issue but still can't figure out what's wrong with buttons
2). I set an OnClickListener to my buttons in the Adapter's getView() method. To find out if the button is identified correctly I did nothing but just changed its background. BUT a click on a certain button forces the background of every 11th or 12th button to be changed. Can't figure it out so far.
I can't proceed to getting url and streaming audio until those problems are resolved, so any help is greatly appreciated. My classes go below, please ask if something appears unclear.
AudioList
public class AudioList extends ListActivity {
private ListView lv;
private PlaylistLoader loader;
private AudioListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_list);
init(); // initialize the ListView
/*--- populate the list with user's audio in case network connection is available ---*/
loader = new PlaylistLoader(this, lv, adapter);
if (Utils.isNetworkAvailable(this)) {
loader.execute();
} else {
APP_CONSTANTS.NO_DATA_CONNECTION(this);
}
}
#Override
protected void onResume() {
super.onResume();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), Integer.toString(arg2),
Toast.LENGTH_SHORT).show();
}
});
}
private void init() {
lv = getListView();
lv.setTranscriptMode(0x00000000);
lv.setDividerHeight(1);
lv.setSmoothScrollbarEnabled(true);
lv.setVerticalFadingEdgeEnabled(true);
}
PlaylistLoader
public class PlaylistLoader extends AsyncTask<Void, Void, Void> {
private JSONObject usersPlaylist, singleJSONItem;
private JSONArray responseJSONArray;
private ListView lv;
private ArrayList<PlaylistItem> playlist;
private Activity a;
private PlaylistItem audioList;
private SharedPreferences prefs;
private ProgressDialog pd;
AudioListAdapter adapter;
public PlaylistLoader(Activity a, ListView lv, AudioListAdapter adapter) {
this.lv = lv;
this.a = a;
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
/*--- create new ArrayList of PlaylistItem Objects ---*/
playlist = new ArrayList<PlaylistItem>();
/*--- get the preferences using context of calling activity ---*/
prefs = PreferenceManager.getDefaultSharedPreferences(a);
try {
/*--- download the response JSONObject from server // access_token and
* user_id come from activity's defaultSharedPreferences ---*/
usersPlaylist = Utils.retrieveJsonObjectFromUrl(new URL(
APP_CONSTANTS.REQUEST_AUDIO_LIST(prefs)), a);
/*--- get the response array from received object ---*/
responseJSONArray = usersPlaylist.getJSONArray("response");
/*--- populate the ArrayList with Objects from the response array ---*/
for (int i = 0; i < responseJSONArray.length(); i++) {
singleJSONItem = responseJSONArray.getJSONObject(i);
audioList = new PlaylistItem(singleJSONItem);
playlist.add(audioList);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(a);
pd.setTitle("Please wait");
pd.setMessage("Retrieving audio list...");
pd.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
lv.setVisibility(View.VISIBLE);
pd.dismiss();
/*--- set the adapter passed in constructor as an adapter for passed ListView ---*/
adapter = new AudioListAdapter(a, R.layout.playlist_item, playlist);
lv.setAdapter(adapter);
}
}
AudioListAdapter
public class AudioListAdapter extends ArrayAdapter<PlaylistItem> {
private PlaylistItem pl;
private Context context;
private int layoutResourceId;
private PlaylistItem aud;
private ArrayList<PlaylistItem> data = null;
public AudioListAdapter(Context context, int layoutResourceId,
ArrayList<PlaylistItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public PlaylistItem getItem(int position) {
return super.getItem(position);
}
#Override
public int getCount() {
return data.size();
}
#Override
public int getPosition(PlaylistItem item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pl = new PlaylistItem();
aud = getItem(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
pl.btnPlay = (Button) convertView.findViewById(R.id.btn_list_play);
pl.imgSaved = (ImageView) convertView
.findViewById(R.id.img_list_audio_saved);
pl.tvArtist = (TextView) convertView
.findViewById(R.id.tvListItemArtist);
pl.tvTitle = (TextView) convertView
.findViewById(R.id.tvListItemSong);
convertView.setTag(pl);
} else {
pl = (PlaylistItem) convertView.getTag();
pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
}
pl.tvArtist.setText(aud.getArtist() + " " + "-");
pl.tvTitle.setText(aud.getTitle());
pl.btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*--- vibrate if this option is enabled in the preferences ---*/
if (APP_CONSTANTS.isHapticFeedbackEnabled(getContext())) {
APP_CONSTANTS.doVibrate(getContext());
}
pl.btnPlay.setBackgroundResource(R.drawable.list_button_pause);
}
});
return convertView;
}
PlayListItem
public class PlaylistItem {
private String artist, title;
private JSONObject obj;
public Button btnPlay;
public TextView tvArtist, tvTitle;
public ImageView imgSaved;
public int duration;
public int audio_id;
public String url;
/*--- the constructor takes a single JSONObject from the response array ---*/
public PlaylistItem(JSONObject obj) {
this.obj = obj;
}
public PlaylistItem() {
// default constructor
}
/*--- the methods below return values by key from the passed JSONObject ---*/
public String getArtist() {
try {
artist = obj.getString("artist");
} catch (JSONException e) {
e.printStackTrace();
}
return artist;
}
public String getTitle() {
try {
title = obj.getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
return title;
}
public int getID() {
try {
audio_id = obj.getInt("aid");
} catch (JSONException e) {
e.printStackTrace();
}
return audio_id;
}
public String getURL() {
try {
url = obj.getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
return url;
}
}
Edit:
Try this
Take a custom Selector in your drawable
button_play.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pause_button"
android:state_selected="true" />
<item android:drawable="#drawable/play_button" />
</selector>
Modifty your adapter like this
public class AudioListAdapter extends ArrayAdapter<PlaylistItem> {
private PlaylistItem pl;
private Context context;
private int layoutResourceId;
private PlaylistItem aud;
private ArrayList<PlaylistItem> data = null;
Button previous;
public AudioListAdapter(Context context, int layoutResourceId,
ArrayList<PlaylistItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
previous=new Button(context);
this.context = context;
this.data = data;
}
....
....
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pl = new PlaylistItem();
aud = getItem(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
pl.btnPlay = (Button) convertView.findViewById(R.id.btn_list_play);
pl.btnPlay.setBackGroundResouce(R.drawable.button_play); //you can set here or in xml
pl.imgSaved = (ImageView) convertView
.findViewById(R.id.img_list_audio_saved);
pl.tvArtist = (TextView) convertView
.findViewById(R.id.tvListItemArtist);
pl.tvTitle = (TextView) convertView
.findViewById(R.id.tvListItemSong);
convertView.setTag(pl);
} else {
pl = (PlaylistItem) convertView.getTag();
}
pl.tvArtist.setText(aud.getArtist() + " " + "-");
pl.tvTitle.setText(aud.getTitle());
pl.btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*--- vibrate if this option is enabled in the preferences ---*/
if (APP_CONSTANTS.isHapticFeedbackEnabled(getContext())) {
APP_CONSTANTS.doVibrate(getContext());
}
//for some reason, the background gets changed for every 11th or 12th button in the list
Button current=((Button)v);
current.setSelected(true);
previous.setSelected(false);
previous=current;
}
});
return convertView;
}
}
The reason why your button and listitem not clickable is because Your list have a focus item button, so you need to setFocusable=false for your button.
Try setting focusable=false for your button in the xml. If it is not worked for you than do like this
In your row xml file
1.set focusable=true for your button.
2.In the same set android:descendantFocusability="blocksDescendants" for your parent item.(i.e parent layout in which your views lie).
In getView() method after setting the onclickListener for the button, set focusable false for the button.
It will work for sure. I hope this will help you..
BUT a click on a certain button forces the background of every 11th or 12th button to be changed. Can't figure it out so far.
You are fighting the way ListViews recycle the row layouts.
Think of it this way: if you have a ListView with 10,000 rows but can only fit 9 of them on the screen, then it doesn't make sense to create 10,000 unique layouts. This just waste resources, instead ListView only creates ~10 layouts and reuses them.
Solution: return each row to it's default state when it is reused. In getView() add:
} else {
pl = (PlaylistItem) convertView.getTag();
pl.btnPlay.setBackgroundResource(R.drawable.list_button_play);
// I guessed at the resource's name ^^^^^^^^^^^^^^^^
}
(Also you can make a few small changes to speed up your code. For instance, you only need one OnClickListener since they all contain the same code, make this a class variable and pass this to each play Button. There are more.)
I read a lot of threads here and elsewhere about loading images in custom listviews but I got nowhere! So, I thought I'd better ask!
The sittuation is as follows:
I have an activity that has a listview on it with 6 items (lets say Item1, Item2 etc). When the user clicks on an item I launch a new activity with another listview but this time the list view is a custom one with an image and some text.
The first activity's onCreate method is this:
GetImageFromURL eventImageLoader = new GetImageFromURL(FirstActivity.this, eventMultimediaID);
eventImageLoader.execute();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
CustomAdapter adapter = new CustomAdapter(this, android.R.layout.simple_expandable_list_item_1, R.id.textView1, eventName, bitmap);
eventList = (ListView) findViewById(R.id.secEventList);
eventList.setAdapter(adapter);
eventList.setOnItemClickListener(eventNameListClickListener);
I create and start an AsyncTask to load the images into a bitmap List.
eventMultimediaID is a String array and so is eventName.
The GetImageFromURL Task is this:
public class GetImageFromURL extends AsyncTask<Void, Void, List<Bitmap>>
{
private ProgressDialog progressDialog = null;
private Context callingContext = null;
private List<Bitmap> bitmap = new ArrayList<Bitmap>();
private String[] eventMultimediaID = null;
public GetImageFromURL(Context callingContext, String[] eventMultimediaID)
{
this.callingContext = callingContext;
this.eventMultimediaID = eventMultimediaID;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(callingContext, "Loading Events", "Retrieving data from server, please wait...", true);
}
#Override
protected List<Bitmap> doInBackground(Void... params)
{
try
{
int length = eventMultimediaID.length;
for(int i = 0; i < length; i++)
{
URL imageUrl = new URL("https://www.blahblah/servlet?blahblah=" + eventMultimediaID[i]);
bitmap.add(i, BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream()));
}
}
catch (IOException e)
{
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(List<Bitmap> bitmap)
{
for(int i = 0; i < bitmap.size(); i++)
{
ShowEventCategory.bitmap.add(i, bitmap.get(i));
}
progressDialog.dismiss();
}
}
and this is the CustomAdapter:
public class CustomAdapter extends ArrayAdapter<String>
{
private Context currentContext;
private String[] data;
private List<Bitmap> evImage;
public CustomAdapter(Context context, int resource, int textViewResourceId, String[] objects, List<Bitmap> bitmap)
{
super(context, resource, textViewResourceId, objects);
this.currentContext = context;
this.data = objects;
this.evImage = bitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) currentContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View eventListItem = inflater.inflate(R.layout.show_event_category_list_item, parent, false);
ImageView eventListItemImage = (ImageView) eventListItem.findViewById(R.id.eventImage);
TextView eventListItemText = (TextView) eventListItem.findViewById(R.id.eventText);
eventListItemText.setText(data[position]);
eventListItemImage.setImageBitmap(evImage.get(position));
return eventListItem;
}
}
What I tried to do was to call the async task from the Activity to load the images and while doing so display a loading dialog. After the loading is complete the dialog is dismissed and the adapter takes the filled Bitmap array.
This doesn't work. After the Task is started the execution goes on (I think thats what SHOULD happen) and the adapter gets an empty array so I get an OutOfBoundsException. That's why I placed Thread.sleep(5000) in the main thread to wait for the load operation to complete. But of course that's not an acceptable solution!
:( Any suggetions?! I've spent all day on that thing!!!!
Thanx a lot in advance!
I try to implement homeline pagination via Twitter4j to pull-to-refresh list from Chris Banes. However, I have problems of that how to realize it. I have some notes how it should work but it isn't so, my pull refresh list doesn`t refresh. Have any ideas how to upload next 40 tweet to list on refresh?
Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tweetlist);
initializeVars();
paging = new Paging(1, 40);
try {
ListView actualListView = pullToRefreshView.getRefreshableView();
tweets = twitter.getHomeTimeline(paging);
tweetAdapter = new TweetListAdapter(this, R.layout.customtweetlist, tweets);
actualListView.setAdapter(tweetAdapter);
} catch (TwitterException e) {
e.printStackTrace();
}
}
public void onRefresh() {
new GetDataTask().execute();
}
private class GetDataTask extends AsyncTask<Void, Void, List<Status>> {
protected List<twitter4j.Status> doInBackground(Void... params) {
paging.setPage(2);
try {
tweets = twitter.getHomeTimeline(paging);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tweets;
}
protected void onPostExecute(List<twitter4j.Status> result) {
tweetAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
}
}
My TweetAdapter
public class TweetListAdapter extends ArrayAdapter<Status> {
private final Context context;
private final List<Status> values;
public TweetListAdapter(Context context,int textViewResourceId, List<Status> tweets) {
super(context, textViewResourceId, tweets);
this.context = context;
this.values = tweets;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.customtweetlist, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.tvText);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivImage);
Status tweet = values.get(position);
textView.setText(tweet.getText());
// imageView.setImageBitmap(getBitmap(tweet.getProfileImageUrl()));
rowView.invalidate();
return rowView;
}
public static Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection() .getInputStream());
}
catch(Exception ex) {return null;}
}
}
So what's happening is that you're updating the tweets variable, which will update the Adapter's this.values value, HOWEVER that list is not what the adapter is using to render the list (if you want to know why, just dig into the ArrayAdapter code). The easiest way to fix the problem (and prevent further confusion) is to extend from BaseAdapter. It's a bit more work for you but you will have full control of what the adapter does (and will understand what's going on better).
To clean the code some more, you should also add a metod to your adapter that updates the value of this.values, you shouldn't depend on it referring to the same list as tweets.
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