Scrolling page in ViewPager works very slow - android

Scrolling page in ViewPager on HTC Desire X is very slow, on Samsung Galaxy S4 is ok.
In my app i have view pager which display nine items on every page.
Each item has: name, small image(25kb-50kb, 500x350), and short descriptions.
Each image is downloaded from url via Universal Image Loader
When i set to adapter more than 20 items viewpager works slow, and i had warnings:
Skipped XX frames! The application may be doing too much work on its main thread.
Here is my instantiateItem() code from my PagerAadapter:
public Object instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemsView = inflater.inflate(R.layout.item_pager, container,
false);
LinearLayout[] line = new LinearLayout[3];
line[0] = (LinearLayout)itemsView.findViewById(R.id.item_pager_first_line);
line[1] = (LinearLayout)itemsView.findViewById(R.id.item_pager_second_line);
line[2] = (LinearLayout)itemsView.findViewById(R.id.item_pager_third_line);
int i = 0;
for(LinearLayout layout : line){
TextView[] itemsName = new TextView[3];
LinearLayout[] itemsLayout = new LinearLayout[3];
itemsLayout[0] = (LinearLayout)layout.findViewById(R.id.item1_layout);
itemsLayout[1] = (LinearLayout)layout.findViewById(R.id.item2_layout);
itemsLayout[2] = (LinearLayout)layout.findViewById(R.id.item3_layout);
final ImageView[] itemsImage = new ImageView[3];
TextView[] desc = new TextView[3];
final int objectId1 = (position*9)+(i*3);
final int objectId2 = (position*9)+(i*3)+1;
final int objectId3 = (position*9)+(i*3)+2;
if(mItemsList.size()>objectId1){
// Set appropriate name of item.
itemsName[0] = (TextView)layout.findViewById(R.id.item1_name);
itemsName[0].setText(mItemsList.get(objectId1).getName());
//Set appropriate image of item
itemsImage[0] = (ImageView)layout.findViewById(R.id.item1_image);
mImageLoader.displayImage(Image.getRegularUrl(mItemsList.get(objectId1)
.getImages()[0].getFilename()),itemsImage[0],mOptions);
desc[0] = (TextView)layout.findViewById(R.id.item1_desc_text_view);
desc[0].setText(mItemsList.get(objectId1).getDesc()));
//Set action after click on item.
itemsLayout[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onMyClikItem(mItemsList.get(objectId1).getItemId());
}
});
//Set action after long click on item.
itemsLayout[0].setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
onMyLongClikItem(objectId1);
return true;
}
});
// Check next item.
if(mItemsList.size()>objectId2){
itemsName[1] = (TextView)layout.findViewById(R.id.item2_name);
itemsName[1].setText(mItemsList.get(objectId2).getName());
itemsImage[1] = (ImageView)layout.findViewById(R.id.item2_image);
mImageLoader.displayImage(Image.getRegularUrl(mItemsList.get(objectId2)
.getImages()[0].getFilename()),itemsImage[1],mOptions);
desc[1] = (TextView)layout.findViewById(R.id.item2_desc_text_view);
desc[1].setText(mItemsList.get(objectId1).getDesc()));
itemsLayout[1].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onMyClikItem(mItemsList.get(objectId2).getItemId());
}
});
itemsLayout[1].setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
onMyLongClikItem(objectId2);
return true;
}
});
if(mItemsList.size()>objectId3){
itemsName[2] = (TextView)layout.findViewById(R.id.item3_name);
itemsName[2].setText(mItemsList.get(objectId3).getName());
itemsImage[2] = (ImageView)layout.findViewById(R.id.item3_image);
mImageLoader.displayImage(Image.getRegularUrl(mItemsList.get(objectId3)
.getImages()[0].getFilename()),itemsImage[2],mOptions);
desc[2] = (TextView)layout.findViewById(R.id.item3_desc_text_view);
desc[2].setText(mItemsList.get(objectId1).getDesc()));
itemsLayout[2].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onMyClikItem(mItemsList.get(objectId3).getItemId());
}
});
itemsLayout[2].setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
onMyLongClikItem(objectId3);
return true;
}
});
} else {
itemsLayout[2].setVisibility(View.INVISIBLE);
}
} else {
itemsLayout[1].setVisibility(View.INVISIBLE);
itemsLayout[2].setVisibility(View.INVISIBLE);
}
}else {
layout.setVisibility(View.INVISIBLE);
}
i++;
}
((ViewPager) container).addView(itemView);
return itemsView;
}
What should i change to speed up my ViewPager.

There are a lot of things you can do to improve performance in Android. Try to put all the loading etc in a AsycTask (http://developer.android.com/reference/android/os/AsyncTask.html).
Also there is documentation about how to optimise preformance: http://developer.android.com/training/articles/perf-tips.html. When I read your code I saw a lot of difficult to read code and a lot of repetetive code. Try to rethink the way you handeld the situation.

Related

Get selected item value from ListView CustomAdapter

I have listview with custom adapter. Each row of item has button that activates popup menu with. When user click on one of the items it should display some data.
Here is the item holder class:
public class cNalog {
public String IDNalog;
public String NazivKlijenta;
public String OpisNaloga;
public String Napomena;
public int Hitnost;
public cNalog(String IDNalog, String nazivKlijenta, String opisNaloga, int hitnost) {
this.IDNalog = IDNalog;
NazivKlijenta = nazivKlijenta;
OpisNaloga = opisNaloga;
Hitnost = hitnost;
}
public cNalog() {}
public String getIDNalog() {
return IDNalog;
}
public void setIDNalog(String IDNalog) {
this.IDNalog = IDNalog;
}
public String getNazivKlijenta() {
return NazivKlijenta;
}
public void setNazivKlijenta(String nazivKlijenta) {
NazivKlijenta = nazivKlijenta;
}
public String getOpisNaloga() {
return OpisNaloga;
}
public void setOpisNaloga(String opisNaloga) {
OpisNaloga = opisNaloga;
}
public String getNapomena() {
return Napomena;
}
public void setNapomena(String napomena) {
Napomena = napomena;
}
public int getHitnost() {
return Hitnost;
}
public void setHitnost(int hitnost) {
Hitnost = hitnost;
}
}
And here is the getView method from CustomAdapter that extend BaseAdapter class:
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null)
{
holder = new ViewHolder();
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.popisnaloga_red, null);
holder.btnPopUpMenu = (Button) view.findViewById(R.id.btnPopUpNalog);
holder.btnPopUpMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(mContext, view);
popup.getMenuInflater().inflate(R.menu.popup_nalog, popup.getMenu());
//holder.uidNalog = mData.get(_i).getIDNalog();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
Toast.makeText(mContext,
"Your Message", Toast.LENGTH_LONG).show();
switch (menuItem.getItemId()) {
case R.id.mnuActionInfo:
Log.i("Selekcija", mData.get(i).getIDNalog()); //Info(mData.get(i).getOpisNaloga());
default:
return false;
}
}
});
popup.show();
}
});
}
TextView tvOpisRada = (TextView)view.findViewById(R.id.viewNazivNaloga);
tvOpisRada.setText(mData.get(i).getOpisNaloga());
return view;
}
private class ViewHolder {
protected Button btnPopUpMenu;
}
When user select some item it should print out UID. This works fine when I have 3-4 items... but if I scrool down and let's say he select 12th item he get the same UID as the one of the first fours item. It seems that when I scrool down the listview acts like there is always 4 items in list not 12 or more... How to solve this?
you did wrong when use ViewHolder. Your code only check if view = null then inflate row for that position. So you can not store view's value.
You need to store row as a tag of viewholder, when check when view != null and get that view.
You can check that link to know how Viewholder work in listview: Implements ViewHolder on a ListView AndroidStudio
I know someone suggest you to use RecyclerView, but I want to suggest you to know about viewHolder/listview first. The most dangerous thing is just copy code but dont know how it work.
I think the best way for what you want is to use a recyclerview rather than a listview
For any help take a look here

how to change image in Recycler View in android (like a radio button)?

I am having Recycler View. It's like a grid view. A total of 9 images in grid layout. If I click a image in any one of the above, that image have to change to an another image. If I click another image. Last one want to reset. Then the clicked image alone will change to highlighted image.
Here is my code...
holder.mLayout.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
//for (int i = 0; i < data_collection.size(); i++) {
holder.mLayout.setVisibility(View.VISIBLE);
holder.mHighLighted.setVisibility(View.GONE);
if (position == i) {
}
//}
holder.mLayout.setVisibility(View.GONE);
holder.mHighLighted.setVisibility(View.VISIBLE);
mHighLight.onHighLight(position, view);
}
});
Remove what you dont need.
#Override
public void onBindViewHolder(final SimpleViewHolder holder, final int position) {
holder.textView.setText(elements.get(position).getName());
holder.textView.setTypeface(typeface1);
CircularImageView circularImageView = (CircularImageView) holder.linearLayout.findViewById(R.id.personazhe_layout_grid_item_image);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// circularImageView.setBackground(elements.get(position).getPhoto());
// }
circularImageView.setImageDrawable(elements.get(position).getProfileImage());
//Picasso.with(context).load(elements.get(position).getProfileImage()).into(circularImageView);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos != position){
c.setImageDrawable(elements.get(position).getProfileImage());
t.setText(elements.get(position).getName());
seekBar.setProgress(0);
pos = position;
}
//image = elements.get(position).getProfileImage();
// textviews
// trajneri = elements.get(position).getTrajneri();
// mosha = elements.get(position).getMosha();
// vendbanimi = elements.get(position).getVendbanimi();
// vendlindja = elements.get(position).getVendlindja();
// arsimi = elements.get(position).getArsimi();
// name = elements.get(position).getName();
// surname = elements.get(position).getSurname();
// pos = elements.get(position).number();
// posi = position;
// button.performClick();
}
});
}
The ViewHolder pattern is something that Android pushed developers to use for a long time, and then (rightfully) forced on them with RecyclerViews. The idea, opposed to a simple ListView, is that you reuse as much of the view as possible when scrolling to reduce inflation and resource identification. The ViewHolder should be managed as something that is changed/not created within the RecyclerView.
Because of that, storing information in a ViewHolder that must be persistent will not work. For that, there are a plethora of other options. Let's go with an inner class that will manage holding onto the currently selected view position and its relative images.
Let's say we have a custom ViewHolder like below:
public class ImageViewHolder extends RecyclerView.ViewHolder{
private ImageView iv;
public ImageViewHolder(View v){
iv = (ImageView) v.findViewById(R.id.iv);
}
public ImageVie getImageView(){
return iv;
}
}
And utilizing that view holder is an adapter DemoAdapter, we can modify it to look something like this:
public class DemoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public interface SelectionListener{
void onImageSelected(Bitmap bmp);
}
private static class SelectionHolder{
protected int position;
protected Bitmap originalBmp, newBmp;
public SelectionHolder(int position, Bitmap originalBmp,
Bitmap newBmp){
this.position = position;
this.originalBmp = originalBmp;
this.newBmp = newBmp
}
}
private SelectionHolder selectionHolder;
private SelectionListener selectionListener;
/*
Pre-existing Adapter functionality
*/
public void setSelectionListener(SelectionListener listener){
selectionListener = listener;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
/*
Pre-existing onBindViewHolder code
*/
ImageView iv = holder.getImageView();
if(selectionHolder != null && selectionHolder.position == position)
iv.setImageBitmap(selectionHolder.newBmp);
else{
//set the image however you are doing it now
}
iv.setOnClickListener(
new new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView iv = (ImageView) v;
// Get the IV's current bmp
Bitmap originalBmp = getBitmapFromImageView(iv);
// Get the currently selected image's "new" image
// if it is null, set it to the original bmp
// this will initialize our "highlighting"
Bitmap newBmp = selectionHolder == null || selectionHolder.newBmp == null?
originalBmp: selectoinHolder.newBmp;
// set the selection holder
selectionHolder = new SelectionHolder(position, originalBmp, newBmp);
// notify our listener
if(selectionListener != null)
selectionListener.onImageSelected(bmp);
// refresh the adapter
DemoAdapter.this.notifyDataSetChanged();
}
});
}
private Bitmap getBitmapFromImageView(ImageView iv){
return ((BitmapDrawable)(iv.getDrawable()).getBitmap()
}
}
Then if we have an activity that needs the selected image, perhaps to display it in an ImageView it hosts
recyclerAdapter = new DemoAdapter(...);
recyclerAdapter.setSelectionListener(new SelectionListener(){
#Override
public void onImageSelected(Bitmap bmp){
// set the bmp to your image view or whatever you want
}
}

set background color for imageview doesn't work

I am trying to change ImageView background when clicked(like Duolingo)
Here is my code from fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.frag_repeat, container, false);
final int[] a1 = {0};
final int[] a2 = {0};
final int[] a3 = {0};
final int[] a4 = {0};
TypedArray itemsIcon = getResources().obtainTypedArray(R.array.nav_drawer_icons);
ImageView wer1 = (ImageView) rootView.findViewById(R.id.imageView);
ImageView wer2 = (ImageView) rootView.findViewById(R.id.imageView2);
ImageView wer3 = (ImageView) rootView.findViewById(R.id.imageView23);
ImageView wer4 = (ImageView) rootView.findViewById(R.id.imageView43);
TextView textView1 = (TextView) rootView.findViewById(R.id.textView711);
textView1.setText(ss[i]);
wer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a1[0] = 1;
a2[0] = 0;
a3[0] = 0;
a4[0] = 0;
}
});
wer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a2[0] = 1;
a1[0] = 0;
a3[0] = 0;
a4[0] = 0;
}
});
wer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a3[0] = 1;
a2[0] = 0;
a1[0] = 0;
a4[0] = 0;
}
});
wer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a4[0] = 1;
a2[0] = 0;
a3[0] = 0;
a1[0] = 0;
}
});
if(a1[0] > 0){
wer3.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer2.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer1.setBackgroundColor(Color.parseColor("#42A5F5"));
wer4.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else if(a2[0] > 0){
wer1.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer3.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer2.setBackgroundColor(Color.parseColor("#42A5F5"));
wer4.setBackgroundColor(Color.parseColor("#FFFFFF"));
}else if(a3[0] > 0){
wer1.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer2.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer3.setBackgroundColor(Color.parseColor("#42A5F5"));
wer4.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else if(a4[0] > 0){
wer1.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer2.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer4.setBackgroundColor(Color.parseColor("#42A5F5"));
wer3.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
if(i1 == 1){
wer1.setImageResource(itemsIcon.getResourceId(i, -1));
} else if(i1 == 2){
wer2.setImageResource(itemsIcon.getResourceId(i, -1));
} else if(i1 == 3){
wer3.setImageResource(itemsIcon.getResourceId(i, -1));
} else if(i1 == 4){
wer4.setImageResource(itemsIcon.getResourceId(i, -1));
}
return rootView;
}
But ImageView background doesn't change! I have CardViews inside RelativeLayout and inside RelativeLayout I have ImageView.
Please share xml file. Maybe you don't set background for ImageView in xml
Each of your onClick listeners is just toggling values in an array. I suspect what you really want is to invoke the setBackground color code inside each handler.
From your code, I think what you are trying to do is this:
Whichever button was clicked - change it's background color from white to #42A5F5.
For the other three buttons not clicked, change the background color back to white.
I don't know what the name of your class is (I'll refer to it as "YourClass"). But make your 4 ImageViews member variables.
class YourClass extends Fragment // I'm guessing this is the declaration, it doesn't matter - use whatever you have now
{
ImageView _wer1;
ImageView _wer2;
ImageView _wer3;
ImageView _wer4;
Then inside onCreateView, assign each one of these member variables exactly where you assign the local variables:
_wer1 = (ImageView) rootView.findViewById(R.id.imageView);
_wer2 = (ImageView) rootView.findViewById(R.id.imageView2);
_wer3 = (ImageView) rootView.findViewById(R.id.imageView23);
_wer4 = (ImageView) rootView.findViewById(R.id.imageView43);
Now set each of your click listeners to invoke a "ToggleBackgroundColors". Notice that there's a different index value passed to this function in each callback handler.
_wer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourClass.this.ToggleBackgroundColors(0);
}
});
_wer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourClass.this.ToggleBackgroundColors(1);
}
});
_wer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourClass.this.ToggleBackgroundColors(2);
}
});
_wer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourClass.this.ToggleBackgroundColors(3);
}
});
Then implement ToggleBackgroundColors:
void ToggleBackgroundColors(int which)
{
int highlight = Color.parseColor("#42A5F5");
ImageView [] views = {_wer1, _wer2, _wer3, _wer4};
for (int x = 0; x < views.length; x++)
{
int background = (which == x) ? highlight : Color.WHITE;
views[x].setBackgroundColor(background);
}
}
In your onClickListener, you can also set colorFilter on your imageView when you onClick it.
Consider using the onTouchListener instead though as you would like the imageView to change color when you touch the button and not when you click on it.
ImageView iv = (ImageView)findViewById(resIdOfImageToFilter);
iv.setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

How to iterate through a set of buttons in Android Studio?

I'm trying to make my first app which has a set of 15 buttons. when you press a button the color changes between two numbers.Then if you press a specificity different "commit" button the buttons won't change colors any more.
My question right now is how would I be able to iterate through the buttons on the screen? I believe I need a assign the buttons a "name", "type", or something like it, and then find all instances where that happens but I cannot find the relevant getter/setter methods.
Here is my code so far:
public void clickHandler(View view) {
Button btn = (Button) view;
int id = btn.getId();
boolean clicked = isChosen(btn);
if( clicked == true && id != 1) {
btn.setBackgroundColor(-3355444);
}
else{
btn.setBackgroundColor(-16777216);
}
}
public boolean isChosen(Button btn){
ColorDrawable buttonColor = (ColorDrawable) btn.getBackground();
int colorId = buttonColor.getColor();
if(colorId == -16777216){
return true;
}
else return false;
}
public boolean player = true;
public void changeTurn(View view) {
TextView t = (TextView) findViewById(R.id.textView3);
if(player == false) {
t.setText("Player 2's turn");
player = true;
}
else{
t.setText("Player 1's turn");
player = false;
}
Hope this piece of code helps
final int buttonCount = 15;
LinearLayout mLayout = (LinearLayout) findViewById(R.id.pager);
for (int i = 0; i < buttonCount; i++) {
TextView textView = new TextView(this);
textView.setTag(String.valueOf(i));
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonID = Integer.valueOf(view.getTag().toString());
updateColorForButtonAtPosition(buttonCount);
}
});
mLayout.addView(textView);
}
private void updateColorForButtonAtPosition (int buttonCount){
// add your functionality here
}

Updating a List View

I've been stuck with this for a long while and it's really frustrating. Basically the app starts off with a ListView containing Movie Titles, their Gross, and Year.
The user then can add a new movie, gross, and year using a different activity from the menu. The values are then returned back to the first activity and is placed at the bottom of the list.
This is where my problem begins. The first problem I had is that the app Force Closes when it's about to display the new item. Now, it doesn't want to display at all. Here's the Code:
public class Lab7_084106 extends ListActivity {
private SampleCustomAdapter adapter;
private ArrayList<MyMovies> movieList;
public static boolean Flag = false;
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
//create stuff
super.onCreate(savedInstanceState);
movieList = new ArrayList<MyMovies>();
Intent data = getIntent();
//Flag = data.getStringExtra("Flag");
String[] oldMovieList = getResources().getStringArray(R.array.movieArray);
String[] oldGrossList = getResources().getStringArray(R.array.worldwideGross);
String[] oldYearList = getResources().getStringArray(R.array.yearArray);
//if there's no new movie to display
if(!Flag){
for (int i = 0; i < oldMovieList.length; i++) {
MyMovies newMovie = new MyMovies();
newMovie.setMovie(oldMovieList[i] + "NEW");
newMovie.setGross(oldGrossList[i]);
newMovie.setYear(oldYearList[i]);
movieList.add(newMovie);
}
//adapter = new SampleCustomAdapter(movieList);
//setContentView(R.layout.row);
//setListAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Else Entered", Toast.LENGTH_SHORT).show();
int newLength = 50; //oldMovieList.length + 1;
//create new array to store the new value
String[] newMovieArray = new String[newLength];
String[] newGrossArray = new String[newLength];
String[] newYearArray = new String[newLength];
//populate the new list with the old one plus the new one
for (int i = 0; i < newLength; i++) {
if( i != newLength - 1){
newMovieArray[i] = oldMovieList[i];
newGrossArray[i] = oldGrossList[i];
newYearArray[i] = oldYearList[i];
}
else{
newMovieArray[i] = data.getStringExtra("Title");
newGrossArray[i] = data.getStringExtra("Gross");
newYearArray[i] = data.getStringExtra("Year");
}
}
//populate the old one using the new list
for (int i = 0; i < newLength; i++) {
oldMovieList[i] = newMovieArray[i];
oldGrossList[i] = newGrossArray[i];
oldYearList[i] = newYearArray[i];
}
//display stuff
for (int i = 0; i < newLength; i++) {
MyMovies newMovie = new MyMovies();
newMovie.setMovie(oldMovieList[i]);
newMovie.setGross(oldGrossList[i]);
newMovie.setYear(oldYearList[i]);
movieList.add(newMovie);
}
//adapter = new SampleCustomAdapter(movieList);
//setListAdapter(adapter);
}
adapter = new SampleCustomAdapter(movieList);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//set stuff such that Page2 sends back a result to page 1
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView t = (TextView) view.findViewById(R.id.title);
String name = (String) t.getText();
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
}
});
}
private class SampleCustomAdapter extends BaseAdapter {
private ArrayList<MyMovies> internalList;
String[] oldMovieList = getResources().getStringArray(R.array.movieArray);
String[] oldGrossList = getResources().getStringArray(R.array.worldwideGross);
String[] oldYearList = getResources().getStringArray(R.array.yearArray);
private ArrayList<MyMovies> GetSearchResults(){
ArrayList<MyMovies> results = new ArrayList<MyMovies>();
// make sure the arrays have the same length
for (int i = 0; i < oldMovieList.length; i++) {
MyMovies sr = new MyMovies();
sr.setMovie(oldMovieList[i]);
sr.setGross(oldGrossList[i]);
sr.setYear(oldYearList[i]);
results.add(sr);
}
return results;
}
public SampleCustomAdapter(ArrayList<MyMovies> contacts){
internalList = contacts;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return internalList.size();
}
#Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return internalList.get(index);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// NOTE: you can only do this if you have access to the Activity object
// which is why this is an inner class
LayoutInflater inflater = getLayoutInflater();
View view;
//System.out.println(parent.getClass().getName());
//System.out.println(position);
if (convertView==null){
view = inflater.inflate(R.layout.row, null);
}
else{
view = convertView;
}
// extract the views to be populated
TextView movie = (TextView) view.findViewById(R.id.title);
TextView gross = (TextView) view.findViewById(R.id.gross);
TextView date = (TextView) view.findViewById(R.id.date);
// extract the object that will fill these
MyMovies movies = GetSearchResults().get(position);
//MyMovies movies = internalList.get(position);
movie.setText(movies.getMovie());
gross.setText(movies.getGross());
date.setText(movies.getYear());
// return the view
return view;
}
}
//menu lawl
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menupage1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection using item.getItemId()
switch(item.getItemId()){
case R.id.addMovie:
AddMovie();
break;
}
return true;
}
//end menu stuff lol
public void AddMovie(){
Intent intent2 = new Intent(this, com.Android.Lab7.addMovie.class);
startActivity(intent2);
finish();
}
}
The Flag Boolean variable basically tells if the user added a movie. If the user added a movie, it will enter the else statement and update from there. I'm really confused where to put this if-else statement.
I ran a few experiments with the GetSearchResult function of SampleCustomAdapter and found out that it directly affects the output of the ListView. I tried placing the if-else statement there but I ended up with a LOT of items in the ListView.
Using adapter.notifyDataSetChanged(); gives a NullPointerException error and points to where I placed it. So even if do something like:
MyMovies newMovie = new MyMovies();
newMovie.setMovie(data.getStringExtra("Title"));
newMovie.setGross(data.getStringExtra("Gross"));
newMovie.setYear(data.getStringExtra("Year"));
movieList.add(newMovie);
adapter.notifyDataSetChanged();
As the else block, it does not work. I think it has something to do with the fact that I'm getting my initial values from the string.xml resource folder and not via hardcode or user input.
This problem has been frustrating me ever since 2-3 days ago and help is really appreciated. Thanks.
you just have to notify the data set Changed on your adapter
movieList.add(newMovie);
adapter.notifyDataSetChanged();
the listview will be updated automatically
UPDATE
you can always use the following it'll work but I prefer notifying the adapter.
movieList.add(newMovie);
adapter = new SampleCustomAdapter(movieList);
setListAdapter(adapter);
you should use adapter.notifyDataSetChanged(). CheckThis Link

Categories

Resources