I have a ListView and a custom adapter. When the user changes the sort type from a spinner, I want to redraw the list with the new items. The problem is that the ListView is re-drawn only after I interact with it on the device (start scrolling for example).
if (update) {
mOfferList = (ArrayList<PositionSearchItem>) psr
.getPositionSearchItem();
mAdapter.clear();
mAdapter.addAll(mOfferList);
mAdapter.notifydataSetChanged()
mList.invalidate();
mList.invalidateViews();
}
I have also tried to fully reset a new instance of my adapter to the list, it is giving the same result except that the list becomes blank at first and appears on user interaction.
I'm using HoloEveryWhere maybe this is an important info.
EDIT : Here is some more code
#EFragment(R.layout.list_fragment_results)
public class ResultsListFragment extends Fragment {
#ViewById(R.id.search_results_list)
ListView mList;
#ViewById(R.id.search_result_list_spinner)
Spinner mSpinner;
MainActivity mActivity;
private String mTypedText;
private List<String> mSortType;
private ResultsListFragment mFrag;
private Bundle mOffersPageBundle;
private SearchResultsListAdapter mAdapter;
private ArrayList<PositionSearchItem> mOfferList;
#AfterViews
public void afterViews() {
mFrag = this;
mActivity = (MainActivity) getActivity();
mSortType = new ArrayList<String>();
mSortType.add(SearchResultSortType.SCORE_DESCENDING);
mOfferList = new ArrayList<PositionSearchItem>();
mOffersPageBundle = getArguments();
PositionSearchResponse psr = mOffersPageBundle.getParcelable("offers");
mTypedText = mOffersPageBundle.getString("typedText");
mOfferList = (ArrayList<PositionSearchItem>) psr.getPositionSearchItem();
mAdapter = new SearchResultsListAdapter(this,
android.R.layout.simple_list_item_1, mOfferList, mTypedText,
mSortType, mActivity.getLat(), mActivity.getLon());
mList.setAdapter(mAdapter);
this.setListeners();
}
private void setListeners() {
mSpinner.setOnItemSelectedListener(new org.holoeverywhere.widget.AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(
org.holoeverywhere.widget.AdapterView<?> parent, View view,
int pos, long id) {
Boolean update = false;
PositionSearchResponse psr = null;
switch (pos) {
case 0:
if (mSortType.get(0) != SearchResultSortType.SCORE_DESCENDING) {
mSortType.clear();
mSortType.add(SearchResultSortType.SCORE_DESCENDING);
psr = processSearch(mTypedText, mSortType, 0, mActivity);
update = true;
}
break;
case 1:
if (mSortType.get(0) != SearchResultSortType.DATE) {
mSortType.clear();
mSortType.add(SearchResultSortType.DATE);
psr = processSearch(mTypedText, mSortType, 0, mActivity);
update = true;
}
break;
default:
break;
}
if (update) {
mOffersPageBundle.putParcelable("offers", psr);
mOfferList = (ArrayList<PositionSearchItem>) psr
.getPositionSearchItem();
mAdapter.mIdMap.clear();
for (int i = 0; i < mOfferList.size(); ++i) {
mAdapter.mIdMap.put(mOfferList.get(i), i);
}
mOfferList = (ArrayList<PositionSearchItem>) psr
.getPositionSearchItem();
mAdapter.clear();
mAdapter.addAll(mOfferList);
mAdapter.notifydataSetChanged()
mList.invalidate();
mList.invalidateViews();
}
}
#Override
public void onNothingSelected(
org.holoeverywhere.widget.AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
EDIT : the getView method from custom adapter
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
this.v = convertView;
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
PositionSearchItem psr = getItem(pos);
v = vi.inflate(R.layout.result_list_item, parent, false);
v.setTag(pos);
// Inject text into view
((TextView) v.findViewById(R.id.result_title_textview))
.setText(getItem(pos).getTitle());
// Disable hardware acceleration for the view (it brakes dotted lines on
// some devices)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
v.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// reload list if scrolled to bottom
int page = 0;
if (pos > mLastViewed && pos == getCount() - 1) {
mLastViewed = pos;
ResultsListFragment frag = new ResultsListFragment_();
PositionSearchResponse newSearch = frag.processSearch(mTypedText, mSortType, mPage,
mActivity);
mPage = mPage + 12;
if(newSearch != null && newSearch.getPositionSearchItem() != null && newSearch.getPositionSearchItem().size() > 0){
for (int i = 0; i < newSearch.getPositionSearchItem().size(); ++i) {
mIdMap.put(newSearch.getPositionSearchItem().get(i), i);
}
this.addAll(newSearch.getPositionSearchItem());
}
}
return v;
}
Use
if (update) {
mAdapter.NotifyDataSetChanged();
}
this may solve your problem.
Try to set the adatpter again.Place the below code in all the places you wrote the code to update listview
mAdapter = new YourAdapter();
mList.setAdapet(mAdapter)
I hope you have created custom list view using adapter and model.
Now each time when you need to update your list view dynamically then you need to clear your previously created list view. Then after you need to fetch all new values and then update same over custom list view.
Hope it helps!
Related
i made a custom listView having two textViews..for example student name and roll no...
now i want to implement a selection...for example..i will click on few students in the listview and the object should get saved somewhere ...for example:
ClassList.add(new StudentList(99,"student1","code"));
ClassList.add(new StudentList(70,"student2","code"));
ClassList.add(new StudentList(20,"student3","code"));
ClassList.add(new StudentList(30,"student4","code"));
adapter = new StudentListViewAdapter(this, ClassList,"code");
listView.setAdapter(adapter);
now i should be able to set another method for example:
ClassList2=listView.getSelectedStudents();
this should return the selected students..for example if i select student 1,student 2 it should return Student List Objects for both of them so i can access there roll and Code too
And there is another problem...when i deselect it should remove that object from the list..
It would be really helpfull if someone will write a sample code
This is how i do it..but i don't think it is really a good method
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (ItemView == null) {
ItemView = inflater.inflate(R.layout.customvistview_atd, parent, false);
}
//find the hotels to work with
final studentlist currentList = totalClass_list.get(position);
//fill the view
final TextView textview_studentName = (TextView) ItemView.findViewById(R.id.textview_atd_studentName);
textview_studentName.setText((currentList.getName()));
final TextView textview_studentRollno = (TextView) ItemView.findViewById(R.id.textview_atd_studentRollno);
textview_studentRollno.setText((currentList.getRoll_no() + ""));
final CardView cardView = (CardView) ItemView.findViewById(R.id.card_view_atd);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i = 0; i < presentStudents.size(); i++) {
if (presentStudents.get(i).getMindex() == position) {
System.out.println("m-index : "+presentStudents.get(i).getMindex());
System.out.println("position : "+position);
isChecked = true;
System.out.println("I am in the loop, I am at position: "+i);
me = i;
break;
}
}
if (isChecked) {
presentStudents.remove(me);
isChecked = false;
ColorDrawable[] color = {new ColorDrawable(Color.parseColor("#198b9f")), new ColorDrawable(Color.WHITE)};
TransitionDrawable trans = new TransitionDrawable(color);
cardView.setBackground(trans);
trans.startTransition(1500);
textview_studentName.setTextColor(Color.GRAY);
textview_studentName.setTextColor(Color.GRAY);
//cardView.setBackgroundColor(Color.WHITE);
System.out.println("I am in isChecked");
} else {
presentStudents.add(new tempclass(currentList.getRoll_no(),atdCode,position));
ColorDrawable[] colorCard = {new ColorDrawable(Color.WHITE), new ColorDrawable(Color.parseColor("#198b9f"))};
TransitionDrawable trans = new TransitionDrawable(colorCard);
cardView.setBackground(trans);
trans.startTransition(1500);
textview_studentName.setTextColor(Color.WHITE);
textview_studentName.setTextColor(Color.WHITE);
// cardView.setBackgroundColor(Color.BLUE);
System.out.println("I am in else, making it blue");
}
}
});
you can use this one
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
StudentLists studentList = listView.getItemAtPosition(i);//selected object
adapter.dismiss(); // If you want to close the adapter
}
});
I'm facing a strange behaviour using an ArrayAdapter.
When the number of listview item exceed the height of the listView (say after item 8), the next item get the id 0 instead the id 9.
In my opinion this type of issue was explained here with the convertView, but i use it in the same way (i think).
The following code is my ArrayAdapter.
public class StepsAdapter extends ArrayAdapter<String> {
Context context;
List<String> steps;
public StepsAdapter(Context context, int resourceId, List<String> steps) {
super(context, resourceId, steps);
this.context = context;
}
private class ViewHolder {
EditText stepValue;
ImageView removeStep;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final String step = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_step, null);
holder = new ViewHolder();
holder.stepValue = (EditText) convertView.findViewById(R.id.stepEdit);
holder.removeStep = (ImageView) convertView.findViewById(R.id.removeStep);
holder.stepValue.setText(step);
holder.removeStep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"* Remove id step " + position, Toast.LENGTH_LONG).show();
steps.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
Then my main activity where i get existing data and put it in my listView, the add button and the save button.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_game);
mContext = getApplicationContext();
steps = new ArrayList<String>();
stepsAdapter = new StepsAdapter(mContext,R.layout.row_step,steps);
Gson gson = new GsonBuilder().create();
game = gson.fromJson(gameJson, Games.class);
/*
* Settings values
*/
gameNameValue.setText(game.getName());
gameBackgroundPreview.setBackgroundColor(game.getColor());
colorSelected = game.getColor();
for(int i = 0; i < game.getSteps().size() ; i++){
//steps.add(game.getSteps().get(i).toString());
//notifyDataSetChanged();
stepsAdapter.add(game.getSteps().get(i).toString());
}
final ListView listSteps = (ListView) findViewById(R.id.listViewSteps);
listSteps.setAdapter(stepsAdapter);
gameNameValue.setText(gameName);
addSteps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stepsId = steps.size();
Toast.makeText(getApplicationContext(), "addSteps : " + stepsId, Toast.LENGTH_LONG).show();
stepsAdapter.insert("newstep", stepsId);
}
});
buttonSaveGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String valueEditGameName = gameNameValue.getText().toString();
int valueColorBackaground = colorSelected;
String picture = "testPic";
for(int i=0; i < listSteps.getChildCount(); i++) {
LinearLayout rowLayout = (LinearLayout) listSteps.getChildAt(i);
//Log.e(TAG, ">> :) layout >>" + listSteps.getChildAt(i).getClass().getName());
EditText editRow = (EditText) rowLayout.getChildAt(0);
stepsValues.add(editRow.getText().toString());
//Log.e(TAG, ">> :) inside layout >>" + editRow.getText().toString());
}
if(valueEditGameName.trim().length() > 0 && picture.trim().length() >0 ){
Games game = new Games(valueEditGameName,valueColorBackaground,picture,stepsValues);
String goToSave = game.createJson();
Log.e(TAG, ">>Saved>>" + goToSave);
final CkdFile file = new CkdFile();
String saved = file.writeToSDFile(game.getName(), goToSave);
Toast.makeText(mContext, saved, Toast.LENGTH_LONG).show();
Intent backToMain = new Intent(mContext,MainActivity.class);
startActivity(backToMain);
} else {
Toast.makeText(mContext, "Fill all texts", Toast.LENGTH_LONG).show();
}
}
});
}
I try to add items in 2 different ways :
add item through : List steps
add item through : StepsAdapter stepsAdapter
Both give me same behaviour.
If someone has a clue to help understanding what i'm doing wrong with my implementation of ListView/ArrayAdapter.
Thanks in advance !
EDIT 1 :
After pushing some logs everywere, it understand the strange behaviour :
My adapter have only 6 slots (the limit came from the size of the listview in layout), and when my arraylist have more than 6 items, the getView select items only between 0 and 5.
I'm searching now a way to get the position in ArrayList and not the position in arrayadapter.
I faced same issue recently. Add following overrides to Adapter:
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
I found a simple xml "trick" to avoid this behaviour : i set a biger height to listView.
<ListView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:layout_gravity="center_horizontal"
android:id="#+id/listViewSteps"
android:layout_margin="10dp">
</ListView>
It's not really resolve but a take it ...
I've looked for this issue but nothing I've found matches my situation.
My problem occurs onAndroid 2.3.x (on 4.x it works perfectly)
I have an application with a custom list view. I initialize my listview as follows
ListAdapter mListAdapter = new ListAdapter(getApplicationContext(), this, ...);
lvSelector = (ListView) findViewById(R.id.listView1);
lvSelector.setAdapter(mListAdapter);
My ListAdapter is as follows:
public class ListAdapter extends BaseAdapter {
static class Holder {
LinearLayout layoutRoot, layoutColor;
TextView hText;
Animation anim = AnimationUtils.loadAnimation(mActivity, R.anim.anim_list_item);
public Holder() {
layoutRoot = new LinearLayout(mContext);
layoutColor = new LinearLayout(mContext);
hText = new TextView(mContext);
}
public Holder(Holder holder) {
this.layoutRoot = holder.layoutRoot;
this.layoutColor = holder.layoutColor;
this.hText = holder.hText;
}
}
int mSwap1, mSwap2;
Animation mAnimation;
public ListAdapter(Context _context, Activity _activity, FileHandler _fileHandler, String _strSchemaName, List<String> _list, List<String> _solution) {
mContext = _context;
mActivity = _activity;
mAnimation = AnimationUtils.loadAnimation(mActivity, R.anim.anim_list_item);
mAnimation.reset();
mSwap1 = mSwap2 = -1;
/* ... */
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int fPosition = position;
View row = convertView;
Holder lHolder = null;
if (row==null) {
LayoutInflater inflater = mActivity.getLayoutInflater();
row = inflater.inflate(R.layout.layout_schema_element, parent, false);
lHolder = new Holder();
lHolder.layoutRoot = (LinearLayout) row.findViewById(R.id.elementLayoutRoot);
lHolder.layoutColor = (LinearLayout) row.findViewById(R.id.elementLayoutColor);
lHolder.hText = (TextView) row.findViewById(R.id.textViewWord);
row.setTag(lHolder);
}
else {
lHolder = (Holder)row.getTag();
}
row.setOnClickListener(null);
if (position==0 || position==mDataList.size()-1) {
lHolder.layoutColor.setBackgroundResource(R.drawable.bg_elem_fixed);
lHolder.layoutColor.setOnClickListener(null);
}
else {
lHolder.layoutColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveElement(fPosition);
}
});
}
lHolder.hText.setText(mDataList.get(position));
lHolder.layoutRoot.setBackgroundResource(0);
mHolder.set(position, lHolder);
return row;
}
}
protected void moveElement(int _element) {
if (mDataList.get(_element).equals(mSolution.get(_element)))
return;
if (mSwap1==-1)
{
System.out.println("setting swap1=" + _element);
mHolder.get(_element).layoutRoot.setBackgroundResource(R.drawable.bg_elem_selected_lite);
mSwap1 = _element;
}
else
{
if (mSwap2==-1)
{
System.out.println("setting swap2=" + _element);
mHolder.get(_element).layoutRoot.setBackgroundResource(R.drawable.bg_elem_selected_lite);
mSwap2 = _element;
}
}
if (mSwap1!=-1)
{
System.out.println("running animation on mSwap1=" + mSwap1);
mHolder.get(mSwap1).layoutRoot.clearAnimation();
mHolder.get(mSwap1).layoutRoot.startAnimation(mAnimation);
}
/***** THIS IS WHAT DOES NOT WORK *****/
if (mSwap2!=-1)
{
System.out.println("running animation on mSwap2=" + mSwap2);
mHolder.get(mSwap2).layoutRoot.clearAnimation();
mHolder.get(mSwap2).layoutRoot.startAnimation(mAnimation);
}
if (mSwap1!=-1 && mSwap2!=-1)
{
mHolder.get(mSwap1).layoutRoot.setBackgroundColor(0);
mHolder.get(mSwap2).layoutRoot.setBackgroundColor(0);
if (mSwap1==mSwap2)
{
mSwap1 = mSwap2 = -1;
return;
}
Collections.swap(mDataList, mSwap1, mSwap2);
Collections.swap(mHolder, mSwap1, mSwap2);
Collections.swap(dataObjs, mSwap1, mSwap2);
mSwap1 = mSwap2 = -1;
notifyDataSetChanged();
}
}
}
Everything works fine when I perform Collections.swap(list, mSwap1, mSwap2), elements are correctly swapped.
First animation (mSwap1) is run fine; my problem is that when second animation is run (mSwap2), it is executed on another element in screen even if mSwap2 is right (e.g.: mSwap1=1 -> second element in list is animated, mSwap2=2 -> n-1 element and n-2 element in list are animated where n is the number of visible elemnts).
I've solved my problem replacing animation calls
mHolder.get(idx).layoutRoot.clearAnimation();
mHolder.get(idx).layoutRoot.startAnimation(mAnimation);
with the following method
private void animateItem(int _index, Animation _animation) {
if (
_index<mLvSelector.getFirstVisiblePosition() // selected item is above first visible element
|| _index>mLvSelector.getLastVisiblePosition() // selected item is below last visible element
)
// element is invisible -> no animation
return;
int newIndex = _index;
if (
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH // before android 4.0
&& mSwap2>=0 // second selection
&& mSwap1!=mSwap2 // second selection differs from first selection
)
newIndex = mLvSelector.getFirstVisiblePosition() + (mLvSelector.getLastVisiblePosition() - _index);
mHolder.get(newIndex).layoutRoot.clearAnimation();
mHolder.get(newIndex).layoutRoot.startAnimation(_animation);
}
Adding Animation argument to the method allows to differentiate animation between elements (mSwap1 and mSwap2).
I am having trouble with an update to the data in an ArrayAdapter in a ListView and even on listAdapter.notifyDataSetChanged() the changes are not being reflected in the ListView.
Whats interesting is that the initial load is fine, i get the full list of data rendered in the ListView. It is when i load the activity for the second time, where the cached ArrayList gets passed to the setDataList() method doesn't get rendered. The resulting ListView only contains the single default entry setup in the onCreate() method.
I have debugged the code and stepped through the runnable and it appears to run as i would have expected, just without the end result.
If anyone could help with this i would really appreciate it, i have googled it to death!
My code snippets:
public class CriteriaOriginIncludeActivity extends Activity {
private CriteriaOriginIncludeController m_controller;
private CriteriaOriginIncludesAdapter m_listAdapter;
private ArrayList<OriginRowData> m_listData;
private ListView m_originList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.criteria_origin_includes);
ArrayList<OriginRowData> list = new ArrayList<OriginRowData>();
list.add(new OriginRowData(new Origin(0,""), false));
m_listAdapter = new CriteriaOriginIncludesAdapter(this,
R.layout.origin_include_list_row,
R.id.lst_origin_include,
list);
m_originList = (ListView) this.findViewById(R.id.lst_origin_include);
m_originList.setAdapter(m_listAdapter);
m_controller = new CriteriaOriginIncludeController(this);
}
public void setOriginList(ArrayList<OriginRowData> list) {
if (list != null && list.size() > 0) {
m_listData = list;
} else {
m_listData = new ArrayList<OriginRowData>();
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
public void run() {
m_listAdapter.clear();
if(m_listData != null && m_listData.size() > 0){
m_listAdapter.notifyDataSetChanged();
for(int i=0;i<m_listData.size();i++)
m_listAdapter.add(m_listData.get(i));
}
m_listAdapter.notifyDataSetChanged();
}
};
}
And the adapter:
public class CriteriaOriginIncludesAdapter extends ArrayAdapter<OriginRowData> {
private ArrayList<OriginRowData> m_items;
private Context m_context;
public CriteriaOriginIncludesAdapter(Context context, int resourceId, int textViewResourceId, ArrayList<OriginRowData> list) {
super(context, resourceId, textViewResourceId, list);
this.m_context = context;
m_items = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.origin_include_list_row, null);
}
OriginRowData o = m_items.get(position);
if (o != null) {
TextView txtName = (TextView) v.findViewById(R.id.txt_origin_include_name);
TextView txtId = (TextView) v.findViewById(R.id.txt_origin_include_id);
CheckBox chkOrigin = (CheckBox) v.findViewById(R.id.chk_origin);
if (txtName != null) {
txtName.setText(o.getOrigin().getOrigin());
}
if (txtId != null) {
txtId.setText(Integer.toString(o.getOrigin().getId()));
}
if (chkOrigin != null) {
chkOrigin.setChecked(o.getInclude());
chkOrigin.setOnClickListener(new OriginIncludeOnClickListener(position));
}
}
return v;
}
}
You need to override ArrayAdapter's Add() method.
Since you are using your own private private ArrayList<OriginRowData> m_items;, default Add() method does not know that it has to add the data into this array list.
And in your getView you are using m_items array, So this needs to be updated. The default Add() method will add the items to the ArrayAdapter's inbuilt
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