Dynamic Separator in ListView - android

I want to parse json into list view.
{
"Submenus": [
{
"MenuName": "Pizza",
"SubMenu": [
"Pizza Margherita ",
"Pizza al Prosciutto",
"Pizza al Peperoncino "
]
},
{
"MenuName": "Bøffer",
"SubMenu": [
"Oksekødmørbrad"
]
},
{
"MenuName": "Dessert",
"SubMenu": [
"Chokolade kage"
]
}
]
}
My class is as follows.
public class MenuTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
// Getting JSON String from URL..............
JSONObject jsonObject = jParser.makeHttpRequest(
"http://smartaway.dk/json/submenu.php?resid=" + res_id,
"POST", params);
try {
bestdeal = jsonObject.getJSONArray(TAG_MENU);
// / LOOping through AllEvents........
for (int i = 0; i < bestdeal.length(); i++) {
JSONObject e = bestdeal.getJSONObject(i);
String resname = e.getString(TAG_MENUNAME);
String city_state = e.getString(TAG_PRICE);
// Creating New HAsh Map.........
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_ID, id);
map.put(TAG_MENUNAME, resname);
map.put(TAG_PRICE, city_state);
/*
* map.put(TAG_STREET, street); map.put(TAG_COUSINE,
* cousine); map.put(TAG_RES_LOGO, reslogo);
*/
// adding HashList to ArrayList
bestdeal_list.add(map);
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
MenuAdapter menuAdapter=new MenuAdapter(RestaurantDetails.this.getParent(),bestdeal_list);
//setListAdapter(menuAdapter);
list.setAdapter(menuAdapter);
}
});
}
// }
}
Custom Adapter class is as follows.
public class MenuAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public MenuAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.menu_list, null);
TextView menuname = (TextView) vi.findViewById(R.id.textView1); // title
TextView price = (TextView) vi.findViewById(R.id.textView3);
HashMap<String, String> events = new HashMap<String, String>();
events = data.get(position);
String menustr = events.get(RestaurantDetails.TAG_MENUNAME);
String pricestr = events.get(RestaurantDetails.TAG_PRICE);
menuname.setText(menustr);
price.setText(pricestr);
return vi;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return super.getItemViewType(position);
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return super.getViewTypeCount();
}
}
I just want to separate the listview from Menuname. Each Menuname should appear on some textview with background then its respective submenus must be shown under that, then another mainmenu and so on. Please suggest how to implement that and how to modify adapter class.

What you basically want to do is to use a custom adapter, most likely derived from BaseAdapter. You will need to override getViewTypeCount() and return the number of different kinds of list items that you have in the list. In your case it's 2 since you have menu names and normal list items.
You will also have to override getItemViewType(position) and return either a 0 if the item at the specified position is a normal list item or a 1 if it's a menu name.
Finally you'll also have to override getView() and return a list item of the appropriate type (menu name or normal list item), based on getItemViewType().
There should be several snippets of code that already does this if you Google a bit. I wrote a SectionedAdapter that does this as well. It's a generic class and it handles sections/heading of a certain type (can be String or some specific class such as Section, Header or MenuName) and section contents as another type. Subclass it and implement the getSectionView() and getItemView(). Add sections and items using addSection() and addItem().

Related

how to show selected data of one custom list to another custom list view on same activity

I have created two textview and one editText when i enter the edit text value and then click on the button to get both textview and edittext value in the second value and which will show in second listview but it will show all data from first list view.
ArrayList<HashMap<String, String>> MyArrList;
String rate;
String itemn;
String quan;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuitem);
final ListView lisView1 = (ListView)findViewById(R.id.listView1);
final ListView lisView2 = (ListView)findViewById(R.id.listView2);
MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
/*** Rows 1 ***/
map = new HashMap<String, String>();
map.put("ID", "Butterscotch");
map.put("Code", "Rs 10");
MyArrList.add(map);
/*** Rows 2 ***/
map = new HashMap<String, String>();
map.put("ID", "Birthday Cake");
map.put("Code", "Rs 100");
MyArrList.add(map);
/*** Rows 3 ***/
map = new HashMap<String, String>();
map.put("ID", "Black Crunch");
map.put("Code", "Rs 102");
MyArrList.add(map);
/*** Rows 4 ***/
map = new HashMap<String, String>();
map.put("ID", "Industrial Chocolate");
map.put("Code", "Rs 200");
MyArrList.add(map);
/*** Rows 5 ***/
map = new HashMap<String, String>();
map.put("ID", "Coffee Molasses Chip");
map.put("Code", " Rs 500");
MyArrList.add(map);
/*** Rows 5 ***/
map = new HashMap<String, String>();
map.put("ID", "Coffee Molasses Chip");
map.put("Code", " Rs 500");
MyArrList.add(map);
lisView1.setAdapter(new CountryAdapter(this));
// Get Item Input
lisView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(Mmnue.this,""+ position ,Toast.LENGTH_LONG).show();
}
});
Button btnGetItem = (Button) findViewById(R.id.btnGetItem);
btnGetItem.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
TextView txtCode = (TextView)findViewById(R.id.ColCode);
TextView itemnm = (TextView)findViewById(R.id.ColID);
EditText txtInput = (EditText)findViewById(R.id.txtInput);
rate = txtCode.getText().toString();
itemnam = txtInput.getText().toString();
quan= itemnm.getText().toString();
int count = lisView1.getAdapter().getCount();
Toast.makeText(Mmnue.this, itemnam + ", " + rate+ " , " + quan ,Toast.LENGTH_LONG).show();
lisView2.setAdapter(new CountryAdapter2(getApplicationContext()));
}
});
}
public class CountryAdapter extends BaseAdapter
{
private Context context;
public CountryAdapter(Context c)
{
//super( c, R.layout.activity_column, R.id.rowTextView, );
// TODO Auto-generated method stub
context = c;
}
public CountryAdapter(OnClickListener onClickListener) {
// TODO Auto-generated constructor stub
}
public int getCount() {
// TODO Auto-generated method stub
return MyArrList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_mmnue, null);
}
// ColID
TextView txtID = (TextView) convertView.findViewById(R.id.ColID);
txtID.setText(MyArrList.get(position).get("ID") +".");
// ColCode
TextView txtCode = (TextView) convertView.findViewById(R.id.ColCode);
txtCode.setText(MyArrList.get(position).get("Code"));
return convertView;
}
}
public class CountryAdapter2 extends BaseAdapter
{
private Context context;
public CountryAdapter2(Context c)
{
//super( c, R.layout.activity_column, R.id.rowTextView, );
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return MyArrList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.activity_mmnue, null);
}
// ColID
TextView txtID = (TextView) convertView.findViewById(R.id.ColID);
//txtID.setText(MyArrList.get(position).get("ID") +".");
txtID.setText(quan);
// ColCode
TextView txtCode = (TextView) convertView.findViewById(R.id.ColCode);
// txtCode.setText(MyArrList.get(position).get("Code"));
txtCode.setText(rate);
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
but it will show all data from first list view.
Because you are returning MyArrList.size(); from getCount() of CountryAdapter2. so change it to 1 because you showing only single row in second ListView as:
public int getCount() {
// TODO Auto-generated method stub
return 1;
}

How to Implement on scroll load ListView in Android?

I have implemented listview in fragment. In that listview i have used custom adapter to display images with their description. Data is coming from web server. There are many list items with image so I'd like to implement on scroll load ListView for the same.
Which approach should i follow to do the same? I have tried to google it and found some sample but it does not fit into my requirement.
Here is the code of my Fragment containing listview. Thanks in advance.
FragmentTab1.class
public class FragmentTab1 extends Fragment implements
AdapterView.OnItemClickListener {
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
JSONArray AdsArray = null;
String TAG_IMAGE = "image";
String TAG_DISCRIPTION = "description";
ListView lv;
final Context context = getActivity();
static ArrayList<HashMap<String, String>> adList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,false);
options = new DisplayImageOptions.Builder().showStubImage(R.drawable.no_image).cacheInMemory().cacheOnDisc()
.bitmapConfig(Bitmap.Config.RGB_565).build();
lv = (ListView) rootView.findViewById(R.id.listView1);
lv.setOnItemClickListener(this);
adList = new ArrayList<HashMap<String, String>>();
new LoadMyAds().execute();
return rootView;
}
class LoadMyAds extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
String type = "all";
JSONObject json = userFunction.myAds(userid, type);
try {
if (json.getString("status") != null) {
String res = json.getString("status");
if (Integer.parseInt(res) == 1) {
adList.clear();
AdsArray = json.getJSONArray("myadslistsArray");
for (int i = 0; i < AdsArray.length(); i++) {
JSONObject c = AdsArray.getJSONObject(i);
String description = c.getString(TAG_DISCRIPTION);
String image = c.getString(TAG_IMAGE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_IMAGE, image);
map.put(TAG_DISCRIPTION, description); adList.add(0, map);
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
"parsing error", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// image parameter need to be added
lv.setAdapter(new CustomAdapter(adList));
}
}
class CustomAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> locallist;
public CustomAdapter(ArrayList<HashMap<String, String>> list) {
// TODO Auto-generated constructor stub
locallist = list;
imageLoader.init(ImageLoaderConfiguration
.createDefault(getActivity()));
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return locallist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
// return null;
return getItem(getCount() - position - 1);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
if (row == null) {
row = getActivity().getLayoutInflater().inflate(
R.layout.ad_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.desc= (TextView) row.findViewById(R.id.title);
viewHolder.img = (ImageView) row.findViewById(R.id.thumbImage);
row.setTag(viewHolder);
}
final ViewHolder holder = (ViewHolder) row.getTag();
holder.desc.setText(""+locallist.get(position).get(TAG_DISCRIPTION));
imageLoader.displayImage(locallist.get(position).get(TAG_IMAGE),
holder.img, options);
return row;
}
}
class ViewHolder {
protected TextView desc;
protected ImageView img;
}
}
Attach scroll listener to the listView
lv.setOnScrollListener(new EndlessScrollListener());
Here is the class implementation:
class EndlessScrollListener implements OnScrollListener {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
new LoadMyAds().execute();
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}

Android how to display arraylist index numbers in my dynamic listview

Sorry for my English,How i can show arraylist index numbers in my dynamic listview?
for example in my app when listview display,in a listview every cell have a index number display like first cell 1,second cell 2,third cell 3 and so on..how i can implement this?Thanks in advance.
This is the screen shot:
in my screen shot see the left int number 1.and now want to in 2nd cell display 2 and so on..
This is my activity:
public class Artists extends Activity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// This is not using now if you want you can remove its all references :)
ArrayList<HashMap<String, String>> albumsList;
ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
private LazyAdapterArtist mLazyAdatper = null;
private ArrayList<String> array_sort = new ArrayList<String>();
int textlength = 0;
// albums JSONArray
JSONArray albums = null;
LinearLayout ll_artists_chart;
LinearLayout ll_artists_newrelease;
private EditText etSearch;
private static String URL_ALBUMS = "My URL";
// JSON Node names
private static final String TAG_CONTACTS = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private ListView lv = null;
EditText et_artists_searchWord;
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.artists);
lv = (ListView) findViewById(R.id.artist_main_list_id);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(Artists.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
/**
* Listview item click listener TrackListActivity will be lauched by
* passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
}
});
ll_artists_chart = (LinearLayout) findViewById(R.id.ll_artists_chart);
ll_artists_newrelease = (LinearLayout) findViewById(R.id.ll_artists_newrelease);
et_artists_searchWord = (EditText) findViewById(R.id.et_artists_searchWord);
et_artists_searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOs, true);
mAdapterDTOs.addAll(list);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
ll_artists_chart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), ChartActivity.class);
startActivity(intent);
// finish();
}
});
ll_artists_newrelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), NewReleases.class);
startActivity(intent);
//finish();
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Artists.this);
pDialog.setMessage("Listing Artists ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
//List<NameValuePair> params = new ArrayList<NameValuePair>();
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_ALBUMS);
// getting JSON string from URL
//String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", params);
// Check your log cat for JSON reponse
Log.i("Albums JSON: ", "> " + json);
try {
//albums = new JSONArray(json);
albums = json.getJSONArray(TAG_CONTACTS);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
/*String EateryThmbnailUrl = c
.getString(TAG_THMBNAIL_URL);*/
// ~\/Uploads\/EateryImages\/\/7\/41283f1f-8e6f-42d4-b3c1-01f990efb428.gif
/*EateryThmbnailUrl = HOST_URL
+ EateryThmbnailUrl.replace("~", "");*/
AdapterDTOArtist adapterDTO = new AdapterDTOArtist();
adapterDTO.setmTag_Id(id);
adapterDTO.setmTag_Name(name);
// adapterDTO.setmImage_URL(EateryThmbnailUrl);
mAdapterDTOs.add(adapterDTO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
albumsList.add(map);
}
} else {
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// updating listview
mLazyAdatper = new LazyAdapterArtist(Artists.this,
mAdapterDTOs);
lv.setAdapter(mLazyAdatper);
// mLazyAdatper.setDataSet(mAdapterDTOs);
}
});
}
}
public static List<AdapterDTOArtist> filter(String string,
Iterable<AdapterDTOArtist> iterable, boolean byName) {
if (iterable == null)
return new LinkedList<AdapterDTOArtist>();
else {
List<AdapterDTOArtist> collected = new LinkedList<AdapterDTOArtist>();
Iterator<AdapterDTOArtist> iterator = iterable.iterator();
if (iterator == null)
return collected;
while (iterator.hasNext()) {
AdapterDTOArtist item = iterator.next();
collected.add(item);
}
return collected;
}
}
}
My AdapterDTOArtist class :
public class AdapterDTOArtist {
private String mTag_Id;
private String mTag_Name;
public String getmTag_Name() {
return mTag_Name;
}
public void setmTag_Name(String mTag_Name) {
this.mTag_Name = mTag_Name;
}
public String getmTag_Id() {
return mTag_Id;
}
public void setmTag_Id(String mTag_Id) {
this.mTag_Id = mTag_Id;
}
}
My LazyAdapterArtist class:
public class LazyAdapterArtist extends BaseAdapter {
private Context mContext = null;
private ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
public LazyAdapterArtist(Context context,
ArrayList<AdapterDTOArtist> mAdapterDTOs2) {
// TODO Auto-generated constructor stub
this.mContext = context;
this.mAdapterDTOs = mAdapterDTOs2;
}
public void setDataSet(ArrayList<AdapterDTOArtist> adapterDTOs) {
this.mAdapterDTOs = adapterDTOs;
notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mAdapterDTOs.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder mHolder = new ViewHolder();
if (row == null) {
// Cell is inflating for first time
row = LayoutInflater.from(mContext)
.inflate(com.whizpool.triplevmusic.R.layout.row_artists,
null, false);
mHolder.mNameTxt = (TextView) row
.findViewById(com.whizpool.triplevmusic.R.id.tv_row_artists);
row.setTag(mHolder);
} else {
// recycling of cells
mHolder = (ViewHolder) row.getTag();
}
mHolder.mNameTxt.setText(mAdapterDTOs.get(position).getmTag_Name());
return row;
}
static class ViewHolder {
TextView mNameTxt = null;
}
}
just want to display my arraylist cells serialwise like first cell is 1,2nd cell 2 and so on
in your listview adapter, on getView() method, you can use the position for that purpose. If you don't have any textView to show the number, first add it to your listview item, then use it in getView() method
Add a new textview to show your position number;
static class ViewHolder {
TextView mNameTxt = null;
TextView mSeqNo; //new
}
Then use it in getView() method,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder mHolder = new ViewHolder();
if (row == null) {
// rest of your code
mHolder.mSeqNo = (TextView)row.findViewById(R.id.your_text_view);
row.setTag(mHolder);
} else {
// recycling of cells
mHolder = (ViewHolder) row.getTag();
}
//rest of your code
mHolder.mSeqNo.setText("" + position);
return row;
}
Using the position param in getView method is sufficient. It starts from 0 (the first index), then 1, 2,3 ...
mHolder.mSeqNo.setText("" + (position+1));
This would start the seq numbers from 1, like 1, 2, 3,..... and so on to the end of the list. But giving mHolder.mSeqNo.setText("" + (position) starts your number from 0, since list starts with 0 (the first value of index). All the best!

How to make a BaseAdapter class part of an asynctask - Android [duplicate]

This question already has answers here:
BaseAdapter class wont setAdapter inside Asynctask - Android
(4 answers)
Closed 9 years ago.
I have an asynctask that gathers comments, usernames, and numbers by using a JSON method. Then I have a class that extends BaseAdapter that suppose to put the comments and usernames into a listView. The problem is how can I get the comments, usernames and numbers to the BaseAdapter class? Here is my current code
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
l1=(ListView)findViewById(R.id.list);
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
}
}
new loadComments().execute();
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(Context ctx_invitation, String[] comments, String[] Numbers, String[] usernames)
{
super();
this.ctx_invitation = ctx_invitation;
listComments = comments;
listNumbers = Numbers;
listUsernames = usernames;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
overwrite the values of the adapter you have implemented or add setters for them. Then set the values and make sure you call notifyDatasetChanged on the adapter.
You can either reference the adapter directly if it is a global variable or pass it in the constructor of your AsyncTask
In onPostExecute you can create a new BaseAdapter with the new data and then use setAdapter to set it as the adapter for your ListView. Or, as already said, you can use setters to update data in your current adapter and then notify the ListView that it should redraw itself.
By the very nature of AsyncTask you can update your UI wherever you want in onPreExecution, onProgressUpdate and onPostExecution.

Galleryview in android

Hi i am very new to this android..Actually i am trying to display 1 heading and description below it in a screen.I have done that using Galleryview.I don't know whether this is correct way to do this r not..
My actually idea is..In galleryview if i swipe the screen the next(heading and description should come) but i can't do this..SO i tried to keep next and previous option to do this..But this also i cant do ..I know that i am doing in wrong way.Please suggest me some goodway to do this.. I am ready to give more explanation if needed..The code below posted is what i done..
My Activity code:
public class NewsDescription extends Activity
{
// private String url = "http://m.indiatoday.in/xml/stories/"+(String)context.getInstance().getAppVariable("storyurl");
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newsdesgallery);
Gallery gl=(Gallery)findViewById(R.id.GalleryNewsDesc);
NewsDescriptionAdapter adapter =new NewsDescriptionAdapter(this);
gl.setAdapter(adapter);
}
}
My adapter class:
public class NewsDescriptionAdapter extends BaseAdapter
{
private static Context contxt;
String[] body= {};//new String[30];
String[] heading= {};//new String[30];
NewsDescriptionAdapter(Context conxt)
{
// System.out.println("inside cons");
this.contxt=conxt;
getelement();
}
public void getelement()
{
// System.out.println("Inside getElement");
String[] url=context.getInstance().getselectedUrl();
// System.out.println("After url");
// System.out.println("count="+(String)context.getInstance().getAppVariable("count"));
int count = Integer.parseInt((String)context.getInstance().getAppVariable("count"));
// System.out.println("count="+count);
// System.out.println("after count="+url[count]);
String URL = "http://xxxx.in/xml/stories/"+url[count];
// System.out.println("url="+URL);
TaplistingParser parser = new TaplistingParser();
// try {
// url=URLEncoder.encode(url, "UTF-8");
// } catch (UnsupportedEncodingException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
URL=URL.replace(" ","");
// System.out.println("url="+url);
String xml= parser.getXmlFromUrl(URL);
Document doc=parser.getDomElement(xml);
NodeList n1 = doc.getElementsByTagName("item");
body = new String[n1.getLength()];
heading = new String[n1.getLength()];
for( int i = 0 ; i < n1.getLength(); i++ )
{
// HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) n1.item(i);
body[i]=parser.getValue(e, "body");
heading[i]=parser.getValue(e, "headline");
// map.put("Body", parser.getValue(e,"body"));
// menuItems.add(map);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return body.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return body[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
// System.out.println("body="+body[position]);
if (convertView == null)
{
//this should only ever run if you do not get a view back
LayoutInflater inflater = (LayoutInflater) contxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.newsdescriptionrow, null);
}
TextView next =(TextView)convertView.findViewById(R.id.nextnews);
// final Gallery gal=(Gallery)convertView.findViewById(R.id.GalleryNewsDesc);
next.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
System.out.println("Inside next");
int count = Integer.parseInt((String)context.getInstance().getAppVariable("count"));
count++;
context.getInstance().setAppVariable("count", Integer.toString(count));
}
});
TextView textViewhead = (TextView) convertView
.findViewById(R.id.name_DescHeading);
textViewhead.setText(heading[position]);
TextView textView = (TextView) convertView
.findViewById(R.id.name_Desclabel);
textView.setText(body[position]);
return convertView;
}
}
You should not use gallery widget any more as it is deprecated in newer version of android. Instead you can use a ViewPager from android support jar.
You can find an example in here :
https://github.com/nostra13/Android-Universal-Image-Loader
Lookout for ImagePagerActivity in the above code. You can create a custom cell with an imageview and textview for description (modify the item_pager_image xml). Let me know how it goes.

Categories

Resources