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.
Related
I am developing an app in which my previous colleague used GridView to show data,but i want to use recyclerview with cardadapter, but I am not getting how to do that.
Here is my code for mainActivity:
public class ActivityCategoryList extends Activity {
GridView listCategory;
ProgressBar prgLoading;
TextView txtAlert;
// declare adapter object to create custom category list
AdapterCategoryList cla;
// create arraylist variables to store data from server
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String CategoryAPI;
int IOConnect = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setTitle("Category");
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listCategory = (GridView) findViewById(R.id.listCategory);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new AdapterCategoryList(ActivityCategoryList.this);
// category API url
CategoryAPI = Constant.CategoryAPI+"?accesskey="+Constant.AccessKey;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle list when clicked
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu page
Intent iMenuList = new Intent(ActivityCategoryList.this, ActivityMenuList.class);
iMenuList.putExtra("category_id", Category_ID.get(position));
iMenuList.putExtra("category_name", Category_name.get(position));
startActivity(iMenuList);
overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
});
}
#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_category, 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.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityCategoryList.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case R.id.refresh:
IOConnect = 0;
listCategory.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// clear arraylist variables before used
void clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data on list
// otherwise, show alert text
if((Category_ID.size() > 0) && (IOConnect == 0)){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from Category API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject category = object.getJSONObject("Category");
Category_ID.add(Long.parseLong(category.getString("Category_ID")));
Category_name.add(category.getString("Category_name"));
Category_image.add(category.getString("Category_image"));
Log.d("Category name", Category_name.get(i));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//cla.imageLoader.clearCache();
listCategory.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
}
Here is the Code for Adapter Class:
class AdapterCategoryList extends BaseAdapter {
private Activity activity;
public ImageLoader imageLoader;
public AdapterCategoryList(Activity act) {
this.activity = act;
imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return ActivityCategoryList.Category_ID.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(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_list_item, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb);
holder.txtText.setText(ActivityCategoryList.Category_name.get(position));
imageLoader.DisplayImage(Constant.AdminPageURL+ActivityCategoryList.Category_image.get(position), holder.imgThumb);
return convertView;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
I am new to this, and I think for recyclerview we need to create a list class also.
If anyone have any idea about this, can you help me?
I didn't check your whole code, but the key steps to archieve this is:
set an adapter
recyclerView.setAdapter(adpter);
and create and set an LayoutManager
int columns=3;
reyclerView.setLayoutManager(new GridLayoutManager(context,columns););
see RecyclerView docs and GridLayoutManager
GridView is different and GridLayoutManager is different.So, first you will have to create a recyclerview with the GridLayoutManager.
Remove GridView from respective xml and use Recyclerview with GridLayoutManager
Create Recycler Adapter using the AdapterCategoryList
I have a ListView which extends BaseAdapter. I have a array list. The ListView inflates and populates correctly. I am using the flipper view to change the layout to another but the problem is when i clicked on the first item it rotate but the item at third or sixth row will also rotate
list view how can i fix it i only want the image is change of selected item
ArrayList<product_data> al=new ArrayList<product_data>();
class product_data
{
String post_title;
String newprice;
String oldprice;
String image;
String id;
product_data(String post_title,String newprice,String oldprice,String image,String id)
{
this.post_title=post_title;
this.newprice=newprice;
this.oldprice=oldprice;
this.image=image;
this.id=id;
}
}
to add data in arraylist
try {
JSONObject parentObject = new JSONObject(json.toString());
JSONObject userDetails = parentObject.getJSONObject("response");
JSONArray jarray=userDetails.getJSONArray("products_data");
for(int i=0;i<jarray.length();i++)
{
System.out.println("From the Dataaaa");
JSONObject c = jarray.getJSONObject(i);
String details=c.getString("details");
String image=c.getString("image");
String catagory=c.getString("catagory");
String new_price=c.getString("new_price");
String title=c.getString("title");
String id1=c.getString("id");
System.out.println("from ther first image"+image);
System.out.println("from the sdafdfadf"+details);
al.add(new product_data(title, new_price, new_price, image, id1));
Adapter class
class MyAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return al.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return al.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View singleView, ViewGroup parent) {
// TODO Auto-generated method stub
final int ok=position;
if(singleView==null)
{
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
singleView = inflater.inflate(R.layout.product_ist_layout,parent,false);
System.out.println("from the if"+position);
viewAnimator = (ViewAnimator)singleView.findViewById(R.id.viewFlipper);
rootLayout = (View)singleView.findViewById(R.id.main_activity_root);
cardFace = (View)singleView.findViewById(R.id.main_activity_card_face);
cardBack = (View) singleView.findViewById(R.id.main_activity_card_back);
}
System.out.println("from the else");
System.out.println("Position in else"+position);
product_data a=al.get(position);
TextView tv1=(TextView)singleView.findViewById(R.id.textView2);
TextView tv2=(TextView)singleView.findViewById(R.id.textView3);
TextView tv3=(TextView)singleView.findViewById(R.id.textView1);
/**
* Bind a click listener to initiate the flip transitions
*/
viewAnimator.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// This is all you need to do to 3D flip
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
cardFace.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("positon"+ok);
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
cardBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT);
}
});
imgview1=(ImageView)singleView.findViewById(R.id.imageView4);
imgview1.setTag(position);
imgview1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println(position1);
String id=al.get(position1).id;
System.out.println("id from the list"+id);
Intent in=new Intent(product_list_Activity.this,rating_dialog.class);
in.putExtra("id",id);
startActivity(in);
}
});
ImageView imgview2=(ImageView)singleView.findViewById(R.id.imageView5);
imgview2.setTag(position);
imgview2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println(position1);
String id=al.get(position1).id;
System.out.println("id from the list"+id);
Intent in=new Intent(product_list_Activity.this,product_review.class);
in.putExtra("id",id);
startActivity(in);
}
});
tv3.setTag(position);
tv3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position1=(Integer)v.getTag();
System.out.println("from the review "+position1);
String id=al.get(position1).id;
globalvariables.product_id=id;
Intent in=new Intent(getApplicationContext(),review_product_tabbar.class);
startActivity(in);
}
});
tv1.setText(a.post_title);
tv2.setText("$"+a.oldprice);
tv1.setTypeface(tf);
tv2.setTypeface(tf);
tv3.setTypeface(tf);
int loader = R.drawable.ic_launcher;
ImageView image = (ImageView)singleView. findViewById(R.id.imageView1);
imgLoader.DisplayImage(a.image, loader, image);
Animation anim = new Rotate3dAnimation(90.0f, 0.0f, 100.0f, false, singleView);
anim.setDuration(1000l);
singleView.startAnimation(anim);
return singleView;
}
}
}
when i click on the first item it rotate and another view is coming
but when i scrolled the fourth item in below image will also rotate
i am using the on click listner on the relative views as in the code
Use ViewHolder for fill adapter. that may solve your issue
Example Code
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(context);
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.news_by_categories_content, null);
holder = new ViewHolder();
holder.strNewsTitle = (TextView) convertView
.findViewById(R.id.txtNewsByCategories);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
NewsListByCategoriesItem obj = new NewsListByCategoriesItem(); // My Model class getting value from this
obj = newsArray.get(position);
holder.strNewsTitle.setText(obj.getStrNewsTitle());
return convertView;
}
class ViewHolder {
TextView strNewsTitle;
}
}
In one of my app, I need to use AsyncTask. I need to get an image URL from an HTTP site. I have done this in the doInBackground method. I am getting the URL of that image as a string.
publishProgress(thumb);//thumb is string
then in
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
sample = new ArrayList<String>();
System.out.println("this is on progress..."+values[0]);
sample.add(values[0]);
GridviewAdapter_old go=new GridviewAdapter_old(getActivity(), sample);
gv.setAdapter(go);
// gv.setAdapter(ga);
}
public class GridviewAdapter_old extends BaseAdapter
{
private ArrayList<String> listCountry;
private Activity activity;
public GridviewAdapter_old(Activity activity, ArrayList<String> listCountry) {
super();
// this.listCountry = listCountry;
this.listCountry = new ArrayList<String>();
this.listCountry = listCountry;
// this.listFlag = listFlag;
this.activity = activity;
System.out.println("this is contry name " + this.listCountry);
// System.out.println("this is img name " + this.listFlag);
// System.out.println();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
System.out.println("len " + listCountry.size());
// return listCountry.size();
return listCountry.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listCountry.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
public ImageView imgViewFlag;
// public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (convertView == null) {
view = new ViewHolder();
convertView = inflator.inflate(R.layout.test, null);
view.imgViewFlag = (ImageView) convertView
.findViewById(R.id.grid_item_image);
// view.imgViewFlag.setBackgroundResource(R.drawable.view_default);
convertView.setTag(view);
}
else {
view = (ViewHolder) convertView.getTag();
}
try {
URL myUrl = new URL(listCountry.get(0));
InputStream inputStream = (InputStream) myUrl.getContent();
Drawable drawable = Drawable.createFromStream(inputStream, null);
view.imgViewFlag.setImageDrawable(drawable);
} catch (Exception e) {
System.out.println(e.getMessage());
}
/*
* Bitmap imageBitmap = null; //System.gc(); try { URL imageURL = new
* URL(listCountry.get(0));
* System.out.println("this is in last portion..."
* +listCountry.get(position)); imageBitmap =
* BitmapFactory.decodeStream(imageURL.openStream());
* view.imgViewFlag.setImageBitmap(imageBitmap); //
* view.txtViewTitle.setText(listCountry.get(position)); //
* view.imgViewFlag.setImageResource(listFlag.get(position));
*
* } catch (Exception e) { System.out.println("this is error " +
* e.getMessage()); }
*/
return convertView;
}
}
The problem is:
I am not getting an image from the URL (that is getting from thumb (publishProgress(thumb);)
I am not getting the multiple images.
you are only getting one in your list because every time you call onProgressUpdate you create a new list.
You dont want to use onProgressUpdate to populate your list, that would be an insane amount of overhead. Instead you want to create your list inside your doInBackground then pass that list to your onPostExecute then put the new list to the adapter and call notifyDatasetChanged on the adapter to refresh the list.
in short, create the adapter (class wide variable), create an ArrayList (class wide variable) and everytime a change is made the the list all you have to do is call notifyDatasetCHanged on the adapter
ArrayList<String> list = new ArrayList<String();
ArrayAdapter adapter;
public class AsyncTask.....
#Override
protected Void doInBackground(Void... params){
...
list.add(stuff);
}
#Override
protected Void onPostExecute(Void params){
adapter.notifyDatasetChanged();
}
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().
I have made an app in which i am using Two Tabs,
First Tab, to show list of Products [Menu Tab]
Second Tab, to show products added by you [Cart Tab]
Here i am allowing user to add products to cart, update quantity for product and show total amount of all the Items.
In my code i am facing very small problem but i am not getting any way for last two days to resolve this.
Problem:
Whenever i do click on Cart Tab to view products, those i have selected to buy and then again move back to Menu Tab to select few more products to buy and then again do click on Cart Tab to view all products i have selected, Here i am able to view Selected Product but not able to view updated quantity and not getting any change in Total Amount [Getting total of all previous added items only, not for those i have added second time...]
Please tell me where i am missing, to get updated quantity and to get change in total price, what code i need to add and where i need to add in my ViewCartActivity class
ViewCartActivity.Java:
public class ViewCartActivity extends Activity {
TextView mTxtViewGrandTotal;
String mGrandTotal ;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewcartactivity);
ListView mLstView1 = (ListView) findViewById(R.id.listView1);
mTxtViewGrandTotal = (TextView) findViewById(R.id.mTxtViewGrandTotalValue);
ViewCartAdapter mViewCartAdpt = new ViewCartAdapter(ViewCartActivity.this);
mLstView1.setAdapter(mViewCartAdpt);
if (Constants.mItem_Detail.size() > 0)
{
Double mGTotal = Double.parseDouble(Constants.mItem_Detail.get(0).get(SingleProductActivity.KEY_TOTAL));
for (int i = 1; i < Constants.mItem_Detail.size(); i++) {
mGTotal = mGTotal + Double.parseDouble(Constants.mItem_Detail.get(i).get(SingleProductActivity.KEY_TOTAL));
}
mGrandTotal = String.valueOf(mGTotal);
mTxtViewGrandTotal.setText(mGrandTotal);
ImageButton mImgViewCart = (ImageButton) findViewById(R.id.back_btn);
mImgViewCart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mViewCartIntent = new Intent(ViewCartActivity.this, com.version.bajrang.january.menu.ArrowsActivity.class);
startActivity(mViewCartIntent);
}
});
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
System.out.println("onResume list current size "+Constants.mItem_Detail.size());
super.onResume();
}
}
In Logcat, i am getting:
onResume list current size 3 [Number of Records]
TabActivity.Java:
private void setTabs()
{
addTab("Order", R.drawable.tab_order, CategoryActivity.class);
addTab("Cart", R.drawable.tab_cart, ViewCartActivity.class);
}
#Override
public void onBackPressed() {
// Code to update product Quantity
super.onBackPressed();
Constants.mItem_Detail.clear();
}
ViewCartAdapter.Java:
public class ViewCartAdapter extends BaseAdapter {
Activity activity;
LayoutInflater inflater;
public ViewCartAdapter(Activity a) {
// TODO Auto-generated constructor stub
activity = a;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return Constants.mItem_Detail.size();
}
public Object getItem(int position) {
//return position;
return Constants.mItem_Detail.get(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
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.viewcartlist, null);
TextView title = (TextView) vi.findViewById(R.id.title);
TextView qty = (TextView) vi.findViewById(R.id.qty);
TextView cost = (TextView) vi.findViewById(R.id.cost);
HashMap<String, String> item = new HashMap<String, String>();
item = Constants.mItem_Detail.get(position);
// Setting all values in listview
title.setText(item.get(SingleProductActivity.TAG_NAME));
qty.setText(item.get(SingleProductActivity.KEY_QTY));
cost.setText(item.get(SingleProductActivity.TAG_DURATION));
return vi;
}
}
Rakesh you have written everything needed in your program, just need to move from onCreate() to onResume() Method in ViewCartActivity
Like this:
public class ViewCartActivity extends Activity
{
TextView mTxtViewGrandTotal;
String mGrandTotal ;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewcartactivity);
ListView mLstView1 = (ListView) findViewById(R.id.listView1);
mTxtViewGrandTotal = (TextView) findViewById(R.id.mTxtViewGrandTotalValue);
ViewCartAdapter mViewCartAdpt = new ViewCartAdapter(ViewCartActivity.this);
mLstView1.setAdapter(mViewCartAdpt);
ImageButton mImgViewCart = (ImageButton) findViewById(R.id.back_btn);
mImgViewCart.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mViewCartIntent = new Intent(ViewCartActivity.this, com.version.bajrang.january.menu.ArrowsActivity.class);
startActivity(mViewCartIntent);
}
});
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("onResume list current size " + Constants.mItem_Detail.size());
if (Constants.mItem_Detail.size() == 0)
{
return;
}
Double mGTotal = Double.parseDouble(Constants.mItem_Detail.get(0).get(SingleProductActivity.KEY_TOTAL));
for (int i = 1; i < Constants.mItem_Detail.size(); i++)
{
mGTotal = mGTotal + Double.parseDouble(Constants.mItem_Detail.get(i).get(SingleProductActivity.KEY_TOTAL));
}
mGrandTotal = String.valueOf(mGTotal);
mTxtViewGrandTotal.setText(mGrandTotal);
}
}