I have ListView with items. I'm using XML to parse data. In that moment I parse data for one item in DetailsView. When I clicked on item, how to make DetailsView for items with SwipeViews beetween items? How to implement with ViewPager? I try to develop some examples, but didn't work. I would be grateful if someone help me.
So first create a Fragment for your detail. This is for a single detail. The detail that you'll swipe. So apply your layout to this.
#SuppressLint("ValidFragment")
public class Detail extends Fragment {
private final String detail;
public DetailView(String detail) {
this.detail = detail;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detailfragment, container, false);
TextView textView = (TextView) view.findViewById(R.id.detailText);
textView.setText(detail);
return view;
}
}
Now create your Activity. This is the Activity that you will go when you clicked. Now the code adds a Fragment for every detail.
public class Main extends FragmentActivity {
public static ViewPager mPager;
private MyAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPager = (ViewPager) findViewById(R.id.viewPager1);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
//The count of details. This will return 5 swipeable views.
return 5;
}
#Override
public Fragment getItem(int position) {
return new Detail("I'm a detail!");
}
}
}
This will create 5 details with text "I'm a detail!". Now, i assume you are using ArrayList that storing details. Then you can get the details like this:
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm, ArrayList<HashMap<String, String>> d) {
super(fm);
data = d;
}
#Override
public int getCount() {
return 5;
}
#Override
public Fragment getItem(int position) {
HashMap<String, String> map = new HashMap<String, String>();
map = data.get(position);
Log.d("", data.get(position).toString());
return new Detail(map.get('KeyForYourDetail'));
}
}
Also on your MainActivity change
mAdapter = new MyAdapter(getSupportFragmentManager());
to this
mAdapter = new MyAdapter(getSupportFragmentManager(), yourArrayList);
EDIT
Let's start from the beginning. First, you have your MainActivity which contains a ListView. In the ListView, you are calling items from ArrayList. When you click a item, you get the detail about it from (?). Now my above code can't do that. You have to do that your own first. After you get the detail, just replace the title part below. To summarize, the code i post should work if you can get the "detail", if you don't know how to get detail, then you should create another question.
return new Detail(title);
EDIT 2
OK, here is the other part. Below code is for FragmentActivity.
First, we need to declare our adapter and ViewPager.
public static ViewPager mPager;
private MyAdapter mAdapter;
ArrayList<HashMap<String, String>> detailList= new ArrayList<HashMap<String, String>>();
MyAdapter is the adapter that puts the details into ViewPager. To hold details, we also need an ArrayList as i declared above. Now, you said you don't have problem with parsing. So I'm skipping that part. While you're parsing, I assume you are using NodeList(i took that part from here)
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes
for (int i = 0; i < nl.getLength(); i++) {
String name = parser.getValue(e, KEY_NAME); // name child value
String cost = parser.getValue(e, KEY_COST); // cost child value
String description = parser.getValue(e, KEY_DESC); // description child value
}
Inside of your for loop, create a HashMap like this
HashMap<String, String> map = new HashMap<String, String>();
Remember while we were creating our ArrayList? It's object was HashMap. Now we are going to fill our data to map, then add map to ArrayList. (Again, this goes inside of for loop)
map.put(TAG_DETAIL, detail);
detailList.add(map);
Now this part is over, only thing left is setting the adapter.
mAdapter = new MyAdapter(getSupportFragmentManager(), detailList);
mPager.setAdapter(mAdapter);
And we are done! Let me explain what's going to happen next. Do you remember our adapter?
public MyAdapter(FragmentManager fm, ArrayList<HashMap<String, String>> d) {
super(fm);
data = d;
}
Here as you see, it takes a FragmentManger and an ArrayList with Hashmap inside of it. we set those with getSupportFragmentManager() and detailList. Adapter takes the detailList with details inside of it, then creates Fragments with it. I hope it was clear enough. If wasn't, ask again.
This is the code of MyAdapter.java:
public class MyAdapter extends ArrayAdapter {
ImageLoader imageLoader;
DisplayImageOptions options;
public MyAdapter(Context ctx, int textViewResourceId, List<NewsFeed> 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()
.cacheOnDisc()
.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 StackSite object that can be put
* into our ListView
*/
#Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("Feed", "getView pos = " + pos);
// 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.list_item, null);
// }
if (pos != 0){
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.list_item, null);
}
else
{
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.list_first_item, null);
}
//Get our View References
final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);
TextView titleTxt = (TextView)row.findViewById(R.id.titleTxt);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
//Initially we want the progress indicator visible, and the image invisible
indicator.setVisibility(View.VISIBLE);
iconImg.setVisibility(View.INVISIBLE);
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
indicator.setVisibility(View.INVISIBLE);
iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
imageLoader.displayImage(getItem(pos).getImgUrl(), iconImg,options, listener);
//Set the relavent text in our TextViews
titleTxt.setText(getItem(pos).getTitle());
return row;
}
}
Related
I want to ask,
I have 2 classes:
1. an activity class (to get data from json)
2. a fragment class (not to do something)
and I want to get data from json of activity via fragment class.
Can be combine Activity and Fragment in a class ? and how to do ?
I combined activity and fragment in a Fragment class, I have used a GridView to get data and display
JSON, execute the AsyncTask in the this Fragment
This is my code after updated 25/10:
public class FeedBackFragment extends Fragment {
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
MyAdapter adapter;
JSONArray manufacturers = null;
// manufacturers JSON url
private static final String URL_MANUFACTURERS ="MYURL";
public FeedBackFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.feedback_gridview_manufacturer, container, false);
GridView gridView = (GridView) view.findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(getActivity(), manufacturersList));
gridView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// on selecting a single manufacturer
// CategoryCarActivity will be launched to show category car inside the manufacturer
Intent i = new Intent(getActivity(), CategoryCarActivity.class);
// send manufacturer id to activity to get list of cars under that manufacturer
String manufacturer_id = ((TextView) view.findViewById(R.id.manufacturer_id)).getText().toString();
i.putExtra("manufacturer_id", manufacturer_id);
startActivity(i);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// manufacturersList = new ArrayList<>();
new LoadAllManufacturers().execute();
}
class LoadAllManufacturers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter.notifyDataSetChanged();
// dismiss the dialog after getting all manufacturers
if (pDialog.isShowing())
pDialog.dismiss();
}
}
private class MyAdapter extends BaseAdapter
{
// List<POJOManufacturer> listData = null;
LayoutInflater inflater;
Context context;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> arrayList)
{
// this.context = context;
this.manufacturersList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
if (manufacturersList != null)
return manufacturersList.size();
return 0;
}
#Override
public Object getItem(int i)
{
if (manufacturersList != null)
return manufacturersList.get(i);
return null;
}
#Override
public long getItemId(int i)
{
if (manufacturersList != null)
return manufacturersList.get(i).hashCode();
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup)
{
ViewHolder holder;
if (convertView == null)
{
convertView = inflater.inflate(R.layout.gridview_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.text);
holder.iconName = (ImageView) convertView.findViewById(R.id.picture);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(this.manufacturersList.get(i).getClass().getName());
// holder.iconName.setImageResource(this.manufacturersList.get(i).image);
return convertView;
}
public class ViewHolder
{
TextView name;
ImageView iconName;
}
}
}
I have updated and added: manufacturerList = new ArrayList<>. everything seem is better, and it happen some issues in getView() method,
I have try and it's only display with 7 empty items in gridview, and not display content and image
So How fill data from Adapter into Gridview?
constructor ManufacturerFragment in class ManufacturerFragment cannot be applied to given types;
gridView.setAdapter() takes an adapter, not a Fragment
And new ManufacturerFragment() doesn't accept an Context.
I am not really sure why you think you need to create a new ManufacturerFragment within the Fragment class you already are in. Did you mean to do gridView.setAdapter(new MyAdapter(getActivity()))?
Also, your manufacturersList needs to be loaded into that adapter, so you'll need to figure that out.
And you need to use getActivity() instead of getActivity().getApplicationContext() in most places.
Then, you should only call new LoadAllManufacturers().execute(); in either onCreateView or onActivityCreated, not both. Otherwise, you're running two AsyncTasks.
Then, onPostExecute already runs on the UI thread, no need to use getActivity().runOnUiThread(new Runnable() {...
Once you do figure out how to put that ArrayList into the Adapter class, you'll want to call adapter.notifyDataSetChanged() within onPostExecute to tell the adapter to refresh the data, thereby updating the GridView to display the data.
I am trying to update the content of my listview by adding stuff to it. Although the listview does update its contents the size still stays the same for some reason. So for example, if the original listview contains A, B, Y, Z and I add C and D to it, the updated list view will be: A, B, C, D. What am I doing wrong?
Here is some relavent code:
//in main activity...
//additionalSongs is an arraylist
addAdditionalSongs(additionalSongs);//add the additional songs to the main list
songTabFragment = new SongTabFragment();//update the list on the screen
...
private void addAdditionalSongs(ArrayList<Song> additionalSongs){
for(int i = 0; i < additionalSongs.size(); i++) {
songList.add(additionalSongs.get(i));
}
}
SongTabFragment class
public class SongTabFragment extends Fragment {
private ListView songView;
private Context context;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.song_tab_layout, container, false);
songView = (ListView) rootView.findViewById(R.id.song_list); //get a reference to the ListView created in song_tab_layout
SongAdapter theAdapter = new SongAdapter(context, MainActivity.getSongArray());
songView.setAdapter(theAdapter); //pass the ListView object the appropriate adapter
return rootView;
}
}
SongAdapter class
public class SongAdapter extends BaseAdapter {
private ArrayList<Song> songArray;
private LayoutInflater songInf;
public SongAdapter(Context c, ArrayList<Song> grabbedSongArray){
songArray = grabbedSongArray;
songInf = LayoutInflater.from(c);
}
#Override
public int getCount() {
return songArray.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = (LinearLayout)songInf.inflate(R.layout.song, parent, false);
//layout for each individual song in the list. Uses song.xml
TextView songView = (TextView)listLayout.findViewById(R.id.song_title);
TextView artistView = (TextView)listLayout.findViewById(R.id.song_artist);
Song currentSong = songArray.get(position);
songView.setText(currentSong.getTitle()); //pass data to textView objects in each list item
artistView.setText(currentSong.getArtist());
listLayout.setTag(position); //use the song's position in list as a tag
return listLayout;
}
}
It might be that the SongTabFragment is not being updated. Instead of accessing your song array via the MainActivity
MainActivity.getSongArray()
Why not add a method in your fragment to update the arraylist in the SongAdapter and then notify the list view that the data set has changed so that it will recreate the view based on the new array list.
Example
In fragment class
// Fragment code
public void updateAdapterArray(ArrayList<Songs> adapter) {
((SongAdapter) mListView.getAdapter()).setSongs(adapter);
}
In adapter class
//Adapter code
public void setSongs(ArrayList<Songs> adapter) {
this.songList = adapter;
notifyDataSetChanged();
}
In mainactivity
// your mainactivity code
SongTabFragment songFragment = (SongTabFragment) mFragmentManager.findFragmentById(R.id.fragContainer);
songFragment.updateAdapterArray(newSongList);
Check your getCount() method,
#Override
public int getCount() {
return list.getSize(); //it should return size of list. Not 4
}
Are you updating the item count in your list view? If the listview still only thinks there are 4 items in the list it will only display 4 items. You have to update the value the getCount() returns.
This is a follow on from an earlier question: ImageButton within row of ListView android not working
But after suggestions from SO gurus it has been suggested I post a new question.
The issue is that I have a custom adapter that is not showing any data. I have looked into other questions, but it didn't provide a solution.
In my Main Activity I have a couple of buttons, one of them: ToDo, should create a row that displays data from a SQLite database, and depending on some factors (dates mainly), it shows a type of traffic light that is stored as a drawable.
Part of the Items in this Row is an Image Button that I want the user to be able to click and the image should change. The user should be able also to click on the actual row and a new activity starts.
The issue I have is that NO DATA is being displayed.
So, here is my code:
public class MainActivity extends Activity {
// definitions etc ...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// definitions etc ...
}
public void ToDo(View v){ // the user has clicked in the ToDo button
IgroDatabaseHelper helper = new IgroDatabaseHelper(getBaseContext()); // create instance of SQLIte database
numRows = helper.NumEntries("ToDo"); // Get the number of rows in table
int i = 1;
ArrayList<RowItem> rowItems = new ArrayList<>();
RowItem myItem1;
while (i <= numRows){
// get items from database
// depending on value select different drawable
// put data into List Array of RowItem
myItem1 = new RowItem(TheWhat, R.drawable.teamworka, R.drawable.redtrafficlight, R.drawable.checkbox, TheWhenBy);
rowItems.add(myItem1);
//
i = i+ 1;
}
ListView yourListView = (ListView) findViewById(R.id.list);
CustomListViewAdapter customAdapter = new CustomListViewAdapter(this, R.layout.todo_row, rowItems);
yourListView.setAdapter(customAdapter);
}
The CustomListViewAdapter looks like this:
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
ArrayList<RowItem> _rowItems;
public CustomListViewAdapter(Context context, int resourceId,
ArrayList<RowItem> rowItems) {
super(context, resourceId);
this.context = context;
_rowItems = rowItems;
System.out.println("I am in the custom Adapter class "+ _rowItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
System.out.println("This is the get view");
View row = convertView;
RowItem item = _rowItems.get(position);
// you can now get your string and drawable from the item
// which you can use however you want in your list
String columnName = item.getColumnName();
int drawable = item.getDrawable();
if (row == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.todo_row, parent, false);
}
ImageButton chkDone = (ImageButton) row.findViewById(R.id.chkDone);
chkDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
System.out.println("I am in position "+ position);
}
});
return row;
}
}
The RowItem Class looks like:
public class RowItem {
private String _heading;
private int _icon;
private int _lights;
private int _chkdone;
private String _date;
public RowItem(String heading, int icon, int lights, int chkDone, String date) {
_heading = heading;
_icon = icon;
_lights = lights;
_chkdone = chkDone;
_date = date;
System.out.println("adding stuff to my rows");
System.out.println("my column Name is " + heading);
System.out.println("My drawable int is "+ icon);
}
public String getColumnName() {
System.out.println("column Names is "+ _heading);
return _heading;
}
public int getDrawable() {
return _icon;
}
public int getLights(){
return _lights;
}
public int getchkDone(){
return _chkdone;
}
public String getDate(){
return _date;
}
}
I am obviously missing something, as I mentioned earlier, no data gets shown. I know that there are 2 row items that get passed to the CustomListViewAdapter. But I also know that the View getView inside the CustomListViewAdapter does not actually get called.
I hope I have put enough information/code, but if you feel I need to explain something further, please say.
Thanking all very much in advance!
I don't see a getCount() method. You should be overriding it like this:
#Override
public int getCount() {
return _rowItems.getCount();
}
Alternatively, calling super(context, resourceId, rowItems); should also fix it.
Your ListView thinks there are no items to display. If you are using your own array, you must override the getCount() method to indicate the number of items you want to display.
What i am doing:: I have a horizontal listview as shown below for which i am populating items dynamically
What is happening:: Since its a dynamically created listview onorientation change the checked items are unchecked
Question: How can i collected the checked items from the adapter and recheck the selected things on orientation change
AdpBufTypeSearch.java
public class AdpBufTypeSearch extends BaseAdapter{
private HashMap<String, String> objHashBufType;
SparseBooleanArray mBufTypeArr = new SparseBooleanArray();
private ArrayList<HashMap<String, String>> objListBufType;
Context mContext;
public AdpBufTypeSearch(Context _mContext,ArrayList<HashMap<String, String>> _objListBufType) {
mContext=_mContext;
objListBufType=_objListBufType;
}
#Override
public int getCount() {
return objListBufType.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
//LOGIC:: result will be a set on which ones are selected Ex:: 0,1,2,4
public String getSelectedBuffetType() {
//This final value(strBufTypeId) is returned when we access from class
String strBufTypeId="";
for(int i=0;i<objListBufType.size();i++) {
HashMap<String, String> objHashBufType = objListBufType.get(i);
if(objHashBufType.get("selected")=="1") {
strBufTypeId=strBufTypeId+objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_ID);
strBufTypeId=strBufTypeId+",";
}
}
//remove the last "," in the string
if(strBufTypeId.lastIndexOf(",")>0)
strBufTypeId=strBufTypeId.substring(0, strBufTypeId.lastIndexOf(","));
return strBufTypeId;
}
/*LOGIC:: <HashMapObject(objHashBufType)> ==> their value of key(selected) is updated to "1" else key(selected) is updated to 0 */
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.adp_meal_type, null);
final TextView buf_type_name = (TextView) retval.findViewById(R.id.buf_type_name);
TextView buf_type_id=(TextView) retval.findViewById(R.id.buf_type_id);
ImageView buf_type_image=(ImageView) retval.findViewById(R.id.buf_type_image);
final LinearLayout imgBkgSelector=(LinearLayout) retval.findViewById(R.id.imgBkgSelector);
imgBkgSelector.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//LOGIC:: If Selected unselect it and if it is unselected select it
if(mBufTypeArr.get((Integer) imgBkgSelector.getTag())==true){
//INNER-LOGIC:: Background not selected
mBufTypeArr.put((Integer) imgBkgSelector.getTag(), false);
objHashBufType = objListBufType.get((Integer) imgBkgSelector.getTag());
objHashBufType.put("selected", "0");
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlack)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
else{
//INNER-LOGIC:: Background selected
mBufTypeArr.put((Integer) imgBkgSelector.getTag(), true);
objHashBufType = objListBufType.get((Integer) imgBkgSelector.getTag());
objHashBufType.put("selected", "1");
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlue)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
}
});
imgBkgSelector.setTag(position);
//Essential code for retain the Background check part on scroll of images
if(mBufTypeArr.get(position)==true){
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlue)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}else{
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlack)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
// Get the position
objHashBufType = objListBufType.get(position);
// Capture position and set results to the TextViews
//Capitilize the names
String capitalizedBufTypeName = WordUtils.capitalizeFully(objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_NAME), ' ');
buf_type_name.setText(capitalizedBufTypeName);
buf_type_id.setText(objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_ID));
Picasso.with(mContext)
.load(mContext.getString(R.string.URL_BUFFET_TYPE_IMAGE).trim()+objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_IMAGE).trim()).resizeDimen(R.dimen.filter_image_width,R.dimen.filter_image_height).centerCrop().into(buf_type_image);
return retval;
}
}
FrgMdSearch .java
public class FrgMdSearch extends Fragment {
private HashMap<String, String> objHashBufType;
private ArrayList<HashMap<String, String>> objListBufType=null;
private AdpBufTypeSearch bufTypeAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Setting the adapter for buf images<---DYNAMIC VIEWS--->
setAdapterBufImages();
}
private void setAdapterBufImages() {
bufTypeAdapter=new AdpBufTypeSearch(getActivity(),objListBufType);
hListView.setAdapter(bufTypeAdapter);
}
}
You need to save the position of the checked item when orientation change occurs in your onSaveInstanceState method also create a getter method in your AdpBufTypeSearch adapter that returns the current position of the checked item and setter method to set the checked item.
sample:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", bufTypeAdapter.getCheckedPosition()); //getCheckedPosition must return the checked item position
}
In oncreateView of the fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Setting the adapter for buf images<---DYNAMIC VIEWS--->
setAdapterBufImages(savedInstanceState);
}
private void setAdapterBufImages(Bundle savedInstanceState) {
bufTypeAdapter=new AdpBufTypeSearch(getActivity(),objListBufType);
if(savedInstanceState != null)
{
bufTypeAdapter.setCheckedItem(savedInstanceState.getInt("position")); //will set the checked item
}
hListView.setAdapter(bufTypeAdapter);
}
i have parsed Json data from the server. On which im showing all the data in listview and i have Load more option below the ListView. Now when i click load more option, this application reload whole list and did not show previous list data. Please help me find out the solution. Here is footer view click listener :
lFooter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
page += 1;
new ParseIssues().execute();
listView.removeFooterView(v);
}
});
in above code ParseIssues class parse json values and displays all the data in ListView Here is code for onPostExecute of AsynkTask class :
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(page < totalPage){
listView.addFooterView(v);
}
listAdapter = new ListAdapterForSearch(activity, mainList);
listView.setAdapter(listAdapter);
// get listview current position - used to maintain scroll position
int currentPosition = listView.getFirstVisiblePosition();
listView.setSelection(currentPosition);
}
Here is BaseAdapter class:
public class ListAdapterForSearch extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ListAdapterForSearch(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.list_row_item, null);
}
TextView title = (TextView)vi.findViewById(R.id.title);
HashMap<String, String> hash = new HashMap<String, String>();
hash = data.get(position);
title.setText(hash.get("title"));
return vi;
}
}
The answer to your question lies with the variable "mainList", which the adapter uses. You need to add the new data to it, basically this list needs to contain all the data you want to show in your ListView.
You should set adapter on create, after that first add loaded data to mainlist(add new loaded data) & then after loading notify adapter like listadapter.notifydatachange()
Edit: Because every time you are creating adapter that's why you are facing this problem, instead after loading just notify your adapter..
Check in your code you may have clear your mainList.