Am trying to build my first app and my recyclerView only displays the first item from the json.I have tried changing the layout height to wrap_content but its still not working
Here is the xml layout for the recyclerview activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
the cardview xml layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
cardview:cardCornerRadius="2dp"
cardview:cardElevation="3dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:paddingBottom="15dp">
<TextView
android:id="#+id/car_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:fontFamily="sans-serif-smallcaps"
android:text="Car Name"
android:textColor="#996515"
android:textSize="24sp"
android:textStyle="bold" />
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/Car_image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_below="#+id/car_name"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp" />
<TextView
android:id="#+id/tvfeature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="90dp"
android:layout_marginTop="25dp"
android:layout_toRightOf="#+id/car_name"
android:text="Features"
android:textColor="#000"
android:textSize="22sp" />
<View
android:layout_width="100dp"
android:layout_height="1dp"
android:layout_below="#+id/tvfeature"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/Car_image"
android:background="#000" />
<ImageView
android:id="#+id/ac"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/tvfeature"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/air_conditioner" />
<TextView
android:id="#+id/feature1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvfeature"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/ac"
android:text="Air conditioner"
android:textColor="#000"
android:textSize="16sp" />
<ImageView
android:id="#+id/tr"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/feature1"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/transmission" />
<TextView
android:id="#+id/feature2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/feature1"
android:layout_marginLeft="2dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/tr"
android:text="Manual"
android:textColor="#333333"
android:textSize="16sp" />
<ImageView
android:id="#+id/pass"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/tr"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/passengers" />
<TextView
android:id="#+id/feature3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/feature2"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/pass"
android:text="6 Passengers"
android:textColor="#333333"
android:textSize="16sp" />
<TextView
android:id="#+id/pricetxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Car_image"
android:text="Price :"
android:textColor="#333333"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="#+id/car_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Car_image"
android:layout_marginLeft="2dp"
android:layout_toRightOf="#+id/pricetxt"
android:text="KSH.2000"
android:textColor="#996515"
android:textSize="22sp" />
<TextView
android:id="#+id/organiser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pricetxt"
android:layout_marginTop="5dp"
android:text="Owner :"
android:textColor="#333333"
android:textSize="14sp" />
<TextView
android:id="#+id/crAgent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pricetxt"
android:layout_marginLeft="2dp"
android:layout_marginTop="5dp"
android:layout_toEndOf="#+id/organiser"
android:layout_toRightOf="#+id/organiser"
android:text="Supercars Rentals"
android:textColor="#05056c"
android:textSize="14sp" />
<Button
android:id="#+id/btn_rent"
style="#style/AppTheme.ButtonCorners"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/Car_image"
android:layout_marginRight="12dp"
android:clickable="true"
android:text="Rent"
android:textColor="#eef525" />
<TextView
android:id="#+id/car_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
</RelativeLayout>
</android.support.v7.widget.CardView>
The cars.java class to load items into the recyclerview
public class cars extends AppCompatActivity {
String url = "http://192.168.43.201/Car_rental/retrievecars.php";
Context context = null;
ProgressDialog dialog;
private List<CarsItem> array_cars = new ArrayList<>();
AdapterClass adapter;
NetworkImageView carsImageview;
private String user_Location = "cLocation";
private String Category = "category";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cars);
adapter = new AdapterClass(cars.this, array_cars);
RecyclerView recycler = (RecyclerView) findViewById(R.id.rv);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setAdapter(adapter);
setCars();
recycler.addOnItemTouchListener(new RecyclerTouchListener(this, recycler, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void setCars() {
dialog = new ProgressDialog(this);
dialog.setMessage("Loading cars...");
dialog.show();
if (array_cars != null) {
array_cars.clear();
}
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
hideDialog();
Log.d("Sever Message", s);
JSONObject cars = new JSONObject(s);
JSONArray jsonArray = cars.getJSONArray("Cars");
JSONObject jobject = null;
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
jobject = jsonArray.getJSONObject(i);
CarsItem carsdata = new CarsItem();
carsdata.setId(jobject.getString("0"));
carsdata.setCarname(jobject.getString("1"));
carsdata.setImages(jobject.getString("car_image"));
carsdata.setfeature1(jobject.getString("5"));
carsdata.setfeature2(jobject.getString("6"));
carsdata.setfeature3(jobject.getString("7"));
carsdata.setPrice(jobject.getString("8"));
array_cars.add(carsdata);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Getting Image Location & category
String Location = "";
String Ccategory = "cars";
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(Category, Ccategory);
params.put(user_Location, Location);
//returning parameters
return params;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding our request to the queue
// requestQueue.add(request);
AppController.getmInstance().addToRequestQueue(request);
}
public void hideDialog() {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
GestureDetector gestureDetector;
cars.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final cars.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recycler, MotionEvent e) {
View child = recycler.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recycler.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recycler, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
and finally my adapter class
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.CustomViewHolder> {
private List<CarsItem> Array_cars;
private ImageLoader imageLoader;
private Context mContext;
public AdapterClass(Context context, List<CarsItem> array_cars) {
this.Array_cars = array_cars;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cars_design, null);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder,final int i) {
final CarsItem carsItem = Array_cars.get(i);
holder.imageUrl = carsItem.getImages();
imageLoader = AppController.getmInstance().getmImageLoader();
holder.Carname.setText(carsItem.getCarname());
holder.feature1.setText(carsItem.getfeature1());
holder.feature2.setText(carsItem.getfeature2());
holder.feature3.setText(carsItem.getfeature3());
holder.price.setText(carsItem.getPrice());
holder.agent.setText(carsItem.getcarowner());
holder.carid.setText(carsItem.getId());
holder.carimage.setImageUrl("http://192.168.43.201/Car_rental/cars/"+carsItem.getImages(), imageLoader);
holder.rent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, HireCar.class);
intent.putExtra("carname",carsItem.getCarname());
intent.putExtra("car_rate",carsItem.getPrice());
intent.putExtra("car_image", carsItem.getImages());
intent.putExtra("car_id", carsItem.getId());
intent.putExtra("c_owner", carsItem.getcarowner());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return (null != Array_cars ? Array_cars.size() : 0);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
String imageUrl;
TextView Carname, feature1, feature2, feature3, price,agent,carid;
NetworkImageView carimage;
Button rent;
public CustomViewHolder(View view) {
super(view);
this.Carname = (TextView) view.findViewById(R.id.car_name);
this.feature1 = (TextView) view.findViewById(R.id.feature1);
this.feature3 = (TextView) view.findViewById(R.id.feature3);
this.price = (TextView) view.findViewById(R.id.car_price);
this.feature2=(TextView) view.findViewById(R.id.feature2);
this.carimage = (NetworkImageView) view.findViewById(R.id.Car_image);
this.rent=(Button)view.findViewById(R.id.btn_rent);
this.agent=(TextView)view.findViewById(R.id.crAgent);
this.carid=(TextView)view.findViewById(R.id.car_id);
}
}
}
I think the problem is that you are not adding the elements to the adapter. You need to have a method in the adapter to add items after the adapter has been created. Inside that method you need to notify. Example:
void addItems(List<CarItem> carItems){
Array_cars.addAll(carItems);
notifyDataSetChanged();
}
However, I would go a bit far and find the number of items and try to notify only for the newly inserted ones(in case there is something already).
This can be done like this:
void addItems(List<CarItem> carItems){
int position = Array_cars.size();
Array_cars.addAll(carItems);
notifyItemRangeChanged(position, Array_cars.size() - position);
}
EDIT
Look at this example below:
RecycleView
Here is the xml layout for the recyclerview activity
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
You have added match_parent height of "RecyclerView" please change to wrap_content.
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
Related
I am creating a weather forecast aplication. For this I want to use RecyclerView to show items. The problem is that my RecyclerView is showing only one item instead of all. I am using the OpenWeatherMap API forecast.
This is my layout:
<LinearLayout 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="match_parent"
android:layout_gravity="center"
android:background="#drawable/weather_background2"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txt_close_weather"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:background="#drawable/circle"
android:gravity="center"
android:text="X"
android:textColor="#color/blackTransparent"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:orientation="vertical">
<TextView
android:id="#+id/city_country_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="0dp"
android:text="KOTA"
android:textColor="#color/blackTransparent"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="2dp"
android:text="Today"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
<TextView
android:id="#+id/current_date_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="4dp"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
<ImageView
android:id="#+id/weather_icon"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_gravity="center|center_horizontal"
android:layout_marginTop="8dp"
android:contentDescription="#string/app_name"
android:src="#drawable/img_02d" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="3">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tv_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hummidity"
android:textColor="#color/blackTransparent"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:id="#+id/wind_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="#string/app_name"
android:textColor="#color/blackTransparent"
android:textSize="14dp" />
<TextView
android:id="#+id/temperature_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="#string/app_name"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:gravity="center_horizontal"
android:background="#color/whiteTr"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2.5"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/weather_daily_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:scrollbars="none" />
</LinearLayout>
</LinearLayout>
This my code in activity :
public class DialogWeather extends android.app.DialogFragment {
public static final int WIDTH = 60;
public static final int HEIGHT = 80;
public static final String DATE_FORMAT_WITHOUT_TIME = "dd/MM";
private static final String ICON_PREFIX = "img_";
private static final String API_KEY = "2fc56d498a3b4d87ba298c232e65e6b0";
private static final String UNITS = "metric";
final String q = "Jakarta";
PopupWindow myPopupWindow;
Dialog myDialog;
DialogWeather dialogWeather;
private TextView txtCloseWeather, txtCityCountry,
txtCurrentDate, tvDescription, tvWindResult, tvTemperatureResult;
private ImageView weatherIcon;
private RecyclerView mRecyclerViewWeather;
DialogWeatherAdapter dialogWeatherAdapter;
private ArrayList<Example2> weathers = new ArrayList<>();
Example2 example2List;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_dialog_weather,
container, false);
getDialog().getWindow().setBackgroundDrawable(new
ColorDrawable(Color.TRANSPARENT));
tvDescription = rootView.findViewById(R.id.tv_description);
tvWindResult = rootView.findViewById(R.id.wind_result);
tvTemperatureResult = rootView.findViewById(R.id.temperature_result);
weatherIcon = rootView.findViewById(R.id.weather_icon);
txtCityCountry = rootView.findViewById(R.id.city_country_weather);
txtCityCountry.setTypeface(Typeface.DEFAULT_BOLD);
txtCurrentDate = rootView.findViewById(R.id.current_date_weather);
txtCloseWeather = rootView.findViewById(R.id.txt_close_weather);
txtCloseWeather.setTypeface(Typeface.DEFAULT_BOLD);
Fragment fragment = this;
txtCloseWeather.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Button Close",
Toast.LENGTH_LONG).show();
getActivity().getFragmentManager().beginTransaction()
.remove(fragment).commit();
}
});
mRecyclerViewWeather = rootView.findViewById(R.id.weather_daily_list);
LinearLayoutManager layoutManager = new
LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
mRecyclerViewWeather.setLayoutManager(layoutManager);
mRecyclerViewWeather.setHasFixedSize(true);
dialogWeatherAdapter = new DialogWeatherAdapter(weathers);
mRecyclerViewWeather.setAdapter(dialogWeatherAdapter);
loadWeathers(q, API_KEY, UNITS);
return rootView;
}
private void loadWeathers(String q, String apiKey, String units) {
ApiServicesWeather weather = InitRetrofitWeather.getServicesWeather();
Call<Example2> exampleCall = weather.getDetailWeather(q, apiKey, units);
exampleCall.enqueue(new Callback<Example2>() {
#Override
public void onResponse(Call<Example2> call, Response<Example2>
response) {
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Success",
Toast.LENGTH_LONG).show();
example2List = response.body();
weathers.addAll(Collections.singleton(example2List));
loadSetView();
dialogWeatherAdapter.updateList(weathers);
dialogWeatherAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<Example2> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Gagal " +
t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void loadSetView() {
txtCityCountry.setText(weathers.get(getId()).getCity().getName());
txtCurrentDate.setText(Util.formatDate(weathers
.get(getId()).getList().get(getId()).getDtTxt(), "EEE MMM dd, yyyy"));
weatherIcon.setImageResource(Util
.getDrawableResourceIdByName(getApplicationContext(),ICON_PREFIX + weathers
.get(getId()).getList().get(getId()).getWeather().get(getId()).getIcon()));
tvDescription.setText(weathers.get(getId()).getList().get(getId())
.getWeather().get(getId()).getDescription());
tvWindResult.setText("Wind : " +
weathers.get(getId()).getList().get(getId()).getWind().getSpeed() + " m/s");
double mTemperature = (double)
weathers.get(getId()).getList().get(getId()).getMain().getTemp();
tvTemperatureResult.setText(String.valueOf(weathers
.get(getId()).getList().get(ge
tId()).getMain().getTemp()) + " °C");
}
#Override
public void onResume() {
super.onResume();
ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = 700;
params.height = 1100;
getDialog().getWindow().setAttributes((WindowManager.LayoutParams)
params);
}
this My Adapter :
public class DialogWeatherAdapter extends
RecyclerView.Adapter<DialogWeatherAdapter.DialogViewHolder> {
ArrayList<Example2> data;
Context context;
Activity c;
public DialogWeatherAdapter(ArrayList<Example2> data, Context context,
Activity c) {
this.data = data;
this.context = context;
this.c = c;
}
public DialogWeatherAdapter(ArrayList<Example2> weathers) {
this.data = weathers;
}
#Override
public DialogViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
LayoutInflater layoutInflater = (LayoutInflater)
parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.item_weathers, parent,
false);
return new DialogViewHolder(view);
}
#Override
public void onBindViewHolder(DialogViewHolder holder, int position) {
if (holder instanceof DialogViewHolder) {
final DialogViewHolder viewHolder = (DialogViewHolder) holder;
if (data != null) {
for (int i = 0; i < data.size(); i++) {
viewHolder.tvCurrentDateItem.setText(Util.formatDate(data
.get(position).getList()
.get(position).getDtTxt(), "dd/MM"));
viewHolder.ivIconItem.setImageResource(Util
.getDrawableResourceIdByName(getApplicationContext(), ICON_PREFIX + data
.get(getId()).getList().get(getId()).getWeather().get(getId()).getIcon()));
viewHolder.tvDescriptionItem.setText(data.get(position)
.getList().get(position).getWeather().get(position).getDescription());
viewHolder.tvTemperatureItem.setText(String.valueOf(weathers
.get(getId()).getList
().get(getId()).getMain().getTemp()) + " °C");
}
}
}
}
#Override
public int getItemCount() {
return data.size();
}
public void updateList(ArrayList<Example2> weathers) {
this.data = weathers;
}
public class DialogViewHolder extends RecyclerView.ViewHolder {
TextView tvCurrentDateItem, tvDescriptionItem, tvTemperatureItem;
ImageView ivIconItem;
public DialogViewHolder(View itemView) {
super(itemView);
tvCurrentDateItem = itemView.findViewById(R.id.current_date_weather_item);
tvDescriptionItem = itemView.findViewById(R.id.description_item);
tvTemperatureItem = itemView.findViewById(R.id.temperature_item);
ivIconItem = itemView.findViewById(R.id.icon_weather_item);
}
}
}
enter image description here
The reason for this is -
The Item file (R.layout.item_weathers) has height match parent. Change it to wrap_content as shown -
<LinearLayout 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"/>
and it will show all the items.
I am using a listview with swipelayout (daimajia library) and my listview is scrolling...
My problem is when I swipe listview item and click on button in it ,it returns me wrong position..
Do you have any idea of how to solve this??
This is my adapter
public View generateView(final int position, final ViewGroup parent) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.ledger_layout, null);
SwipeLayout swipeLayout = (SwipeLayout) v.findViewById(getSwipeLayoutResourceId(position));
swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
}
});
swipeLayout.setOnDoubleClickListener(new
SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(context, "DoubleClick",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
I think your implementation of getView method is messy. Try this.
ListAdapter Java class.
package com.dev4solutions.myapplication.activities;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SimpleSwipeListener;
import com.daimajia.swipe.SwipeLayout;
import com.dev4solutions.myapplication.R;
import java.util.ArrayList;
class ListAdapter extends BaseAdapter {
private ArrayList<String> strings;
private Context mContext;
public ListAdapter(Context context, ArrayList<String> list) {
strings = list;
mContext = context;
}
#Override
public int getCount() {
return strings.size();
}
#Override
public Object getItem(int i) {
return strings.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.ledger_layout, null);
viewHolder = new ViewHolder();
viewHolder.swipeLayout = view.findViewById(R.id.swipe);
viewHolder.textView = view.findViewById(R.id.text_data);
viewHolder.delete = view.findViewById(R.id.delete);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.textView.setText(String.valueOf("Swipe Layout : " + position));
viewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
Toast.makeText(mContext, "onOpen : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "onDelete Click : " + position,
Toast.LENGTH_SHORT).show();
}
});
return view;
}
// view holder for managing to recycle of view
public static class ViewHolder {
SwipeLayout swipeLayout;
TextView textView;
View delete;
}
}
ledger_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
swipe:leftEdgeSwipeOffset="0dp"
swipe:rightEdgeSwipeOffset="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#FF5534"
android:gravity="center"
android:tag="Bottom3"
android:weightSum="10">
<ImageView
android:id="#+id/trash"
android:layout_width="27dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="#android:drawable/ic_delete" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="Delete Item?"
android:textColor="#fff"
android:textSize="17sp" />
<Button
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="4"
android:background="#ffffff"
android:text="Yes,Delete"
android:textColor="#FF5534" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cac6c6"
android:padding="10dp">
<TextView
android:id="#+id/position"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:tag="Hover"
android:text="Do not, for one repulse, forgo the purpose that you resolved to effort. " />
</LinearLayout>
</com.daimajia.swipe.SwipeLayout>
using the way which is marked as an answer will work but there is an another way of doing it too...
adapter class
public class testadapter1 extends RecyclerSwipeAdapter<testadapter1.SimpleViewHolder> {
public static final String TAG = testadapter1.class.getSimpleName();
private static SwipLayoutListener swipLayoutListener;
private static ClickListener clickListener;
String[] time;
Animation animSlide;
boolean ANIM_FLAG = true;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
private int visibleThreshold = 5;
private String phone;
private String email;
public static class SimpleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
SwipeLayout swipeLayout;
TextView text;
TextView info;
TextView swipeImage;
LinearLayout linearLayout;
ImageView imageView;
#Override
public void onClick(View view) {
clickListener.onItemClick(getAdapterPosition(), view);
Log.e("position", String.valueOf(getAdapterPosition()));
}
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
text = (TextView) itemView.findViewById(R.id.input_cname);
txtdate = (TextView) itemView.findViewById(R.id.date);
id = (TextView) itemView.findViewById(R.id.input_cid);
Typeface iconFont = FontManager.getTypeface(mContext, FontManager.FONTAWESOME);
FontManager.markAsIconContainer(itemView.findViewById(R.id.swipe), iconFont);
swipeImage = itemView.findViewById(R.id.swipeIcon);
imageView = new ImageView(mContext);
call = (TextView) itemView.findViewById(R.id.call_btn);
sms = (TextView) itemView.findViewById(R.id.sms_btn);
mail = (TextView) itemView.findViewById(R.id.email_btn);
info = (TextView) itemView.findViewById(R.id.detail_btn);
call.setTypeface(iconFont);
sms.setTypeface(iconFont);
mail.setTypeface(iconFont);
info.setTypeface(iconFont);
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, linearLayout);
itemView.setOnClickListener(this);
swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
if (swipLayoutListener != null) {
swipLayoutListener.onOpen(layout, getAdapterPosition());
}
}
});
}
}
private static Context mContext;
ArrayList<HashMap<String, String>> mDataset;
public testadapter1(Context mContext, ArrayList<HashMap<String, String>> objects, RecyclerView listView) {
this.mContext = mContext;
this.mDataset = objects;
if (listView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) listView
.getLayoutManager();
listView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView listView,
int dx, int dy) {
super.onScrolled(listView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ledger_layout, parent, false);
return new SimpleViewHolder(view);
}
public interface ClickListener {
void onItemClick(int position, View v);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
viewHolder.txtdate.setText(mDataset.get(position).get("date"));
viewHolder.id.setText("Amount: ₹ " + viewHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// HashMap<String, String> mDataset = getItem1(position);
Intent intent = new Intent(mContext, LedgerDetailActivity.class);
intent.putExtra("ledger_name", String.valueOf(mDataset.get(position).get("ledger_name")));
// Log.e("intent", mDataset.get("ledger_name"));
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
if (mDataset == null) {
Log.d(TAG, "getCount: 0");
return 0;
} else {
Log.d(TAG, "getCount: " + mDataset.size());
return mDataset.size();
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
public void addSwipeListener(SwipLayoutListener swipLayoutListener) {
testadapter1.swipLayoutListener = swipLayoutListener;
}
public interface SwipLayoutListener {
void onOpen(SwipeLayout layout, int position);
}
fragment layout
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/frame3"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/list_ledger"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"/>
<!-- Adding bottom sheet after main content -->
</android.support.v4.widget.SwipeRefreshLayout>
adapter layout
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
swipe:leftEdgeSwipeOffset="0dp"
swipe:rightEdgeSwipeOffset="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center"
android:weightSum="7">
<RelativeLayout
android:id="#+id/relativeLayoutSms"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/call_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_phone"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/call_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Call"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutCall"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/sms_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_sms"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sms_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="SMS"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutMail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/email_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_mail"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/email_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Email"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/detail_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_info"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/detail_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Details"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:id="#+id/input_cname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/date"
android:layout_marginEnd="5dp"
android:layout_toStartOf="#id/amount"
android:ellipsize="end"
android:maxLines="1"
android:textColor="#color/colorAccent"
android:textSize="16sp" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/input_cname"
android:layout_marginStart="10dp"
android:paddingTop="2dp"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/input_cid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginEnd="2dp"
android:layout_marginStart="10dp"
android:paddingEnd="5dp"
android:textAlignment="viewEnd"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/gp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignStart="#+id/input_cid"
android:layout_below="#+id/input_cname"
android:textAlignment="viewEnd"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="14sp"
android:visibility="gone" />
<TextView
android:id="#+id/swipeIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#id/gp"
android:layout_marginTop="14dp"
android:paddingStart="6dp"
android:visibility="gone" />
</RelativeLayout>
It's been a long time but I had the same issue. It took hours to solve the problem but the solution is here. This WARNING is from the daimajia's wiki.
ATTENTION: Never bind listeners or fill values in generateView. Just generate the view and do everything else in fillValues (e.g using your holder class) See issues #14 and #17
You can find detailed solution here : Solution to your position problem from daimajia's wiki
And sample code is like this :
//ATTENTION: Never bind listener or fill values in generateView.
// You have to do that in fillValues method.
#Override
public View generateView(int position, ViewGroup parent) {
return LayoutInflater.from(mContext).inflate(R.layout.grid_item, null);
}
#Override
public void fillValues(int position, View convertView) {
TextView t = (TextView)convertView.findViewById(R.id.position);
t.setText((position + 1 )+".");
}
You should do everything in fillValues() function. position value here is always right.
Just follow this rule and everything will be fine with your Swipe ListView.
In my Application I m having a RecyclerView in one of my Fragments in which I am getting response from a server using Reterofit. Every thing is fine but My RecylerView is not displaying any data returned from my service. Even the
int count = offerRecyclerAdapter.getItemCount();
of my adapter is returning the correct amount of data count returned from server.
Inside Fragment:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
offersRecyclerView = (RecyclerView) view.findViewById(R.id.offer_recycler);
MotorCityArabiaGlobal global = (MotorCityArabiaGlobal) getActivity().getApplication();
ApiInterface apiService=global.getClient().create(ApiInterface.class);
Call<OfferResponse> call = apiService.getOffers(4);
call.enqueue(new Callback<OfferResponse>() {
#Override
public void onResponse(Call<OfferResponse> call, Response<OfferResponse> response) {
OfferResponse offers = response.body();
if(offers!=null){
List<Offer> result = response.body().getResult();
offerRecyclerAdapter = new OffersAdapter(getActivity(),result);
offersRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
offersRecyclerView.setItemAnimator(new DefaultItemAnimator());
offersRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
offersRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
int count = offerRecyclerAdapter.getItemCount();
offerRecyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<OfferResponse> call, Throwable t) {
}
});
}
Adapter Class:
public class OffersAdapter extends RecyclerView.Adapter<OffersAdapter.MyViewHolder> {
private List<Offer> offersList= Collections.emptyList();
private LayoutInflater inflater;
Context ctx;
public OffersAdapter(Context ctx,List<Offer> offersList) {
this.ctx = ctx;
this.inflater = LayoutInflater.from(ctx);
this.offersList = offersList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent.getContext())
// .inflate(R.layout.offer_list_layout, parent, false);
View view = inflater.inflate(R.layout.offer_list_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Offer offer = offersList.get(position);
holder.title.setText(offer.getOffer_title());
holder.price.setText(offer.getPrice());
holder.offerCount.setText(offer.getOffer_count());
}
#Override
public int getItemCount() {
return offersList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, offerCount, price;
public ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
offerCount = (TextView) view.findViewById(R.id.offer_count);
price = (TextView) view.findViewById(R.id.price);
image = (ImageView)view.findViewById(R.id.car_img);
}
}
}
home_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/header_wrapper"
>
<!-- Row1-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<!-- Column1 row 1-->
<LinearLayout
android:layout_width="140dp"
android:layout_height="125dp"
android:layout_weight="1"
android:background="#drawable/new_car_selector"
android:clickable="true"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
></LinearLayout>
<!-- Column2 row 1-->
<LinearLayout
android:layout_width="140dp"
android:layout_height="125dp"
android:layout_weight="1"
android:background="#drawable/find_car_selector"
android:clickable="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
></LinearLayout>
</LinearLayout>
<!-- Row2-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
>
<!-- Column1 row 2-->
<!-- Column2 row 2-->
<LinearLayout
android:layout_width="140dp"
android:layout_height="125dp"
android:layout_weight="1"
android:background="#drawable/sell_car_selector"
android:clickable="true"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="10dp"
></LinearLayout>
<LinearLayout
android:layout_width="140dp"
android:layout_height="125dp"
android:layout_weight="1"
android:background="#drawable/compare_car_selector"
android:clickable="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"
></LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- Header Wrapper ends-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header_wrapper"
android:id="#+id/offers_recycler_wrapper"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CAR OFFERS"
android:textColor="#color/colorAccentDark"
android:textStyle="bold"
android:textSize="16sp"
android:layout_marginLeft="5dp"
/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/offer_recycler"
></android.support.v7.widget.RecyclerView>
</LinearLayout>
</RelativeLayout>
offer_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical"
android:paddingTop="6dp"
android:paddingBottom="5dp"
>
<ImageView
android:layout_width="80dp"
android:layout_height="60dp"
android:src="#drawable/sell_car_select"
android:id="#+id/car_img"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/meta_data"
android:orientation="vertical"
android:layout_toEndOf="#id/car_img"
android:layout_marginLeft="5dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TITLE"
android:textSize="16dp"
android:textColor="#000"
android:textStyle="bold"
android:id="#+id/title"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="3dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/price"
android:text="13,000"
android:textStyle="bold"
android:textColor="#color/colorAccentDark"
android:textSize="16dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/curr"
android:textColor="#BDBDBD"
android:text=" SAUDI RAYAL"
android:textSize="12dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/offer_count_wrapper"
android:orientation="horizontal"
android:layout_marginTop="3dp"
>
<ImageView
android:layout_width="12dp"
android:layout_height="12dp"
android:src="#drawable/ic_offer_orange"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12dp"
android:text=" 3 Offers"
android:id="#+id/offer_count"
/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
add the line below in your onResponse after offersRecyclerView.addItemDecoration();
offersRecyclerView.setAdapter(offerRecyclerAdapter);
hope this helps.
You did not set the adapter to the RecyclerView. Use setAdapter method. See the following code,
List<Offer> results = new ArrayList<Offer>();
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
offersRecyclerView = (RecyclerView) view.findViewById(R.id.offer_recycler);
offersRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
offersRecyclerView.setItemAnimator(new DefaultItemAnimator());
offersRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
offerRecyclerAdapter = new OffersAdapter(getActivity(), results)
offersRecyclerView.setAdapter(offerRecyclerAdapter);
offersRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
MotorCityArabiaGlobal global = (MotorCityArabiaGlobal) getActivity().getApplication();
ApiInterface apiService=global.getClient().create(ApiInterface.class);
Call<OfferResponse> call = apiService.getOffers(4);
call.enqueue(new Callback<OfferResponse>() {
#Override
public void onResponse(Call<OfferResponse> call, Response<OfferResponse> response) {
OfferResponse offers = response.body();
if(offers != null){
List<Offer> result = response.body().getResult();
results.clear();
results.addAll(result);
offerRecyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<OfferResponse> call, Throwable t) {
}
});
}
i have two adapters and a fragment, and i want to display feeds on two views, one bottom and one recycler view. Although the Json was working with a list adapter. its not working with the recycler view.
here is the main fragment
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardExpand;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.view.CardViewNative;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;
public class FeedFragmentAlternative extends Fragment{
private static final String TAG = FeedFragmentAlternative.class.getSimpleName();
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
private WaveSwipeRefreshLayout mWaveSwipeRefresh;
int duration = 200;
private List<FeedItem> FeedItems;
public static FeedFragmentAlternative newInstance(){
FeedFragmentAlternative feedFragmentAlternative = new FeedFragmentAlternative();
return feedFragmentAlternative;
}
private void refresh(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mWaveSwipeRefresh.setRefreshing(false);
}
},3000);
}
private ExpandablePager pager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.feed_activity_alternate, container, false);
final List<FeedItem> myFeedList = new ArrayList<>();
final FeedExpandableAdapter adapter = new FeedExpandableAdapter(myFeedList);
pager = (ExpandablePager) getActivity().findViewById(R.id.bottom_feed_container);
pager.setAdapter(adapter);
pager.setOnSliderStateChangeListener(new OnSliderStateChangeListener() {
#Override
public void onStateChanged(View page, int index, int state) {
toggleContent(page, state, duration);
}
#Override
public void onPageChanged(View page, int index, int state) {
toggleContent(page, state, 0);
}
});
final RecyclerView mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.feeds_list_recycler_view);
mRecyclerView.setHasFixedSize(true);
final FeedGridAdapter a = new FeedGridAdapter(myFeedList);
a.setListener(new OnItemClickedListener() {
#Override
public void onItemClicked(int index) {
pager.setCurrentItem(index, false);
pager.animateToState(ExpandablePager.STATE_EXPANDED);
}
});
mWaveSwipeRefresh = (WaveSwipeRefreshLayout)view.findViewById(R.id.feed_wave_swipe_layout_refresh_alternate);
mWaveSwipeRefresh.setColorSchemeColors(Color.WHITE, Color.GREEN);
mWaveSwipeRefresh.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
pager.setAdapter(adapter);
mRecyclerView.setAdapter(a);
FeedFragmentAlternative.newInstance();
refresh();
}
});
mWaveSwipeRefresh.setWaveColor(Color.parseColor("#80C5EFF7"));
mWaveSwipeRefresh.setMaxDropHeight((int)(mWaveSwipeRefresh.getHeight() * 0.9));
mRecyclerView.setAdapter(a);
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED);
if (entry != null){
try {
String data = new String (entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e){
e.printStackTrace();
}
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
} else {
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response:" + response.toString());
if (response != null){
parseJsonFeed(response);
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "ERROR:" + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonReq);
}
return view;
}
private void toggleContent(final View page, final int state, int duration){
final int headerHeight = (int) getResources().getDimension(R.dimen.header_height);
if (page != null){
ValueAnimator animator = state == ExpandablePager.STATE_EXPANDED ? ValueAnimator.ofFloat(1,0): ValueAnimator.ofFloat(0,1);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
page.findViewById(R.id.profile_name_header).setTranslationY(25 * (1 - ((Float) animation.getAnimatedValue())));
page.findViewById(R.id.profile_name_header).setTranslationX(-headerHeight * (1 - ((Float)animation.getAnimatedValue())));
page.findViewById(R.id.feed_time_stamp_header).setAlpha(((Float)animation.getAnimatedValue()));
page.findViewById(R.id.profile_pic_header_image).setAlpha(((Float)animation.getAnimatedValue()));
page.findViewById(R.id.feed_like_bottom_sheet).setAlpha(((Float) animation.getAnimatedValue()));
}
});
animator.setDuration((long)(duration * 5));
animator.setInterpolator(new FastOutSlowInInterpolator());
animator.start();
}
}
private void parseJsonFeed(JSONObject response){
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0;i < feedArray.length(); i++){
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
String image = feedObj.isNull("image")? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
String feedUrl = feedObj.isNull("url")? null : feedObj
.getString("url");
item.setUrl(feedUrl);
FeedItems.add(item);
}
} catch (JSONException e){
e.printStackTrace();
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initCards();
}
private void initCards(){
init_standard_header_with_expandcollapse_button();
}
private void init_standard_header_with_expandcollapse_button(){
Card card = new Card(getActivity());
CardHeader header = new CardHeader(getActivity());
header.setButtonExpandVisible(true);
card.addCardHeader(header);
CardExpand expand = new CardExpand(getActivity());
expand.setTitle("expanded");
CardViewNative cardViewNative = (CardViewNative) getActivity().findViewById(R.id.feed_card_style);
cardViewNative.setCard(card);
}
}
the grid adapter is as follows
public class FeedGridAdapter extends RecyclerView.Adapter<FeedGridAdapter.ViewHolder> {
private OnItemClickedListener listener;
private List<FeedItem> mFeedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public static class ViewHolder extends RecyclerView.ViewHolder{
public LoginTextView ProfileNameCell;
public LoginTextView FeedTimesStampCell;
public NetworkImageView ProfilepicCell;
public LoginTextView FeedStatusMgsCell;
public FeedImageView FeedImageViewCell;
public ViewGroup container;
public ViewHolder(RelativeLayout v){
super(v);
container = v;
ProfileNameCell = (LoginTextView) v.findViewById(R.id.client_name_alternate_cell);
FeedTimesStampCell = (LoginTextView) v.findViewById(R.id.time_stamp_alternate_cell);
ProfilepicCell = (NetworkImageView) v.findViewById(R.id.profile_pic_alternate_cell);
FeedStatusMgsCell = (LoginTextView) v.findViewById(R.id.txtStatusMgs_alternate);
FeedImageViewCell = (FeedImageView) v.findViewById(R.id.feedImage1_alternate);
}
}
public FeedGridAdapter(List<FeedItem> feedItems){mFeedItems = feedItems;}
#Override
public FeedGridAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RelativeLayout v = (RelativeLayout) LayoutInflater.from(parent.getContext())
.inflate(R.layout.feed_card_alternate, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.ProfileNameCell.setText(mFeedItems.get(position).getName());
CharSequence timeStampCell = DateUtils.getRelativeTimeSpanString(
Long.parseLong(mFeedItems.get(position).getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
holder.FeedTimesStampCell.setText(timeStampCell);
if (!TextUtils.isEmpty(mFeedItems.get(position).getStatus())){
holder.FeedStatusMgsCell.setText(mFeedItems.get(position).getStatus());
holder.FeedStatusMgsCell.setVisibility(View.VISIBLE);
} else {
holder.FeedStatusMgsCell.setVisibility(View.GONE);
}
holder.ProfilepicCell.setImageUrl(mFeedItems.get(position).getImge(), imageLoader);
if (mFeedItems.get(position).getImge() != null){
holder.FeedImageViewCell.setImageUrl(mFeedItems.get(position).getImge(), imageLoader);
holder.FeedImageViewCell.setVisibility(View.VISIBLE);
holder.FeedImageViewCell
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.FeedImageViewCell.setVisibility(View.GONE);
}
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClicked(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return mFeedItems.size();
}
public void setListener(OnItemClickedListener listener){this.listener = listener;}
}
and the expandable fragment is
public class FeedExpandableAdapter extends ExpandablePagerAdapter<FeedItem> {
public FeedExpandableAdapter(List<FeedItem> items){super(items);}
private LayoutInflater inflater;
private Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
#Override
public Object instantiateItem(ViewGroup container, int position) {
final ViewGroup rootView = (ViewGroup) LayoutInflater.from(container.getContext()).inflate(R.layout.feed_page_alternative, container, false);
if (inflater == null)
inflater = (LayoutInflater)activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
LoginTextView name = (LoginTextView) rootView.findViewById(R.id.profile_name_header);
LoginTextView timestamp = (LoginTextView) rootView.findViewById(R.id.feed_time_stamp_header);
NetworkImageView profilepic = (NetworkImageView) rootView.findViewById(R.id.profile_pic_header_image);
FeedImageView feedImageView = (FeedImageView) rootView.findViewById(R.id.feed_main_image_bottom_sheet);
LoginTextView statusMgs = (LoginTextView) rootView.findViewById(R.id.body_bottom_panel_feed);
name.setText(items.get(position).getName());
CharSequence timeofStamp = DateUtils.getRelativeTimeSpanString(
Long.parseLong(items.get(position).getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeofStamp);
if (!TextUtils.isEmpty(items.get(position).getStatus())){
statusMgs.setText(items.get(position).getStatus());
statusMgs.setVisibility(View.VISIBLE);
} else {
statusMgs.setVisibility(View.GONE);
}
profilepic.setImageUrl(items.get(position).getProfilePic(), imageLoader);
if (items.get(position).getImge() != null) {
feedImageView.setImageUrl(items.get(position).getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return attach(container, rootView, position);
}
}
the error shown is like this -
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.telenav.expandablepager.ExpandablePager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at com.evolustudios.askin.askin.src.fragments.FeedFragmentAlternative.onCreateView(FeedFragmentAlternative.java:86)
can anyone tell me why its returning null?
its possible duplicate, but i cannot figure out why its returning null
xml - feed_card_alternate
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="350dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<it.gmariotti.cardslib.library.view.CardViewNative
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/feed_card_style"
style="#style/card_external">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frame_list_card_item_alternate"
android:background="#drawable/cardpanel"
android:paddingTop="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:id="#+id/feed_top_panel_alternate"
android:paddingBottom="25dp">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/profile_pic_alternate_cell"
android:scaleType="fitCenter"
android:paddingTop="15dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingTop="15dp">
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/client_name_alternate_cell"
android:textSize="15dp"
android:textStyle="bold"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time_stamp_alternate_cell"
android:textColor="#color/timestamp"
android:textSize="13dp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/feed_other_content_alternate"
android:layout_below="#+id/feed_top_panel_alternate">
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtStatusMgs_alternate"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="13dp" />
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtUrl_alternate"
android:linksClickable="true"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textColor="#color/link" />
<com.evolustudios.askin.askin.src.Utils.FeedImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/feedImage1_alternate"
android:background="#80FFFFFF"
android:scaleType="fitXY"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
</FrameLayout>
</it.gmariotti.cardslib.library.view.CardViewNative>
feed_activity_alternate.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/feed_wave_swipe_layout_refresh_alternate">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/feeds_list_recycler_view"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:scrollbars="vertical"
tools:listitem="#layout/feed_item_list_new">
</android.support.v7.widget.RecyclerView>
<com.telenav.expandablepager.ExpandablePager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottom_feed_container"
android:layout_gravity="bottom"
app:animation_duration="200"
app:collapsed_height="#dimen/header_height"/>
</jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout>
feed_page_alternative
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/pumice">
<include
layout="#layout/feed_header_layout"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="250sp"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:paddingTop="10dp"
android:id="#+id/feed_bottom_panel_first_container">
<com.evolustudios.askin.askin.src.Utils.FeedImageView
android:layout_width="270sp"
android:layout_height="match_parent"
android:background="#color/edward"
android:id="#+id/feed_main_image_bottom_sheet"
android:scaleType="fitCenter"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:scrollbars="none">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/feed_extra_iamge_list_view_bootom_panel">
</ListView>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="#+id/feed_bottom_panel_second_container"
android:baselineAligned="false"
android:orientation="horizontal"
android:weightSum="5">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_sentiment_very_satisfied_black_24dp"
android:scaleType="fitCenter"
android:padding="5dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:src="#drawable/ic_sentiment_satisfied_black_24dp"
android:scaleType="fitCenter"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_sentiment_neutral_black_24dp"
android:scaleType="fitCenter"
android:padding="5dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_sentiment_dissatisfied_black_24dp"
android:scaleType="fitCenter"
android:padding="5dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_sentiment_very_dissatisfied_black_24dp"
android:scaleType="fitCenter"
android:padding="5dp"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/feed_bottom_panel_third_container"
android:baselineAligned="false"
android:orientation="horizontal"
android:weightSum="5">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/very_liked_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/liked_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/neutral_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/not_liked_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/very_not_liked_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:paddingLeft="22dp"
android:paddingRight="22dp"
android:paddingTop="15dp"
android:paddingBottom="15dp">
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/body_bottom_panel_feed"
android:text="Body"
android:textSize="20dp"/>
</ScrollView>
Change,
pager = (ExpandablePager) getActivity().findViewById(R.id.bottom_feed_container);
to
pager = (ExpandablePager) view.findViewById(R.id.bottom_feed_container);
Also change,
final RecyclerView mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.feeds_list_recycler_view);
to
final RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.feeds_list_recycler_view);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a fragment with a foldingcell view
here is the mainfragment -
public class FriendFragmentMain extends Fragment {
private static final String TAG = FriendFragmentMain.class.getSimpleName();
private FriendsCellListAdapter friendsCellListAdapter;
private List<FriendsItem> friendsItems;
private String URL_FRIEND="http://212.224.76.127/friends/friends.json";
private FragmentActivity fragmentActivity;
private Activity mActivity;
private ListView friendsListView;
public static FriendFragmentMain newInstance(){
FriendFragmentMain friendFragmentMain = new FriendFragmentMain();
return friendFragmentMain;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.friend_fragment_main, container, false);
friendsListView = (ListView) getActivity().findViewById(R.id.friend_super_list);
friendsItems = new ArrayList<>();
friendsCellListAdapter = new FriendsCellListAdapter(mActivity, friendsItems);
friendsListView.setAdapter(friendsCellListAdapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
((FoldingCell) view).toggle(false);
friendsCellListAdapter.registerToggle(pos);
}
});
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FRIEND);
if (entry != null){
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFriend(new JSONObject(data));
} catch (JSONException e){
e.printStackTrace();
}
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
} else {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
URL_FRIEND, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response:" + response.toString());
if (response != null) {
parseJsonFriend(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "ERROR:" + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
return view;
}
private void parseJsonFriend(JSONObject response){
try {
JSONArray friendArray = response.getJSONArray("friends");
for (int i =0; i < friendArray.length(); i++){
JSONObject friendObj = (JSONObject) friendArray.get(i);
FriendsItem item = new FriendsItem();
item.setId(friendObj.getInt("id"));
item.setName(friendObj.getString("name"));
item.setProfilePic(friendObj.getString("profilePic"));
item.setBackgroundImage(friendObj.getString("backgroundImage"));
item.setStatus(friendObj.getString("status"));
item.setWork(friendObj.getString("work"));
item.setLocation(friendObj.getString("location"));
String friendUrl = friendObj.isNull("website")? null : friendObj
.getString("website");
item.setWebsite(friendUrl);
friendsItems.add(item);
}
friendsCellListAdapter.notifyDataSetChanged();
} catch (JSONException e){
e.printStackTrace();
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
}
the base adapter looks like this -
public class FriendsCellListAdapter extends BaseAdapter{
private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultMessageButton;
private View.OnClickListener defaultViewProfileButton;
private Activity activity;
private Context context;
private LayoutInflater inflater;
private List<FriendsItem> friendsItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FriendsCellListAdapter(Activity activity, List<FriendsItem> friendsItems){
this.activity = activity;
this.friendsItems = friendsItems;
}
#Override
public int getCount() {
return friendsItems.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return friendsItems.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
if (inflater==null)
inflater = (LayoutInflater)activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
FriendsItem item = friendsItems.get(position);
FoldingCell cell = (FoldingCell) convertView;
ViewHolder viewHoler;
if (cell == null){
viewHoler = new ViewHolder();
cell = (FoldingCell) inflater.inflate(R.layout.friends_cell, parent, false);
viewHoler.profilePic = (NetworkImageView) cell.findViewById(R.id.friends_profile_pic);
viewHoler.clientName = (LoginTextView) cell.findViewById(R.id.client_name);
viewHoler.friendStatus = (LoginTextView) cell.findViewById(R.id.friend_status);
viewHoler.backgroundImage = (NetworkImageView) cell.findViewById(R.id.friend_background_image);
viewHoler.friendAvatar = (NetworkImageView) cell.findViewById(R.id.friends_avatar);
viewHoler.friendName = (LoginTextView) cell.findViewById(R.id.friend_name);
viewHoler.friendLocation = (LoginTextView) cell.findViewById(R.id.friend_location);
viewHoler.friendURL = (LoginTextView) cell.findViewById(R.id.friend_url);
viewHoler.friendWork = (LoginTextView) cell.findViewById(R.id.friend_work);
cell.setTag(viewHoler);
} else {
if (unfoldedIndexes.contains(position)){
cell.unfold(true);
} else {
cell.fold(true);
}
viewHoler = (ViewHolder) cell.getTag();
}
viewHoler.clientName.setText(item.getName());
viewHoler.friendName.setText(item.getName());
//chech for empty status
if (!TextUtils.isEmpty(item.getStatus())){
viewHoler.friendStatus.setText(item.getStatus());
viewHoler.friendStatus.setVisibility(View.VISIBLE);
} else {
viewHoler.friendStatus.setVisibility(View.GONE);
}
//check for empty location
if (!TextUtils.isEmpty(item.getLocation())){
viewHoler.friendLocation.setText(item.getLocation());
viewHoler.friendLocation.setVisibility(View.VISIBLE);
} else {
viewHoler.friendLocation.setVisibility(View.GONE);
}
//check for null url
if (item.getWebsite() != null){
viewHoler.friendURL.setText(Html.fromHtml("" + item.getWebsite()+""));
viewHoler.friendURL.setMovementMethod(LinkMovementMethod.getInstance());
viewHoler.friendURL.setVisibility(View.VISIBLE);
} else {
viewHoler.friendURL.setVisibility(View.GONE);
}
//check for empty work
if (!TextUtils.isEmpty(item.getWork())){
viewHoler.friendWork.setText(item.getWork());
viewHoler.friendWork.setVisibility(View.VISIBLE);
}else {
viewHoler.friendWork.setVisibility(View.GONE);
}
//profile pic
viewHoler.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
viewHoler.friendAvatar.setImageUrl(item.getProfilePic(), imageLoader);
//background image
viewHoler.backgroundImage.setImageUrl(item.getBackgroundImage(), imageLoader);
return convertView;
}
public void registerToggle(int position){
if (unfoldedIndexes.contains(position))
registerFold(position);
else
registerUnfold(position);
}
public void registerFold(int position){unfoldedIndexes.remove(position);}
public void registerUnfold(int position){
unfoldedIndexes.add(position);
}
private class ViewHolder{
NetworkImageView profilePic;
LoginTextView clientName;
LoginTextView friendStatus;
NetworkImageView backgroundImage;
NetworkImageView friendAvatar;
LoginTextView friendName;
LoginTextView friendLocation;
LoginTextView friendURL;
LoginTextView friendWork;
}
}
now when i run it it throws -
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.evolustudios.askin.askin.src.fragments.FriendFragmentMain.onCreateView(FriendFragmentMain.java:60)
this error. i am unable to find out why its throwing a null object? can anyone throw a light on why its showing null object.
the views are here- friends_cell
<com.ramotion.foldingcell.FoldingCell xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
xmlns:folding-cell="http://schemas.android.com/apk/res-auto"
folding-cell:additionalFlipsCount="2"
folding-cell:animationDuration="1300"
folding-cell:backSideColor="#color/bgBackSideColor">
<include layout="#layout/friends_content_layout"/>
<include layout="#layout/friends_cell_title_layout"/>
</com.ramotion.foldingcell.FoldingCell>
friends_cell_title_layout -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false">
<!--LEFT Part -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="155dp"
android:layout_weight="3"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="20dp"
android:background="#color/feed_item_border">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/friends_profile_pic"
android:scaleType="fitCenter"/>
</RelativeLayout>
<!--RIGHT Part-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingBottom="20dp"
android:paddingEnd="20dp"
android:paddingStart="15dp"
android:paddingTop="20dp"
android:background="#color/feed_item_border">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/title_from_to_dots"
android:layout_marginEnd="10dp"
android:src="#drawable/from_to_purple"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/client_name"
android:layout_alignTop="#+id/title_from_to_dots"
android:layout_marginTop="-5dp"
android:layout_toEndOf="#+id/title_from_to_dots"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:singleLine="true"
android:textColor="#android:color/holo_blue_dark"
android:textSize="16sp"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="1dp"
android:id="#+id/friend_profile_divider"
android:layout_below="#+id/client_name"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toEndOf="#+id/title_from_to_dots"
android:src="#color/contentDividerLine"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friend_status"
android:layout_below="#+id/friend_profile_divider"
android:layout_toEndOf="#+id/title_from_to_dots"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:singleLine="true"
android:textColor="#android:color/holo_blue_dark"
android:textSize="16sp"/>
</RelativeLayout>
and friend_content_layout -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone">
<!--Content header line-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/text_password"
android:paddingBottom="7dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="7dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:src="#drawable/menu_icon"/>
</RelativeLayout>
<!--Content header Image-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/friend_background_image"
android:scaleType="centerCrop"/>
</RelativeLayout>
<!--Content body layout-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="6dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="9dp">
<!--avatar and name-->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friends_avatar"
android:layout_alignParentStart="true"
android:layout_marginBottom="5dp"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friend_name"
android:layout_alignTop="#+id/friends_avatar"
android:layout_marginBottom="2dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#+id/friends_avatar"
android:textColor="#color/mainTextColor"
android:textSize="18sp"
android:textStyle="bold"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friend_location"
android:layout_alignStart="#+id/friend_name"
android:layout_marginBottom="-2dp"
android:layout_marginStart="3dp"
android:layout_below="#+id/friend_name"
android:textColor="#a9a9a9"
android:textSize="12sp"/>
</RelativeLayout>
<!--Divider Line-->
<ImageView
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginBottom="6dp"
android:layout_marginTop="9dp"
android:src="#color/contentDividerLine"/>
<!--Address Part-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/url_badge"
android:textColor="#a9a9a9"
android:layout_alignParentStart="true"
android:text="WEBSITE"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friend_url"
android:layout_alignStart="#+id/url_badge"
android:layout_below="#+id/url_badge"
android:textColor="#color/mainTextColor"
android:textSize="18sp"
android:textStyle="bold"/>
</RelativeLayout>
</LinearLayout>
<!--Divider Line-->
<ImageView
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginBottom="6dp"
android:layout_marginTop="7dp"
android:src="#color/contentDividerLine"/>
<!--Work Part-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/work_badge"
android:textColor="#a9a9a9"
android:layout_alignParentStart="true"
android:text="WORK"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friend_work"
android:layout_alignStart="#+id/work_badge"
android:layout_below="#+id/work_badge"
android:textColor="#color/mainTextColor"
android:textSize="18sp"
android:textStyle="bold"/>
</RelativeLayout>
</LinearLayout>
<!--Buttons-->
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/friend_send_message"
android:layout_marginTop="16dp"
android:background="#color/btnRequest"
android:padding="10dp"
android:text="Send Message"
android:textAlignment="center"
android:textColor="#color/mainTextColor"
android:textSize="20sp"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/friend_view_profile"
android:layout_marginTop="16dp"
android:background="#color/btnRequest"
android:padding="10dp"
android:text="View Profile"
android:textAlignment="center"
android:textColor="#color/mainTextColor"
android:textSize="20sp"/>
</LinearLayout>
</LinearLayout>
Initialize friendsItems before passing it to friendsCellListAdapter
friendsItems = new ArrayList<FriendsItem>(); // add this line
friendsCellListAdapter = new FriendsCellListAdapter(mActivity, friendsItems);
friendsListView.setAdapter(friendsCellListAdapter);