RecyclerView not populating on fragment - java

I have been trying to figure this problem out for quite a while now, but i just can't figure out what the problem is. The aim is to make a request to Songkick api (which is json), which will return the upcoming events of artist and populate it on the the fragment. The request works fine, but it doesn't come on the screen using recyclerView.
This is my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.artispot.fragments.FragmentEvents">
<android.support.v7.widget.RecyclerView
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
This is the Adapter:
public class AdapterEvents extends RecyclerView.Adapter<AdapterEvents.ViewHolderEvents> {
private LayoutInflater layoutInflater;
private String cls = "TAG";
private ArrayList<Events> listEvents = new ArrayList<>();
public AdapterEvents(Context context){
layoutInflater = LayoutInflater.from(context);
}
public void setListEvents(ArrayList<Events> listEvents){
this.listEvents = listEvents;
notifyItemRangeChanged(0,listEvents.size());
}
#Override
public ViewHolderEvents onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_events,parent,false);
ViewHolderEvents viewHolder =new ViewHolderEvents(view);
return viewHolder;
}
//create an object for each textview
#Override
public void onBindViewHolder(ViewHolderEvents holder, int position) {
Events currentEvent = listEvents.get(position);
holder.DateTextView.setText(currentEvent.getStartDate());
// + "--"+ currentEvent.getEndDate()
holder.displayName.setText(currentEvent.getDisplayName());
holder.Venue.setText(currentEvent.getVenue());
}
#Override
public int getItemCount() {
return listEvents.size();
}
static class ViewHolderEvents extends RecyclerView.ViewHolder{
private TextView DateTextView;
private TextView displayName;
private TextView Venue;
public ViewHolderEvents(View itemView){
super(itemView);
DateTextView = (TextView) itemView.findViewById(R.id.DateTextView);
displayName = (TextView) itemView.findViewById(R.id.displayName);
Venue = (TextView) itemView.findViewById(R.id.Venue);
}
}
}
and this part is from my fragment class:
public void sendRequest(){
// Formulate the request and handle the response.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
getRequestUrl(),(String)null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse( JSONObject response) {
listEvents= parseJSONResponse(response);
adapterEvents.setListEvents(listEvents);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
requestQueue.add(request);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_events, container,false);
recyclerView = (RecyclerView)view.findViewById(R.id.List);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapterEvents = new AdapterEvents(getActivity());
recyclerView.setAdapter(adapterEvents);
return view;
}
I have been on this for about a few days, and it's sort of frustrating because it's my project that is due in a week time. Any sort of help will be much appreciated. Thanks in advance.

Related

Setting an id to a Switch

I have a recycle view which populates data from a server, the components inside are a textView and a Switch. The server can return n number of data. How can i set a unique id to the Switch2 when I am populating the data, because later I will need to set a listener to the Switches, My server actually returns a unique id but I'm not so sure on how to set it to the Switch2, or is there any alternate parameters that can be used to identify the Switch?
layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="81dp">
<android:android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="1dp"
card_view:cardUseCompatPadding="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:id="#+id/switch2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:paddingLeft="5dip"
android:layout_marginTop="16dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="254dp" />
<TextView
android:id="#+id/user_set_light_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif"
android:text="TextView"
android:textSize="20dp"
tools:layout_editor_absoluteX="27dp"
tools:layout_editor_absoluteY="23dp" />
</RelativeLayout>
</android:android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
adapter
public class populateLights_adapter extends RecyclerView.Adapter<populateLights_adapter.ViewHolder> {
private List<populate_lights> listItems;
private Context context;
public populateLights_adapter(List<populate_lights> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.addlight_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
populate_lights listItem = listItems.get(position);
holder.lightText.setText(listItem.getLightName());
holder.status.setChecked(listItem.getState());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView lightText;
public Switch status;
public ViewHolder(View itemView) {
super(itemView);
lightText = (TextView) itemView.findViewById(R.id.user_set_light_id);
status = (Switch) itemView.findViewById(R.id.switch2);
}
}
}
java class
public class populate_lights {
private String lightName;
private boolean state;
public populate_lights(String lightName, boolean state){
this.lightName = lightName;
this.state = state;
}
public String getLightName(){
return lightName;
}
public boolean getState(){
return state;
}
}
main
public class lightsControl extends Fragment {
View myView;
public static final String URL = "serverurl.com";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<populate_lights> listItems;
private Switch mySwitch;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.lightscontrol, container, false);
recyclerView = (RecyclerView) myView.findViewById(R.id.lightsView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
listItems = new ArrayList<>();
loadData();
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
return myView;
}
private void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(myView.getContext());
progressDialog.setMessage("Loading");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Snackbar mySnackbar = Snackbar.make(myView, "Data Fetched!", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("DATA_RESPONSE", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("lightData");
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
Log.v("LIGHT ID ", "index=" + obj.getString("LightID"));
Log.v("Value ", "index=" + obj.getBoolean("Value"));
populate_lights popLights = new populate_lights(
obj.getString("LightID"), //unique id
obj.getBoolean("Value") //value returns true, or false
);
listItems.add(popLights);
}
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
}
catch(Exception e){
e.printStackTrace();
}
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar mySnackbar = Snackbar.make(myView, "Oops, there was an error communicating with our server, try again", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("LoginFormERROR", "index=" + error);
progressDialog.dismiss();
}
}
)
};
RequestQueue requestQueue = Volley.newRequestQueue(myView.getContext());
requestQueue.add(stringRequest);
}
public void showErrorAlert(){
AlertDialog.Builder builder1 = new AlertDialog.Builder(myView.getContext());
builder1.setMessage("Opps, something went wring");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Main Menu",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().onBackPressed();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
screenshot
See if this code prints the right position in the logs. Put this inside the constructor of the view holder in the adapter class:
status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Log.d("Position: ", String.valueOf(getLayoutPosition()));
}
});

My Recycler View is asking for List Adapter parameter while setting up adapter

I created a new Dialog fragment to display my listview in a alert dialog builder from here. My code was already working correctly when i was using normal listview instead of recycler view but as soon as i changed it to recycler view it is asking me to cast a parameter of List Adapter while setting the adapter to dialog builder.
Here is my DialogActivity
public class DialogActivity extends DialogFragment {
private RecyclerView recyclerView;
private FoodList adapter;
private List<Food> foodList = new ArrayList<>();
private GoogleMap mMap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new FoodList(foodList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.flist, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
return rootView;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
}
});
alertDialogBuilder.setCancelable(false)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
return alertDialogBuilder.create();
}
}
And here is my adapter
public class FoodList extends RecyclerView.Adapter<FoodList.MyViewHolder> {
Context context;
private List<Food> foodList;
public FoodList(List<Food> foodList) {
this.foodList = foodList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.examplelistview, parent, false);
context = parent.getContext();
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Food food = foodList.get(position);
holder.txtfield1.setText(food.getfield1());
holder.txtfield2.setText(food.getfield2());
holder.txtfield3.setText(food.getfield3());
holder.txtfield4.setText(food.getfield4());
/*
Animation animation = AnimationUtils.loadAnimation(context, R.anim.push_up_in);
animation.setFillEnabled(true);
animation.setFillAfter(true);
view.startAnimation(animation);
*/
}
#Override
public int getItemCount() {
return foodList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView txtfield1, txtfield2, txtfield3, txtfield4;
public MyViewHolder(View view) {
super(view);
txtfield1 = (TextView) view.findViewById(R.id.txtfield1);
txtfield2 = (TextView) view.findViewById(R.id.txtfield2);
txtfield3 = (TextView) view.findViewById(R.id.txtfield3);
txtfield4 = (TextView) view.findViewById(R.id.txtfield4);
}
}
Here is my flist.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
and i am calling dialog fragment in main activity like this
private void startNextActivity() {
FragmentManager fm = getFragmentManager();
DialogActivity testDialog = new DialogActivity();
testDialog.setRetainInstance(true);
testDialog.show(fm, "fragment_name");
}
while setting adapter in dialog builder it is giving me error to give a parameter of ListAdapter
alertDialogBuilder.setAdapter((ListAdapter) adapter, new DialogInterface.OnClickListener()
but in this case also it is giving me error that my custom adapter cannot be converted in List Adapter. I know i am doing some blunder but please can anyone help me!!
Thanks in Advance

Android RecyclerView inside popupwindow is not working?

popup_layout
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
app:cardUseCompatPadding="true">
<android.support.v7.widget.RecyclerView
android:id="#+id/landmarkView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_take_photo_surrounding"/>
</android.support.v7.widget.CardView>
Above code is design for How PopUpWindow will look like. I am opening this PopWindows on EditText.addTextChangedListener.onTextChanged() by calling following method:
private void popupWindow() {
int popupwindowHeight = LinearLayout.LayoutParams.WRAP_CONTENT;
LayoutInflater layoutInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(
R.layout.dashboard_profile_popup_window, null);
final PopupWindow pwindow = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
pwindow.setHeight(popupwindowHeight);
pwindow.setFocusable(true);
pwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
//TODO dismiss settings
}
});
RecyclerView landmarkRecyclerView = (RecyclerView) layout.findViewById(R.id.landmarkView);
List<String> data = new ArrayList<String>();
data.add("my data");
data.add("set Data");
landmarkRecyclerView.setAdapter(new LandmarkRecyclerViewAdapter(data, getContext()));
pwindow.setWindowLayoutMode(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
pwindow.setHeight(1);
pwindow.setWidth(1);
pwindow.showAtLocation(layout, Gravity.NO_GRAVITY, mPoint.x, mPoint.y);
pwindow.showAsDropDown(place_pop_up);
}
But what I can see through above code is :
A blank PopUpWindow on Text change listener. What I am doing wrong here?
edit
Adding LandMarkRecyclerViewAdapter too
public class LandmarkRecyclerViewAdapter extends RecyclerView.Adapter<LandmarkRecyclerViewAdapter.ViewHolder> {
private Context mContext;
private List<String> mLocalityEntities;
public LandmarkRecyclerViewAdapter(List<String> localityEntityList, Context context){
this.mContext = context;
this.mLocalityEntities = localityEntityList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.landmark_view_adapter, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if( null != mLocalityEntities.get(position)){
holder.mTextView.setText(mLocalityEntities.get(position).toString());
}
}
#Override
public int getItemCount() {
return mLocalityEntities.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.landmarkText);
}
}
}

Button setOnClickListener in a ListView

I'm trying to get the onclick event of a button inside a listview, but it's not working
fragment_contact.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="404dp"
android:layout_weight="0.64"
android:orientation="horizontal"
android:paddingBottom="40dip" >
<ListView
android:id="#+id/contactlistview"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="fill"
android:layout_weight="10"
android:textSize="5pt"
android:visibility="visible" />
</LinearLayout>
fragment_contact_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btn_edit_contact"
android:layout_gravity="right" />
</LinearLayout>
FragmentContact.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_contact, container, false);
ListAdapter adapter_contact = new SimpleAdapter(
getActivity(), allcontact,
R.layout.fragment_contact_content, new String[]{"name", "level", "function", "phone", "email"},
new int[]{R.id.contact, R.id.level, R.id.function, R.id.phone, R.id.email});
listview_contact = (ListView) view.findViewById(R.id.contactlistview);
listview_contact.setItemsCanFocus(true);
listview_contact.setAdapter(adapter_contact);
Button btn_edit_contact = (Button) view.findViewById(R.id.btn_edit_contact);
btn_edit_contact.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Do something");
}
});
return view;
}
I also tried inflating fragment_contact_content.xml but the button still does nothing.
Use custom Adapter and in getView Write your code
public class MealAdapter extends BaseAdapter{
private int mHour, mMinute;
int minutes,hour;
String strtime;
customButtonListener customListner;
private Context context;
private List<Meal> rowItems;
public MealAdapter(Context context, List<Meal> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
private class OptionHolder
{
ImageButton btn_time;
ImageButton btn_delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final OptionHolder holder;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.meal_list_item, null);
holder = new OptionHolder();
holder.btn_time= (ImageButton) convertView.findViewById(R.id.btn_time);
holder.btn_delete =(ImageButton) convertView.findViewById(R.id.btn_delete_meal);
convertView.setTag(holder);
}
else
{
holder = (OptionHolder) convertView.getTag();
}
final Meal row_pos=rowItems.get(position);
row_pos.setMeal("");
row_pos.setDetail("");
holder.ed_meal.setText(row_pos.getMeal());
holder.ed_detail.setText(row_pos.getDetail());
holder.ed_time.setText(row_pos.getTime());
holder.btn_time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(MealPlannerFragment.con,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
strtime=(hourOfDay + ":" + minute);
row_pos.setTime(strtime);
row_pos.setMunite(minute);
row_pos.setHour(hourOfDay);
holder.ed_time.setText(row_pos.getTime());
}
}, mHour, mMinute, false);
tpd.show();
}
});
holder.btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (customListner != null) {
customListner.onButtonClickListner(position,row_pos);
}
}
});
return convertView;
}
public interface customButtonListener {
public void onButtonClickListner(int position,Meal row_pos);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
}
`
you can not get Listview cell's Button event directly in onCreateView. you have to make CustomAdapter class for that.
you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fragment_contact_content, null);
}
//Handle button and add onClickListener
Button editBtn = (Button)view.findViewById(R.id.btn_edit_contact);
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
//some other task
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
You can refer this link: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
just handle on click listener inside getview where you find the button using findviewbyid
I hope it helps!

My custom listview scrolls back to first element instantly when scrolling up. How to prevent that and make a smooth scrolling

I am trying to create a custom listview like this: http://i.stack.imgur.com/l8ZOc.png
Currently I managed to create it but there is a problem. For example when there are 8 items, it loads the first 4, then loads the remiaining items as you scroll down. When scrolling down, it works fine.
However, when scrolling back up from bottom, at the middle of list, it instantly moves to top, skipping 2-3-4. items. Then you can scroll down normally again, but when scrolling up, it instantly goes to top of the list.
How can i prevent this from happening?
Here is my code:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
String headers[];
String image_urls[];
List<MyMenuItem> menuItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
menuItems = new ArrayList<MyMenuItem>();
headers = getResources().getStringArray(R.array.header_names);
image_urls = getResources().getStringArray(R.array.image_urls);
for (int i = 0; i < headers.length; i++) {
MyMenuItem item = new MyMenuItem(headers[i], image_urls[i]);
menuItems.add(item);
}
mylistview = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
}
}
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
// .placeholder(R.drawable.empty)
// .error(R.drawable.error)
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
Use lazy loading mechanism to load your image data.
There is one nice example here

Categories