Empty View on a dynamic RecyclerView - android

I am retrieving Data from MySQL Database in Android and I am using Recyclerview .I test php file and it is working fine but nothing shows in the activity. I checked every thing and it seems fine, I don't know what is the problem ?
Waiting Activity :
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="1dp"
android:layout_height="1dp"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="51dp" />
</RelativeLayout>
list_layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/imageView"
android:layout_width="120dp"
android:layout_height="90dp"
android:padding="4dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:text=" Waiting Time :"
android:textColor="#000000"
android:textStyle="bold"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"/>
<TextView
android:id="#+id/textViewTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/imageView"
android:text="00"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textViewRating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewTime"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/imageView"
android:background="#color/colorPrimary"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="Bus Number : "
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewBusNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textViewRating"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/imageView"
android:text="255"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large" />
</RelativeLayout>
</LinearLayout>
WaitingActivity :
public class WaitingActivity extends AppCompatActivity {
private static final String URL_PRODUCTS = "http://192.168.1.2/Android/v1/test1.php";
List<Product> productList;
RecyclerView recyclerView;
ProductsAdapter adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waiting);
recyclerView = (RecyclerView) findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void loadProducts() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for (int i = 0; i < products.length(); i++) {
JSONObject productObject = products.getJSONObject(i);
int Temp_dt = productObject.getInt("Temp_dt");
int BusNumber =productObject.getInt("BusNumber");
Product product = new Product(Temp_dt, BusNumber);
productList.add(product);
}
adapter = new ProductsAdapter(WaitingActivity.this, productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(WaitingActivity.this, error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
Product class :
public class Product {
private int Temp_dt;
private int BusNumber;
public Product(int Temp_dt, int BusNumber) {
this.Temp_dt = Temp_dt;
this.BusNumber = BusNumber ;
}
public int getWaitingTime() {
return Temp_dt;
}
public int getBusNumber() {
return BusNumber ;
}
}
ProductAdapter :
public class ProductsAdapter extends
RecyclerView.Adapter<ProductsAdapter.ProductViewHolder> {
private Context mCtx;
private List<Product> productList;
public ProductsAdapter(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.list_layout, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
Product product = productList.get(position);
holder.textViewTime.setText(String.valueOf(product.getWaitingTime()));
holder.textViewBusNumber.setText(String.valueOf(product.getBusNumber()));
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textViewTime;
TextView textViewBusNumber;
public ProductViewHolder(View itemView) {
super(itemView);
textViewTime = itemView.findViewById(R.id.textViewTime);
textViewBusNumber = itemView.findViewById(R.id.textViewBusNumber);
}
}
}
I expect to show temp_dt and waiting time from php file but the actual output is nothing just empty activity.

Related

I am trying to display data from server to Recycler View but getting error

I have made a recyclerview and populating it with data from server with volley, but this error keep coming back, I have tried all the solutions available but it won't work. Some help will be really appreciated.
I am using MySQL database my api for getting data from database is working fine, but recyclerview is giving this error
"android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText"
Data Class:
public class bus_data {
private int id;
private String bus_number;
private String bus_total_seats;
private String bus_available_seats;
private String bus_route;
private String bus_leaving_time;
private String bus_reaching_time;
private String bus_driver_name;
private String bus_ticketchecker_name;
private String bus_rating;
private String bus_break_time;
private String bus_company;
public bus_data(int id,String bus_number,String bus_total_seats,String bus_available_seats,
String bus_route,String bus_leaving_time,String bus_reaching_time,
String bus_driver_name,String bus_ticketchecker_name,String bus_rating,String bus_break_time,String bus_company) {
this.id = id;
this.bus_number = bus_number;
this.bus_total_seats = bus_total_seats;
this.bus_available_seats = bus_available_seats;
this.bus_route = bus_route;
this.bus_leaving_time = bus_leaving_time;
this.bus_reaching_time = bus_reaching_time;
this.bus_driver_name = bus_driver_name;
this.bus_ticketchecker_name = bus_ticketchecker_name;
this.bus_rating = bus_rating;
this.bus_break_time = bus_break_time;
this.bus_company = bus_company;
}
public int getId() {
return id;
}
public String getbus_number() {
return bus_number;
}
public String getbus_total_seats() {
return bus_total_seats;
}
public String getbus_available_seats() {
return bus_available_seats;
}
public String getbus_route() {
return bus_route;
}
public String getbus_leaving_time() {
return bus_leaving_time;
}
public String getbus_reaching_time() {
return bus_reaching_time;
}
public String getbus_driver_name() {
return bus_driver_name;
}
public String getbus_ticketchecker_name() {
return bus_ticketchecker_name;
}
public String getbus_rating() {
return bus_rating;
}
public String getbus_break_time() {
return bus_break_time;
}
public String getbus_company() {
return bus_company;
}
}
Adapter Class:
public class adapter_class extends RecyclerView.Adapter<adapter_class.bus_dataViewHolder> {
private Context mCtx;
private List<bus_data> productList;
public adapter_class(Context mCtx, List<bus_data> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public bus_dataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.bus_detail_list, null);
return new bus_dataViewHolder(view);
}
#Override
public void onBindViewHolder(bus_dataViewHolder holder, int position) {
bus_data busDetail = productList.get(position);
//loading the image
holder.bus_number.setText(busDetail.getbus_number());
holder.total_seats.setText(busDetail.getbus_total_seats());
holder.available_seats.setText(String.valueOf(busDetail.getbus_available_seats()));
holder.bus_route.setText(String.valueOf(busDetail.getbus_route()));
holder.bus_leaving_time.setText(String.valueOf(busDetail.getbus_leaving_time()));
holder.bus_reaching_time.setText(String.valueOf(busDetail.getbus_reaching_time()));
holder.bus_driver_name.setText(String.valueOf(busDetail.getbus_driver_name()));
holder.bus_ticketchecker_name.setText(String.valueOf(busDetail.getbus_ticketchecker_name()));
holder.bus_rating.setText(String.valueOf(busDetail.getbus_rating()));
holder.bus_break_time.setText(String.valueOf(busDetail.getbus_break_time()));
holder.bus_company.setText(String.valueOf(busDetail.getbus_company()));
}
#Override
public int getItemCount() {
return productList.size();
}
class bus_dataViewHolder extends RecyclerView.ViewHolder {
EditText bus_number, total_seats, available_seats, bus_route, bus_leaving_time, bus_reaching_time,
bus_driver_name, bus_ticketchecker_name, bus_rating, bus_break_time, bus_company;
public bus_dataViewHolder(View itemView) {
super(itemView);
bus_number = itemView.findViewById(R.id.bus_number);
total_seats = itemView.findViewById(R.id.total_seats);
available_seats = itemView.findViewById(R.id.available_seats);
bus_route = itemView.findViewById(R.id.route);
bus_leaving_time = itemView.findViewById(R.id.leaving_time);
bus_reaching_time = itemView.findViewById(R.id.reaching_time);
bus_driver_name = itemView.findViewById(R.id.driver_name);
bus_ticketchecker_name = itemView.findViewById(R.id.tk_checker_name);
bus_rating = itemView.findViewById(R.id.rating);
bus_break_time = itemView.findViewById(R.id.break_time);
bus_company = itemView.findViewById(R.id.bus_company);
}
}
}
Main Class:
public class Bus_Details extends AppCompatActivity {
private static final String URL_PRODUCTS = "http://192.168.10.17/AutoBus/api.php";
//a list to store all the products
List<bus_data> productList;
//the recyclerview
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bus_details);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout);
recyclerView = findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject data = array.getJSONObject(i);
//adding the product to product list
productList.add(new bus_data(
data.getInt("id"),
data.getString("bus_number"),
data.getString("bus_total_seats"),
data.getString("bus_available_seats"),
data.getString("bus_route"),
data.getString("bus_leaving_time"),
data.getString("bus_reaching_time"),
data.getString("bus_driver_name"),
data.getString("bus_ticketchecker_name"),
data.getString("bus_rating"),
data.getString("bus_break_time"),
data.getString("bus_company")
));
}
//creating adapter object and setting it to recyclerview
adapter_class adapter = new adapter_class(Bus_Details.this, productList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(Bus_Details.this, "Error"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Bus_Details.this, "Error"+error.toString(), Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
}
Here are the layout files.
recycler_activity:
<RelativeLayout 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"
tools:context=".Passenger.Bus_Details">
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="-51dp" />
</RelativeLayout>
List_activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:id="#+id/layout">
<TextView
android:id="#+id/bus_company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Daewo"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#ffffff" />
<TextView
android:id="#+id/bus_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/bus_company"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="GJN-1234"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small" />
<TextView
android:id="#+id/total_seats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/bus_number"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:background="#color/colorPrimary"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="70"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/available_seats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/total_seats"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/leaving_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/available_seats"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/reaching_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/leaving_time"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/driver_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/reaching_time"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/tk_checker_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/driver_name"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/break_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tk_checker_name"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/break_time"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/route"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/rating"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="50"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
This is the error I am getting
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.autobus, PID: 10266
java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText
Screenshot of error:
In your bus_dataViewHolder class replace EditText to TextView.
because in layout you can use TextView and inside the program you use Edittext, that's while this issue generated.
This issue is because you take TextView in your adapter xml and get it like as a EditText.
So change in your adapter onCreateViewHolder from EditText to TextView .
Change below line in your adapter class.
TextView bus_number, total_seats, available_seats, bus_route, bus_leaving_time, bus_reaching_time,
bus_driver_name, bus_ticketchecker_name, bus_rating, bus_break_time, bus_company;

RecyclerView does not show list of objects

I tried the solutions on the other similar posts that I found here but they did not help me. I hope someone can help.
I get data from Unsplash's API and the ArrayList contains 10 items once I get a response, that's why I think It has to be something with the way the view is inflated.
This is code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "unsplash";
private final String CLIENT_ID = "...myclientID...";
// testing keyword used on the API to search for pictures
private final String KEYWORD = "stackOverflow";
private final String urlBase = "https://api.unsplash.com/";
private Retrofit retrofit;
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder()
.baseUrl(urlBase)
.addConverterFactory(GsonConverterFactory.create())
.build();
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerViewAdapter = new RecyclerViewAdapter();
recyclerView.setAdapter(recyclerViewAdapter);
getData();
}
private void getData() {
PictureService service = retrofit.create(PictureService.class);
Call<PictureResponse> pictureResponseCall = service.getPictureList(KEYWORD, CLIENT_ID);
pictureResponseCall.enqueue(new Callback<PictureResponse>() {
#Override
public void onResponse(Call<PictureResponse> call, Response<PictureResponse> response) {
if (response.isSuccessful()){
PictureResponse pictureResponse = response.body();
ArrayList<UnsplashPic> pictureList = pictureResponse.getResults();
recyclerViewAdapter.addPictures(pictureList);
}else{
Log.e (TAG, " onResponse " + response.errorBody());
}
}
#Override
public void onFailure(Call<PictureResponse> call, Throwable t) {
Log.e (TAG, " onFailure " + t.getMessage());
}
});
}
}
My adapter class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UnsplashPic> pictureList;
public RecyclerViewAdapter (){
pictureList = new ArrayList<>();
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_view_holder, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
UnsplashPic pic = pictureList.get(i);
viewHolder.artistName.setText(pic.user.getUsername());
viewHolder.unsplash.setText("Unsplash");
}
#Override
public int getItemCount() {
return pictureList.size();
}
public void addPictures(ArrayList<UnsplashPic> pictureList) {
pictureList.addAll(pictureList);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView artistName;
private TextView unsplash;
public ViewHolder (View itemView){
super(itemView);
imageView = itemView.findViewById(R.id.imageview);
artistName = itemView.findViewById(R.id.artist_name);
unsplash = itemView.findViewById(R.id.unsplash_name);
}
}
}
item_view_holder.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#ababab"
android:contentDescription="unsplash picture" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Photo by "/>
<TextView
android:id="#+id/artist_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="on "/>
<TextView
android:id="#+id/unsplash_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true" />
</LinearLayout>
activity_main.xml
<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:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Search for pictures"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Here:
public void addPictures(ArrayList<UnsplashPic> pictureList) {
pictureList.addAll(pictureList);
notifyDataSetChanged();
}
you are actually adding the content of the pictureList you send as parameter of the function to that same list, your list from adapter is not updated.
You should do like this instead:
public void addPictures(ArrayList<UnsplashPic> pictureList) {
this.pictureList.addAll(pictureList);
notifyDataSetChanged();
}

Unable to display fetch data from MYSQL database in custom gridview in android

In my app I use grid view to display data. grid view is in a fragment.I already retrieve data from mysql database in Log cat but that json data not display in custom grid.
activity_product_list.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".DrawerActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/header2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PRODUCTS : -"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/blue"/>
<GridView
android:id="#+id/productlist"
android:layout_below="#+id/header2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:horizontalSpacing="2dp"
android:layout_marginTop="#dimen/activity_horizontal_margin">
</GridView>
</RelativeLayout>
ProductListFragment.java
public class ProductListFragment extends Fragment {
List<Product> productList;
GridView gridView;
CustomProductList customProductList;
int categoryid;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_product_list, container,false);
gridView = (GridView) rootView.findViewById(R.id.productlist);
final GlobalVariable ID = (GlobalVariable)getActivity().getApplication();
categoryid = ID.getCategoryid();
productList = new ArrayList<>();
loadProduct();
customProductList = new CustomProductList(getActivity(),productList);
gridView.setAdapter(customProductList);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void loadProduct() {
String PRODUCT_URL = "http://192.168.0.101/cart/product/get_all_product.php?vcategoryid="+categoryid;
StringRequest stringRequest= new StringRequest(Request.Method.GET, PRODUCT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("products");
for (int i = 0; i < array.length(); i++){
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
Product product = new Product();
product.setProductid(userJson.getInt("productid"));
product.setProductName(userJson.getString("productname"));
product.setProductDesc(userJson.getString("productdesc"));
product.setPrice(userJson.getString("productprice"));
productList.add(product);
Log.e("product",userJson+"");
}
customProductList.notifyDataSetChanged();
Log.e("product",customProductList+"");
//customCategoryList = new CustomCategoryList(getActivity(),categoryList);
//recyclerView.setAdapter(customCategoryList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
}
custom_product_list.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/home_appliances"/>
<TextView
android:id="#+id/productName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Redmi"
android:textStyle="bold"
android:textColor="#color/black"
android:textSize="22sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RS."
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9999"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/blue"
android:layout_marginLeft="10dp"/>
</LinearLayout>
CustomProductList.java
public class CustomProductList extends BaseAdapter {
private Context mCtx;
private List<Product> productList;
public CustomProductList(Context mCtx, List<Product> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mCtx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(mCtx);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.custom_product_list, null);
TextView productname = (TextView) gridView.findViewById(R.id.productName);
TextView price = (TextView) gridView.findViewById(R.id.price);
// getting data for the row
Product product = productList.get(position);
// set data
productname.setText(product.getProductName());
price.setText(product.getPrice());
} else {
gridView = (View) convertView;
}
return gridView;
}
}
This is my code.All data comes from database in logcat as json..But All not display in grid.Please help me.Tell me What is the problem.
Solution:
You forgot to get count the updated list, hence chenge the below code:
#Override
public int getCount() {
return 0;
}
to this:
#Override
public int getCount() {
return this.productList.size();
}
That's it. Hope it helps.

Android RecyclerView Adapter

what's the Wrong
this code for chat application .. messages not shown and ProgressDialog still in the screen
Adapter class
public class chatadaptor extends RecyclerView.Adapter<chatadaptor.MyViewHolder>{
private Context mContext;
private List<Message> messageList;
public chatadaptor(Context mContext, List<Message> messageList) {
this.mContext = mContext;
this.messageList = messageList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tv_time , tv_message_content;
RadioButton statusradiobutton ;
LinearLayout Rsenttext ,Rresecivedtext;
ImageView img_msg;
RelativeLayout Rsentpic ,Rresecivedp ;
public MyViewHolder(View view) {
super(view);
tv_time = (TextView) view.findViewById(R.id.tv_time);
tv_message_content = (TextView) view.findViewById(R.id.tv_message_content);
Rsenttext = (LinearLayout)view.findViewById(R.id.Rsenttext);
Rresecivedtext = (LinearLayout)view.findViewById(R.id.Rresecivedtext);
Rsentpic = (RelativeLayout)view.findViewById(R.id.Rsentpic);
Rresecivedp = (RelativeLayout)view.findViewById(R.id.Rresecivedp);
img_msg = (ImageView)view.findViewById(R.id.img_msg);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.chatting,parent,false);
MyViewHolder holder = new MyViewHolder(row);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Message message = messageList.get(position);
holder.Rresecivedtext.setVisibility(View.VISIBLE);
holder.tv_message_content.setText(message.getContent());
Toast.makeText(mContext,message.getDegree() , Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return messageList.size();
}
}
Xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:id="#+id/Rresecivedtext"
android:orientation="vertical">
<TextView
android:id="#+id/tv_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_marginTop="2dp"
android:gravity="start"
android:paddingEnd="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/app_name"
android:textColor="#color/colorPrimaryDark"
android:textSize="11sp" />
<FrameLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_username"
android:layout_gravity="start"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/received_message">
<TextView
android:id="#+id/tv_message_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="3dp"
android:gravity="center"
android:minWidth="60dp"
android:text=" مرحبا "
android:textColor="#color/album_title" />
</FrameLayout>
<TextView
android:id="#+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/container"
android:layout_alignRight="#id/container"
android:layout_below="#+id/container"
android:layout_marginBottom="4dp"
android:layout_marginTop="1dp"
android:gravity="end"
android:paddingLeft="10dp"
android:text="12:20 AM"
android:textColor="#color/colorPrimary"
android:textSize="11sp" />
</RelativeLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/Rsenttext"
android:visibility="v"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_marginTop="2dp"
android:gravity="end"
android:paddingRight="10dp"
android:text="12:20 AM"
android:textSize="11sp" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:background="#drawable/sent_message">
<TextView
android:id="#+id/tv_message_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="2dp"
android:gravity="center"
android:minWidth="60dp"
android:text=" message text "
android:textColor="#color/white" />
</FrameLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
And Activity
public void getMessages(){
progress=new ProgressDialog(this);
progress.setMessage(getResources().getString(R.string.wait));
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setCancelable(true);
progress.show();
final Thread t = new Thread() {
#Override
public void run() {
String ADD_TOKEN_URL = "http://XXXXXXXXX/api/Chat.php";
StringRequest request = new StringRequest(Request.Method.POST, ADD_TOKEN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("1000")) {
Toast.makeText(userchats.this, "user error", Toast.LENGTH_SHORT).show();
progress.dismiss();
}else if (response.trim().equals("1111")){
Toast.makeText(userchats.this, "sending error", Toast.LENGTH_SHORT).show();
progress.dismiss();}
else {
response = response.substring(response.indexOf('\n')+1);
try {
String encodedstring = URLEncoder.encode(response, "ISO-8859-1");
response = URLDecoder.decode(encodedstring, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
try {
List<Message> messageList = new ArrayList<>();
Message message;
JSONObject object = new JSONObject(response);
JSONArray apparray = object.getJSONArray("chat");
for (int i = 0; i < apparray.length(); i++) {
JSONObject currentobject = apparray.getJSONObject(i);
String type = currentobject.getString("type");
String content = currentobject.getString("content");
String timestamp = currentobject.getString("timestamp");
String degree = currentobject.getString("degree");
SharedPreferences pref = getSharedPreferences("MyAccount", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
String Uid = pref.getString("Uid", null); // getting String
message = new Message( Uid, type, content, timestamp, degree);
messageList.add(message);
chatadaptor adapter = new chatadaptor(userchats.this , messageList);
recyclerChat.setAdapter(adapter);
}
// progress.dismiss();
} catch (JSONException e) {
e.printStackTrace();
} }
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(userchats.this, "error in sending message", Toast.LENGTH_SHORT).show(); progress.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
SharedPreferences pref = getSharedPreferences("MyAccount", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
String Uid = pref.getString("Uid", null); // getting String
params.put("action","view");
params.put("userid",Uid);
//params.put("type",lpasss);
// params.put("content",lpasss);
// params.put("timestamp",lpasss);
return params;
}
};
Volley.newRequestQueue(getBaseContext()).add(request);
}
};
t.start();
}
data come from serve and converted to JSONObject enter code here correctly
what's the Wrong
this code for chat application .. messages not shown and ProgressDialog still in the screen
just add following lines because you did not add layout manager for your recyclerview
recyclerChat.setLayoutManager(new LinearLayoutManager(this));
hope this works for you..
public class ServicesListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context con;
AtmHolder pvh1;
List<serviceListData> serviceslist;
public ServicesListAdapter(List<serviceListData> serviceslist, Context con) {
this.serviceslist = serviceslist;
this.con = con;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
RecyclerView.ViewHolder viewHolder = null;
if (position == 0) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.services_list_item_style, viewGroup, false);
viewHolder = new AtmHolder(v);
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof AtmHolder) {
pvh1 = (AtmHolder) holder;
pvh1.tv_service.setText(serviceslist.get(position).getName());
Glide.with(con)
.load("image url")
.placeholder(R.drawable.internet)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(pvh1.iv_service);
}
}
public int getItemViewType(int position) {
int a = 0;
return a;
}
#Override
public int getItemCount() {
return serviceslist.size();
}
public static class AtmHolder extends RecyclerView.ViewHolder {
ImageView iv_service;
TextView tv_service;
AtmHolder(View itemView) {
super(itemView);
iv_service = (ImageView) itemView.findViewById(R.id.iv_service);
tv_service = (TextView) itemView.findViewById(R.id.tv_service);
}
}
}

CardView in RecyclerView not inflating with all the values in list

I have a recyclerview that contains the cardview.The data is coming from server and is populated in a list. The Cardview adapter is not inflating the 2nd value from the list. The activity shows only one value on the screen:
This is the cardview screen
Following is the code for Recycler view layout file:
<?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="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:scrollbars="vertical"
tools:context="com.appshaala.vorkal.app.ViewWorkerList">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Following is the code for worker_card layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:card_view="http://schemas.android.com/tools"
android:padding="16dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/WorkerCV"
app:cardBackgroundColor="#color/colorPrimaryDark"
android:elevation="5dp"
card_view:cardCornerRadius="#dimen/card_album_radius">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="6dp"
>
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip" >
<ImageView
android:id="#+id/pic"
android:layout_width="96dp"
android:layout_height="96dp"
android:src="#drawable/cover"
android:contentDescription="Worker pic" />
</LinearLayout>
<TextView
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Raja"
android:textSize="35sp"
android:foregroundGravity="center"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/Wrating"
android:layout_alignStart="#+id/Wrating"
android:textAlignment="center" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View Profile"
android:id="#+id/button2"
android:layout_below="#+id/thumbnail"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/Wrating"
android:layout_toStartOf="#+id/Wrating" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call"
android:id="#+id/button3"
android:layout_alignTop="#+id/button2"
android:layout_alignRight="#+id/Wrating"
android:layout_alignEnd="#+id/Wrating" />
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Wrating"
style="?android:attr/ratingBarStyleIndicator"
android:foregroundGravity="center"
android:layout_below="#+id/Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:rating="3.5"
android:numStars="5" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Following is the code for worker adapter:
public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.PersonViewHolder> {
private List<Worker> persons;
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView personName;
RatingBar personRating;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.WorkerCV);
personName = (TextView) itemView.findViewById(R.id.Name);
personRating = (RatingBar) itemView.findViewById(R.id.Wrating);
}
}
public WorkerAdapter(List<Worker> persons)
{
this.persons = persons;
Log.d("Size",""+persons.size());
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.worker_card, parent, false);
PersonViewHolder pvh = new PersonViewHolder(v);
Log.d("here","ya");
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
Log.d("Pos",""+position);
holder.personName.setText(persons.get(position).getName());
holder.personRating.setRating(persons.get(position).getRating());
}
#Override
public int getItemCount() {
if (persons != null) {
return persons.size();
}
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
Following is the code for ViewWorkerList that calls worker adapter and inflates the recycler view:
public class ViewWorkerList extends AppCompatActivity {
//Creating a List of workers
private List<Worker> listWorkers;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private WorkerAdapter adapter;
// Json nodes
private static String KEY_SUCCESS = "success";
private static String KEY_NAME = "name";
private static String KEY_PHONE = "phoneno";
String url = "http://vorkal.com/read_data.php";
ArrayList<HashMap<String, String>> Item_List;
public static final String KEY_SERVICE = "service";
private String service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(),"2nd page",Toast.LENGTH_LONG);
Log.d("2pg","2page");
Intent intent = getIntent();
service = intent.getStringExtra("service"); //if it's a string you stored.
setContentView(R.layout.worker_list_main);
//Initializing our workers list
listWorkers = new ArrayList<>();
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "get_list");
params.put("service", service);
StringRequest stringRequest = new StringRequest (Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.d("response",response.toString());
JSONObject jsonObject=new JSONObject(response);
int success = jsonObject.getInt("success");
//int success=response.getInt(KEY_SUCCESS);
// Log.d("response", response.getString("workers"));
Log.d("sucess",""+success);
String workerArray=jsonObject.getString("workers");
JSONArray jar=new JSONArray(workerArray);
JSONObject json = jar.getJSONObject(0);
Log.d("name",json.getString("name"));
parseData(jar);
} catch (Exception e) {
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//recyclerView.setAdapter(new CardAdapter(listWorkers, this));
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
//Finally initializing our adapter
Log.d("listworkers",listWorkers.get(1).getName());
adapter = new WorkerAdapter(listWorkers);
recyclerView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("tag", "get_list");
params.put("service", service);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
Worker worker = new Worker();
JSONObject json = null;
try {
json = array.getJSONObject(i);
worker.setImageUrl(json.getString("pic"));
worker.setName(json.getString("name"));
worker.setLocation(json.getString("location"));
worker.setRating(json.getInt("rating"));
worker.setId(json.getInt("id"));
worker.setPhone(json.getInt("phonenumber"));
worker.setOccupation(json.getString("occupation"));
worker.setPrice(json.getInt("price"));
worker.setReview(json.getString("Review"));
} catch (JSONException e) {
e.printStackTrace();
}
listWorkers.add(worker);
}
}
}
The listWorkers contains 2 workers. But only one is getting populated in the cardview. The worker is the normal bean class. I am not able to see the 2nd worker card on the screen. Please help me out and suggest the changes.

Categories

Resources