Wrong item position into ListView - java

I need to open a frameLayout details into a listView, but when I press the buttonDetails, it opens a wrong frameLayout.
here is the code of my adapterView
public class SitesAdapter extends ArrayAdapter<AtlantisSite> {
ImageLoader imageLoader;
DisplayImageOptions options;
FrameLayout frameLayout;
public SitesAdapter(Context ctx, int textViewResourceId, List<AtlantisSite> sites) {
super(ctx, textViewResourceId, sites);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
}
/*
* (non-Javadoc)
* #see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*
* This method is responsible for creating row views out of a AtlantisSite object that can be put
* into our ListView
*/
#Override
public View getView(final int pos, final View convertView, final ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("AtlantisSites", "getView pos = " + pos);
//ViewHolder mainViewHolder = null;
final ViewHolder viewHolder;
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
viewHolder = new ViewHolder();
viewHolder.btnDownload = (Button) row.findViewById(R.id.btnDownload);
viewHolder.btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer pos=(Integer)v.getTag();
Log.i("AtlantisSites", "getView pos = " + pos);
//String url = getItem(pos).getLink();
DownloadZip zipActivity = new DownloadZip();
zipActivity.DownloadFromUrlZip();
//Intent i = new Intent(Intent.ACTION_VIEW);
//i.setData(Uri.parse(url));
//Intent zipActivity = new DownloadZip();
//zipActivity.start...;
//Toast.makeText(getContext(), "Downloading " + pos, Toast.LENGTH_SHORT).show();
}
});
viewHolder.btnDetails = (Button) row.findViewById(R.id.btnDetails);
viewHolder.btnDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Integer pos = (Integer) v.getTag();
//Log.i("AtlantisSites", "getView pos = " + pos);
getItemId(pos);
if(frameLayout.getVisibility()==View.GONE){
showFrameLayout();
} else {
hideFrameLayout();
}
}
});
row.setTag(viewHolder);
} else{
viewHolder = (ViewHolder) row.getTag();
}
//Get our View References
final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);
TextView nameTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView titleTxt = (TextView)row.findViewById(R.id.titleTxt);
//Button btnDownload = (Button)row.findViewById(R.id.btnDownload);
TextView summaryIta = (TextView)row.findViewById(R.id.textViewSummaryItaRow);
TextView summaryEng = (TextView)row.findViewById(R.id.textViewSummaryEngRow);
TextView priceItaTxt=(TextView)row.findViewById(R.id.txtViewPriceIta);
TextView priceEngTxt=(TextView)row.findViewById(R.id.txtViewPriceEng);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
frameLayout = (FrameLayout)row.findViewById(R.id.frame_layout_listview);
//Set the relavent text in our TextViews
nameTxt.setText(getItem(pos).getName());
titleTxt.setText(getItem(pos).getTitle());
summaryIta.setText(getItem(pos).getSummaryIta());
summaryEng.setText(getItem(pos).getSummaryEng());
viewHolder.btnDetails.setTag(pos);
return row;
}
public class ViewHolder{
Button btnDownload;
Button btnDetails;
}
private void showFrameLayout(){
frameLayout = (FrameLayout) frameLayout.findViewById(R.id.frame_layout_listview);
frameLayout.setVisibility(View.VISIBLE);
}
private void hideFrameLayout(){
frameLayout = (FrameLayout) frameLayout.findViewById(R.id.frame_layout_listview);
frameLayout.setVisibility(View.GONE);
}
}
Something goes wrong with the position.
please help me to find error o solutions.
thanks

in the method showFrameLayout() you dont have any reference to the current frame layout you want to show, remove the methods show/hide frameLayout and inside the listener for the details btn
viewHolder.btnDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Integer pos = (Integer) v.getTag();
//Log.i("AtlantisSites", "getView pos = " + pos);
getItemId(pos);
FrameLayout detailsFrame = row.findViewById(R.id.frame_layout_listview);
if(detailsFrame.getVisibility()==View.GONE){
detailsFrame.setVisibility(View.VISIBLE);
} else {
detailsFrame.setVisibility(View.GONE);
}
}
});
As a general suggestion i would put my FrameLayout inside the viewholder, wich is exactly whats for.

I found the solution . I have to declare the Frame Layout final. It works
final FrameLayout detailsFrame = (FrameLayout)row.findViewById(R.id.frame_layout_listview);

Related

Add items price together in a listview android

I have a listview containing items name and price i made my code so when i click on one item it displays its price in a small dialog box at the bottom of the screen but now when i click another item i want to add that item's price to the first one and so on..
Here is my code for now:
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.price);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
LayoutInflater inflater2 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final Dialog mBottomSheetDialog = new Dialog(context, R.style.MaterialDialogSheet);
View content = inflater2.inflate(R.layout.activity_main2, null);
mBottomSheetDialog.setContentView(content);
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
final Dialog mBottomSheetDialog2 = new Dialog(context, R.style.MaterialDialogSheet);
final View content2 = inflater2.inflate(R.layout.smalldialog, null);
final TextView total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
total.setText(null);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
total.setText(String.valueOf(last));
mBottomSheetDialog2.show();
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
}
});
return rowView;
}
I tried using boolean but it didn't go as well as i expected.
I will appreciate any help!
Is all of your code (the getView() method) within your ArrayAdapter class? If so, move you listener register out into your Activity, and then the listener needs only pull the required value from the selected item and append it to a property of your Activity class, and then raise the view to show the running total.

Opening new view inside ViewPager

Using Devlight NavigationTabBar on my android app. Here's the whole code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horizontal_ntb);
initUI();
}
private void initUI() {
final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
viewPager.setAdapter(new PagerAdapter() {
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(final View view, final Object object) {
return view.equals(object);
}
#Override
public void destroyItem(final View container, final int position, final Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
final View viewNews = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp_list, null, false);
final View ViewSol = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_sol, null, false);
final View viewProfile = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_profile, null, false);
final View viewContact = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_contact, null, false);
View finalView = null;
if (position == 0) {
final RecyclerView recyclerView = (RecyclerView) viewNews.findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(
getBaseContext(), LinearLayoutManager.VERTICAL, false
)
);
recyclerView.setAdapter(new RecycleAdapter());
container.addView(viewNews);
finalView = viewNews;
} else if (position == 1) {
container.addView(viewSol);
finalView = viewSol;
} else if (position == 2) {
container.addView(viewProfile);
finalView = viewProfile;
} else if (position == 3){
container.addView(viewContact);
finalView = viewContact;
}
return finalView;
}
});
final String[] colors = getResources().getStringArray(R.array.default_preview);
final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_library),
Color.parseColor(colors[0]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_library))
.title("News")
.badgeTitle("+10")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_error_black_24dp),
Color.parseColor(colors[1]))
// .selectedIcon(getResources().getDrawable(R.drawable.ic_eighth))
.title("Solicitation")
//.badgeTitle("with")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_person_black_24dp),
Color.parseColor(colors[3]))
// .selectedIcon(getResources().getDrawable(R.drawable.ic_eighth))
.title("My Account")
//.badgeTitle("icon")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_phone_black_24dp),
Color.parseColor(colors[2]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_phone_black_24dp))
.title("Contact")
//.badgeTitle("state")
.build()
);
navigationTabBar.setModels(models);
navigationTabBar.setViewPager(viewPager, 2);
navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
navigationTabBar.getModels().get(position).hideBadge();
}
#Override
public void onPageScrollStateChanged(final int state) {
}
});
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
for (int i = 0; i < navigationTabBar.getModels().size(); i++) {
final NavigationTabBar.Model model = navigationTabBar.getModels().get(i);
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
//model.showBadge();
}
}, i * 100);
}
}
}, 500);
}
As you can see, whenever I choose a tab it opens the view inside the view pager.
However, I have no idea how to open another view when I click on a button. I tried to start a whole new activity with intent but it crashes and it's not really what I want.
What I want is to open the view on the viewpager ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
If I implement this:
public void openNewView(View view) {
//the code to open a view inside the viewpager should go here
}
How can I proceed?
Add a view to your viewPager in the layout that is originally set to Visibility = GONE or Invisible and change it to Visible when you want it to be visible on screen.
https://developer.android.com/reference/android/view/View.html#GONE
Or use a layoutInflater to add a view from another layout to your viewpager
https://developer.android.com/reference/android/view/LayoutInflater.html
To open a new view on click of some button you can do this:
Suppose that you want to have a new view on the first button, then in the method instantiateItem of PagerAdapter you can check if position is 0 or not.
If the position if 0, then you can inflate that layout which you want to display.
something like this:
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0)
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.your_layout, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
else if (position == 1)
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
else
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
}
To make your code more modular you can use make your custom fragments and and them in your adapter.
Hope this helps

list view adapter setting null object on custom dialog

hi friends i had tried to implement list view in the custom dialog and passing data dynamically by using JSON and searched everywhere but don't got any solution i had tried everything from past 3 days and also i don't see any wrong in my code too i had set adapter correctly i am getting this error
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
public class Cat_comment_adap extends BaseAdapter {
String cid;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
int idddget;
private LayoutInflater inflater;
private List<CurrentList> catlist;
private PopupWindow commentWindow;
ArrayList<CurrentList> commentlist = new ArrayList<CurrentList>();
Activity activity;
public Cat_comment_adap(Activity activity, List<CurrentList> catlist) {
this.activity = activity;
this.catlist = catlist;
}
#Override
public int getCount() {
return catlist.size();
}
#Override
public Object getItem(int i) {
return catlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.cat_row, viewGroup, false);
NetworkImageView singleimg = (NetworkImageView) view.findViewById(R.id.singleimg);
final ImageView agree = (ImageView) view.findViewById(R.id.agree);
ImageView commentbox = (ImageView) view.findViewById(R.id.commentbox);
commentbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
});
final CurrentList catertlist = catlist.get(i);
singleimg.setImageUrl(catertlist.getCatimg(), imageLoader);
idddget = catertlist.getCcids();
SharedPreferences eveid = activity.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
cid = eveid.getString("userid", "");
agree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android";
Log.d("Vote", "http://sampletemplates.net/majority/api.php?action=addVote&question_id=" + idddget + "&user_id=" + cid + "&vote=1&source=android");
JsonObjectRequest voting = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String votings = response.getString("status");
if (votings.equals("success")) {
agree.setImageResource(R.drawable.agreed);
Toast.makeText(activity, "Voted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Already Voted", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(voting);
}
});
return view;
}
public void onShowpopup(View v) {
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
// commentAdapter = new comment_adapter(activity, commentlist);
WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
commentWindow = new PopupWindow(popupview, width - 50, height - 400, true);
commentWindow.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.comment_bg));
commentWindow.setFocusable(true);
commentWindow.setOutsideTouchable(true);
commentWindow.showAtLocation(v, Gravity.BOTTOM, 0, 100);
commentsListView.setAdapter(new comment_adapter(activity,commentlist));
commentAdapter.notifyDataSetChanged();
}
Adapter class
public class comment_adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CurrentList> commentlist;
public comment_adapter(Activity activity, List<CurrentList> commentlist){
this.activity = activity;
this.commentlist = commentlist;
}
#Override
public int getCount() {
return commentlist.size();
}
#Override
public Object getItem(int i) {
return commentlist.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.comment_row, viewGroup, false);
TextView user_name = (TextView) view.findViewById(R.id.user_name);
TextView posttime = (TextView) view.findViewById(R.id.posttime);
TextView comtsdetails = (TextView) view.findViewById(R.id.comtsdetails);
CurrentList listofcomments = commentlist.get(i);
user_name.setText(listofcomments.getEvtusername());
posttime.setText(listofcomments.getTimetaken());
comtsdetails.setText(listofcomments.getEvcomment());
return view;
}
}
here in this class Cat_comment_adap in the method onShowpopup change
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) v.findViewById(R.id.commentsListView);
to
View popupview = layoutInflater.inflate(R.layout.current_comment_dialog, null);
ListView commentsListView = (ListView) popupview.findViewById(R.id.commentsListView);
because your inflating listview from this layout so u have to give the name of inflated layout object there not the parameter of the method
public void onClick(View view) {
onShowpopup(view);
Toast.makeText(activity, "Comments Button clicked", Toast.LENGTH_SHORT).show();
}
Here passed view is not R.layout.cat_row as you think but it's a button that was clicked.
So just use onShowpopup(self.view) and it will work :)
or change to onClick(View clickedButton)

Image Switcher Issue in Android

I am using image switcher to display several picture.
I have initialized the final Integer[] imageIDs = {} and use declare elements in it in If-Else statement which locates in the OnCreate. I do so because for each different places I would like to input different pictures into the imageIDs. In this example is "UK". So if another places was chosen, the imageIDs should have different pictures refer to.
Unfortunately there was nothing in the imageswitcher when I run the apps.
final Integer[] imageIDs = {};
private ImageSwitcher imageSwitcher;
DBAdapter dbAdapter;
final Context context = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.attraction_details);
Intent intent = getIntent();
String selectedSubArea = intent.getStringExtra("SelectedSubArea");
Button btnAddToTrip = (Button) findViewById(R.id.btnAddToTrip);
Button btnAddToFav = (Button) findViewById(R.id.btnAddToFav);
Button btnShowAttractionLocation = (Button) findViewById(R.id.btnShowAttractionLocation);
TextView description = (TextView) findViewById(R.id.description);
TextView address = (TextView) findViewById(R.id.address);
TextView openingHours = (TextView) findViewById(R.id.openingHours);
TextView contactNo = (TextView) findViewById(R.id.contactNo);
if (selectedSubArea.equals("UK"))
{
this.setTitle(selectedSubArea);
description.setText("desc");
address.setText("add");
latitude = 2.0057378;
longitude = 103.3760577;
openingHours.setText("n/a");
contactNo.setText("n/a");
final Integer[] imageIDs = {
R.drawable.uk_1,
R.drawable.uk_2,
R.drawable.uk_3};
name = selectedSubArea;
desc = description.toString();
add = address.toString();
opening = openingHours.toString();
contact = contactNo.toString();
dbAdapter = new DBAdapter(context);
imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher1);
imageSwitcher.setFactory(this);
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
imageSwitcher.setImageResource(imageIDs[position]);
}
});
}
}
public View makeView()
{
ImageView imageView = new ImageView(this);
imageView.setBackgroundColor(0x00000000);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return imageView;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
//---returns the number of images---
public int getCount()
{
return imageIDs.length;
}
//---returns the ID of an item---
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
Your global imageIDs array length is ZERO so its displayed nothing. You can't use final array in your case as the objects can varies depending on your selectedSubArea
Else
You can change your ImageAdapter like this then it will work
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
Integer[] local_imageIDs
public ImageAdapter(Context c, Integer[] local_imageIDs)
{
context = c;
this.local_imageIDs = local_imageIDs;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
//---returns the number of images---
public int getCount()
{
return local_imageIDs.length;
}
//---returns the ID of an item---
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView(context);
imageView.setImageResource(local_imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
then set this adapter as
gallery.setAdapter(new ImageAdapter(this, imageIDs));
And remove the global imageIDs

How to send Items from one activity to another on item checked

I want to send all selected items from my first activity to another activity on item checked. There are three classes in my app First is Appetizer class,second class is ItemListBaseAdapter class and third class is Manage class I want to send the checked item from Appetizers class to Manage class.If you need to know any other information let me know.
This is my Appetizer class
public class Appetizers extends Activity{
Button manage;
public static final String[] titles = new String[] { "Aloo Chat",
"Paneer Tikka", "Spring Roll", "Paneer Chilly", "Veg Roll","Rice balls","Pasta", };
public static final String totalPrice="0";
public static final int[] quantities = new int[]{ 0 };
public static final String[] price={"20","10","30","40","50","60","10"};
public static final Integer[] images = { R.drawable.a39,
R.drawable.a40, R.drawable.a41, R.drawable.a42,R.drawable.a74,R.drawable.a75,R.drawable.a76 };
public ItemListBaseAdapter adapter;
ListView listView;
public List<RowItem> rowItems;
Button add,sub;
public static Appetizers apti;
public RowItem item;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
apti=this;
// LinearLayout layout = (LinearLayout) getWindow().findViewById(R.id.button1);
// layout.addView(new Button(this));
manage=(Button) findViewById(R.id.manage);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
item = new RowItem(images[i], titles[i], quantities[0],price[i],totalPrice);
rowItems.add(item);
Log.e("item in appetizer", ""+item);
manage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// intt.putParcelable("myclass",rowItems);
// intt.putStringArrayListExtra("key", rowItems);
Intent i=new Intent(Appetizers.this,Manage.class);
startActivity(i);
}
});
}
listView = (ListView) findViewById(R.id.list);
ItemListBaseAdapter adapter = new ItemListBaseAdapter(this,
R.layout.item_details_view, rowItems);
Log.e("Row items in appetizer",""+rowItems);
listView.setAdapter(adapter);
}
}
This is my ItemListBaseAdapter class
class ItemListBaseAdapter extends ArrayAdapter<RowItem> {
public static ItemListBaseAdapter adapter;
Context context;
int getPosition;
int rowItem;
String check1;
public List<RowItem> rowItems;
/*
* here we must override the constructor for ArrayAdapter the only variable
* we care about now is ArrayList<RowItem> objects, because it is the list
* of objects we want to display.
*/
public ItemListBaseAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
adapter=this;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtTitle,txtPrice,ttprice;
TextView txtDesc;
Button add, sub,manage;
CheckBox check;
}
/*
* we are overriding the getView method here - this is what defines how each
* list item will look.
*/
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.item_details_view, null);
}
/*
* Recall that the variable position is sent in as an argument to this
* method. The variable simply refers to the position of the current
* object in the list. (The ArrayAdapter iterates through the list we
* sent it)
*
* Therefore, rowItem refers to the current RowItem object.
*/
RowItem rowItem = getItem(position);
if (rowItem != null) {
holder = new ViewHolder();
// This is how you obtain a reference to the TextViews
// Images,checkBox,Buttons.
// These TextViews are created in the XML files we defined.
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.ttprice=(TextView) convertView.findViewById(R.id.tPrice);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.check = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.add = (Button) convertView.findViewById(R.id.button1);
holder.sub = (Button) convertView.findViewById(R.id.button2);
// holder.manage = (Button) convertView.findViewById(R.id.manage);
// holder.check.setOnClickListener( new View.OnClickListener() {
// public void onClick(View v) {
// CheckBox cb = (CheckBox) v ;
// RowItem rowItem = (RowItem) cb.getTag();
// Toast.makeText(context,"Clicked on Checkbox: " + cb.getText() +" is " + cb.isChecked(), Toast.LENGTH_LONG).show();
// rowItem.setSelected(cb.isChecked());
// }
// });
/*
* holder.check.setOnClickListener( new View.OnClickListener() {
* public void onClick(View v) { CheckBox cb = (CheckBox) v ;
* RowItem rowItem = (RowItem) cb.getTag(); Toast.makeText(context,
* "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(),
* Toast.LENGTH_LONG).show(); rowItem.setSelected(cb.isChecked()); }
* });
*/
} else
{
holder = (ViewHolder) convertView.getTag();
}
/*holder = (ViewHolder) convertView.getTag();
*rowItem = rowItems.get(position); holder.txtTitle.setText(" (" +
*rowItem.getTitle() + ")"); holder.check.setText(rowItem.getName());
*holder.check.setChecked(rowItem.isSelected());
* holder.check.setTag(rowItem);
*/
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.txtPrice.setText(rowItem.getPrice());
Log.e("title",""+rowItem.getTitle());
Log.d("description",""+rowItem.getDesc());
Log.e("Price",""+rowItem.getPrice());
holder.imageView.setImageResource(rowItem.getImageId());
holder.add.setTag(position);
holder.sub.setTag(position);
//holder.manage.setTag(position);
holder.check.setTag(position);
holder.add.setEnabled(false);
holder.sub.setEnabled(false);
final RowItem finalRowItem = rowItem;
final ViewHolder viewHolderFinal = holder;
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity();
if (quantity >= 0) {
finalRowItem.setQuantity(quantity + 1); // update it by adding 1
quantity=finalRowItem.getQuantity();
if (quantity>=1) {
String p=finalRowItem.getPrice();
int x=Integer.parseInt(p);
int y=quantity*x;
String f=Integer.toString(y);
finalRowItem.setTotalPrice(f);
viewHolderFinal.ttprice.setText(finalRowItem.getTotalPrice());
}
viewHolderFinal.add.setEnabled(true);
viewHolderFinal.sub.setEnabled(true);
} else {
viewHolderFinal.add.setEnabled(false);
viewHolderFinal.sub.setEnabled(false);
}
// get the quantity for this row item
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc());
viewHolderFinal.add.setEnabled(true);
viewHolderFinal.sub.setEnabled(true);
String check =finalRowItem.getDesc()+finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getTotalPrice();
Toast.makeText(context,"Clicked on Checkbox check1: " +finalRowItem.getDesc()+finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getTotalPrice(), Toast.LENGTH_LONG).show();
Intent intt=new Intent(context,Manage.class);
intt.putExtra("allItem", check);
Log.d("final description in add", finalRowItem.getDesc());
// set the new description (that uses the updated qunatity)
}
});
holder.sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity();
if (quantity == 1) {
finalRowItem.setQuantity(quantity - 1);
Toast.makeText(context, "Item is unchecked", Toast.LENGTH_LONG).show();
viewHolderFinal.check.setChecked(false);
viewHolderFinal.add.setEnabled(false);
viewHolderFinal.sub.setEnabled(false);
} else {
viewHolderFinal.add.setEnabled(true);
viewHolderFinal.sub.setEnabled(true);
}
// get the quantity for this row item
finalRowItem.setQuantity(quantity - 1);
quantity=finalRowItem.getQuantity();
String p=finalRowItem.getPrice();
int x=Integer.parseInt(p);
int y=quantity*x;
String f=Integer.toString(y);
finalRowItem.setTotalPrice(f);
viewHolderFinal.ttprice.setText(finalRowItem.getTotalPrice());
//Toast.makeText(context, "898798",0).show();
// update it by subtracting 1
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc());
Log.d("final description in sub", finalRowItem.getDesc());
// set the new description (that uses the updated qunatity)
}
});
// the view must be returned to our activity
//Toast.makeText(context,"Quantity selected"+finalRowItem.getTotalPrice() ,Toast.LENGTH_SHORT).show();
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
if (cb.isChecked()) {
Log.d("checkbox checked", "checkbox checked");
// RowItem finalRowItem = (RowItem) cb.getTag();
Toast.makeText(context,"Clicked on Checkbox: " +finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getDesc()+" is " + cb.isChecked(), Toast.LENGTH_LONG).show();
// finalRowItem.setSelected(cb.isChecked());
viewHolderFinal.add.setEnabled(true);
viewHolderFinal.sub.setEnabled(true);
finalRowItem.quantity =finalRowItem.getQuantity();
finalRowItem.quantity = 1;
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc());
if (finalRowItem.quantity>=1) {
Log.e("checkbox checked-2", "checkbox checked-2");
String p=finalRowItem.getPrice();
int x=Integer.parseInt(p);
int y=finalRowItem.quantity*x;
String f=Integer.toString(y);
finalRowItem.setTotalPrice(f);
viewHolderFinal.ttprice.setText(finalRowItem.getTotalPrice());
//Toast.makeText(context, "898798",0).show();
Toast.makeText(context,"Clicked on Checkbox check1: " +finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getTotalPrice()+" is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}
} else {
if (finalRowItem.quantity>=1) {
Log.d("checkbox checked-3", "checkbox checked-3");
String p=finalRowItem.getPrice();
int x=Integer.parseInt(p);
int y=finalRowItem.quantity*x;
y=0;
String f=Integer.toString(y);
finalRowItem.setTotalPrice(f);
viewHolderFinal.ttprice.setText(finalRowItem.getTotalPrice());
//Toast.makeText(context, "898798",0).show();
}
finalRowItem.quantity = finalRowItem.getQuantity();
if (finalRowItem.quantity > 0) {
finalRowItem.quantity = 0;
}
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc());
Toast.makeText(context,"Clicked on Checkbox check2: " +finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getDesc()+finalRowItem.getQuantity()+" is " + cb.isChecked(), Toast.LENGTH_LONG).show();
viewHolderFinal.add.setEnabled(false);
viewHolderFinal.sub.setEnabled(false);
}
}
});
return convertView;
}
}
There are two easier ways by which you can send the item from one class to another:
1. Save the items in SharedPrefernces and access them in another class.
2. Send them as part of intent using putExtra() api.
Write your class which implements Parcelable. Pass its instance over the intent.
See this for usage.
You could implement Parcelable interface on your item.
First of all, your RowItem should implement Parcelable interface (ex: http://developer.android.com/reference/android/os/Parcelable.html)
Then you should use not List but ArrayList, and put this object in intent:
Intent i = ...;
i.putParcelableArrayListExtra(rowItems);
In your MainActivity or the activity where you the values , which you want to send to another activity, write below code.
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("Username", YOUR STRING);
editor.putString("EMAIL", YOUR STRING);
editor.commit();
its a key value pair, where username and EMAIL are key and value will be your string which you have to send to other activity.
Then in other activity where you want to retrieve the data add below code.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String text = preferences.getString("Username", "null");
String Email1=preferences.getString("EMAIL", "null");
String Email=Email1.toString();
Hope this helps.

Categories