Retrofit with recyclerview issue - android-recyclerview

I am not getting data in recycler view but not getting any error .
This is Main Activity class
package in.co.getonlinerecharge.cab.bw_cab.activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import in.co.getonlinerecharge.cab.bw_cab.AppController;
import in.co.getonlinerecharge.cab.bw_cab.R;
import in.co.getonlinerecharge.cab.bw_cab.adepter.CarTypeAdepter;
import in.co.getonlinerecharge.cab.bw_cab.helper.ToastHelper;
import in.co.getonlinerecharge.cab.bw_cab.model.Cartype;
import in.co.getonlinerecharge.cab.bw_cab.model.CartypeArray;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Slect_Car_Activity extends AppCompatActivity {
RecyclerView rvGetCartype;
private ArrayList<Cartype> data;
private CarTypeAdepter carTypeAdepter;
private TextView txt_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slect__car_);
rvGetCartype = (RecyclerView)findViewById(R.id.RV_list);
txt_data = (TextView)findViewById(R.id.txt_data);
getAndSetCarType();
}
private void getAndSetCarType() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.please_wait));
progressDialog.show();
Call<CartypeArray> call = AppController.getInstance().getApiInterface().getCartype();
call.enqueue(new Callback<CartypeArray>() {
#Override
public void onResponse(Call<CartypeArray> call, Response<CartypeArray> response) {
progressDialog.dismiss();
CartypeArray cartypeArray = response.body();
Collections.reverse(cartypeArray.getCtypes());
carTypeAdepter = new CarTypeAdepter(cartypeArray,getApplicationContext());
rvGetCartype.setAdapter(carTypeAdepter);
}
#Override
public void onFailure(Call<CartypeArray> call, Throwable t) {
progressDialog.dismiss();
}
});
}
}
This is my model class for retrofit which gives Json array with status
package in.co.getonlinerecharge.cab.bw_cab.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Cartype {
#SerializedName("id")
#Expose
private String id;
#SerializedName("vehicle_type")
#Expose
private String Vehicale_type;
#SerializedName("vehicle_name")
#Expose
private String Vehicale_name;
#SerializedName("vehicle_no")
#Expose
private String Vehicale_no;
#SerializedName("vimage")
#Expose
private String Vimage;
#SerializedName("status")
#Expose
private String status;
#SerializedName("created_at")
#Expose
private String created_at;
#SerializedName("updated_at")
#Expose
private String updated_at;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVehicale_type() {
return Vehicale_type;
}
public void setVehicale_type(String vehicale_type) {
Vehicale_type = vehicale_type;
}
public String getVehicale_name() {
return Vehicale_name;
}
public void setVehicale_name(String vehicale_name) {
Vehicale_name = vehicale_name;
}
public String getVehicale_no() {
return Vehicale_no;
}
public void setVehicale_no(String vehicale_no) {
Vehicale_no = vehicale_no;
}
public String getVimage() {
return Vimage;
}
public void setVimage(String vimage) {
Vimage = vimage;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
This is my Adapter class with view holder for recycler view
package in.co.getonlinerecharge.cab.bw_cab.adepter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import in.co.getonlinerecharge.cab.bw_cab.R;
import in.co.getonlinerecharge.cab.bw_cab.model.Cartype;
import in.co.getonlinerecharge.cab.bw_cab.model.CartypeArray;
import in.co.getonlinerecharge.cab.bw_cab.utils.Constans;
public class CarTypeAdepter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private CartypeArray cartypeArray;
private Context mcontext;
public CarTypeAdepter(CartypeArray cartypeArray, Context mcontext) {
this.cartypeArray = cartypeArray;
this.mcontext = mcontext;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = (LayoutInflater.from(parent.getContext()).inflate(R.layout.list_car,parent, false));
CartypeHolder cartypeHolder = new CartypeHolder(view);
return cartypeHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder Holder, int position) {
CartypeHolder cartypeHolder = (CartypeHolder) Holder;
cartypeHolder.txt_cartype.setText(cartypeArray.getCtypes().get(position).getVehicale_name());
}
#Override
public int getItemCount() {
return cartypeArray.getCtypes().size();
}
private class CartypeHolder extends RecyclerView.ViewHolder {
ImageView img_car;
TextView txt_cartype;
public CartypeHolder(View itemview) {
super(itemview);
img_car = (ImageView)itemview.findViewById(R.id.CarImageView);
txt_cartype = (TextView)itemview.findViewById(R.id.titleTextView);
}
}
}
My second model class for retrofit for getting JSON data
package in.co.getonlinerecharge.cab.bw_cab.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class CartypeArray {
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("Cartype")
#Expose
private List<Cartype> ctypes;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public List<Cartype> getCtypes() {
return ctypes;
}
public void setCtypes(List<Cartype> ctypes) {
this.ctypes = ctypes;
}
}
This is Activity main XML
<?xml version="1.0" encoding="utf-8"?>
<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="in.co.getonlinerecharge.cab.bw_cab.activity.Slect_Car_Activity">
<android.support.design.widget.AppBarLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="Select Your Car" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/RV_list"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt_data"/>
</LinearLayout>
List of display data for list view
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/card_height"
android:orientation="vertical"
>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/CarImageView"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:src="#drawable/suv"
/>
<TextView
android:layout_gravity="center"
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="SUV"
android:textSize="#dimen/card_text_size"
android:textColor="#color/colorPrimary"/>
</LinearLayout>
</android.support.v7.widget.CardView>

set Layout Manager to your recycler in onCreate:
rvGetCartype = (RecyclerView)findViewById(R.id.RV_list);
rvGetCartype.setLayoutManager(new LinearLayoutManager(this));
If it didnt help try next:
1.Make sure, that in your response ArrayList isnt empty.
2.If it isnt, try to next:
public class CarTypeAdepter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<Cartype> cartypeArray;
private Context mcontext;
public CarTypeAdapter(Context context){
this.mcontext = context;
cartypeArray = new ArrayList<>();
}
public void setList(ArrayList<Cartype> list){
this. cartypeArray = list;
notifyDataSetChanges();
}
//other methods
}
then create variable of this adapter in activity and init it in onCreate, and set it to your recycler view. Then in onResponse use method setList(cartypeArray) to set array to adapter.
Hope you understand me and its help.

Related

Why doesn't my radioButton get checked or unchecked?

I followed a tutorial to check a single radioButton. I tried to change it so you can change multiple radioButtons.
I succeeded to get the value out of the arraylist and show it on the screen, but when I click on it doesn't change. Only the radioButton that is unchecked get checked. Can anyone help me with this.
public interface ItemClickListener {
//Create method
void onClick(String s);
}
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.AdapterView;
import android.widget.RadioButton;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
//Initialize variable
RecyclerView recyclerView;
ItemClickListener itemClickListener;
MainAdapter adapter;
ArrayList<String> arrayList;
ArrayList<Boolean> arrayList_B;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Assign variable
recyclerView = findViewById(R.id.recycler_view);
fillArrayList();
//Initialize listener
itemClickListener = new ItemClickListener() {
#Override
public void onClick(String s) {
//Notify adapter
recyclerView.post(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
//Display toast
Toast.makeText(getApplicationContext(),
"Selected : " + s, Toast.LENGTH_SHORT).show();
}
};
//Set layout manager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Initialize adapter
adapter = new MainAdapter(arrayList, arrayList_B, itemClickListener);
//Set adapter
recyclerView.setAdapter(adapter);
}
public void fillArrayList() {
//initialize array list
arrayList = new ArrayList<>();
arrayList_B = new ArrayList<>();
//Use for loop
for (int i = 0; i < 10; i++) {
//Add values in array list
arrayList.add("RB " + i);
arrayList_B.add(true);
}
arrayList_B.set(3,false);
}
}
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
//Initialize variable
ArrayList<String> arrayList;
ArrayList<Boolean> arrayList_B;
ItemClickListener itemClickListener;
int selectedPosition = -1;
//Create constructor
public MainAdapter(ArrayList<String> arrayList, ArrayList<Boolean> arrayList_B, ItemClickListener itemClickListener) {
this.arrayList = arrayList;
this.itemClickListener = itemClickListener;
this.arrayList_B = arrayList_B;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Initialize view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_main, parent, false);
//Pass holder view
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//Set text on radio button
holder.radioButton.setText(arrayList.get(position));
//Set true or false radio button
holder.radioButton.setChecked(arrayList_B.get(position));
//Set listener on radio button
holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//When checked
//Update selected position
selectedPosition = holder.getAdapterPosition();
//if (arrayList_B.get(selectedPosition).equals(true)) {
//if (b == true) {
// arrayList_B.set(selectedPosition, false);
//}
//if (b == false) {
//
//}
arrayList_B.set(selectedPosition, b);
holder.radioButton.setChecked(arrayList_B.get(selectedPosition));
//Call listener
//Get RadioButton name.
itemClickListener.onClick(holder.radioButton.getText().toString());
//set array list radiobutton
}
});
}
#Override
public long getItemId(int position) {
//Pass position
return position;
}
#Override
public int getItemViewType(int position) {
//Pass position
return position;
}
#Override
public int getItemCount() {
//Pass total List size
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//Initialize variable
RadioButton radioButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
//Assign variable
radioButton = itemView.findViewById(R.id.radiobutton);
}
}
}
The Layout: activity_main.xml
<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"
android:padding="16dp"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view"
tools:listitem="#layout/item_main"/>
</RelativeLayout>
The Layout: item_main.xml
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radiobutton"
android:padding="12dp"
android:textSize="18sp"
android:textColor="#android:color/darker_gray"/>

What is making my app crash without an error

I am writing an app. that you can search info about celebs and save it to a SQlite database. I followed tutorials in showing the information but when I run the app it crashes without an error... please assist
When I request the data I only want the names display in a Listview, then when the user clicks on the name of the Celeb, it will open a page with all the saved data..I have no idea where to even start looking for the problem..I can open the app, save the data but when I open the activity to show the ListView it crashes without an error...
my xml for displaying the listview
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#drawable/mway"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#color/colorPrimaryDark"
android:text="#string/app_name"
android:textAlignment="center"
android:textColor="#color/colorPrimary"
android:textSize="32sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_view"
android:background="#drawable/mway">
</ListView>
</LinearLayout>
Here is my java file for displaying the listview
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class viewceleb extends AppCompatActivity {
DatabaseHelper db;
ArrayList<String> listItems;
ArrayAdapter adapter;
ListView userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewceleb);
userList = findViewById(R.id.list_view);
listItems = new ArrayList<>();
viewData();
userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
String text = userList.getItemAtPosition(i).toString();
Toast.makeText(viewceleb.this, "Now something can happen", Toast.LENGTH_LONG).show();
}
});
}
private void viewData() {
Cursor cursor = db.viewData();
if (cursor.getCount()== 0){
Toast.makeText(this,"No Data To Show", Toast.LENGTH_LONG).show();
}else {
while(cursor.moveToNext()){
listItems.add(cursor.getString(1));//index 1 is name, 0 is ID
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
userList.setAdapter(adapter);
}
}
}
You are only declaring db, it needs to be instantiated.
That is you have DatabaseHelper db; and you additionall need db = new DatabaseHelper(?); where ? are the parameters required by the DatabaseHelper constructor. Typically just the Context so perhaps db = new DatabaseHelper(this);. This would be coded in the activity's onCreate method BEFORE calling the viewData method.
e.g.
public class viewceleb extends AppCompatActivity {
DatabaseHelper db;
ArrayList<String> listItems;
ArrayAdapter adapter;
ListView userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewceleb);
dn = new DatabaseHelper(this); //<<<<<<<<<< ADDED note just the context has been assumed, the parameters depend upon the constructor as per what is coded in the DatabaseHelper class.
userList = findViewById(R.id.list_view);
listItems = new ArrayList<>();
viewData();
userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
String text = userList.getItemAtPosition(i).toString();
Toast.makeText(viewceleb.this, "Now something can happen", Toast.LENGTH_LONG).show();
}
});
}
private void viewData() {
Cursor cursor = db.viewData();
if (cursor.getCount()== 0){
Toast.makeText(this,"No Data To Show", Toast.LENGTH_LONG).show();
}else {
while(cursor.moveToNext()){
listItems.add(cursor.getString(1));//index 1 is name, 0 is ID
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
userList.setAdapter(adapter);
}
}
}

Using Picasso Images not showing in Recycler view

I am trying to show images from a Firebase database in recycler view in android studio but the images are not displaying. I am not sure where I have gone wrong or what the problem is.
Main Activity.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.test.test.AddBrandPage"
android:weightSum="1">
<TextView
android:id="#+id/editText"
android:layout_width="383dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Select your favourite stores..."
android:textAlignment="center"
android:textSize="22sp" />
<LinearLayout
android:id="#+id/alphaindex"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal"></LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recylView"
android:layout_width="337dp"
android:layout_height="370dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/editText2"
android:layout_marginLeft="14dp"
android:layout_marginRight="14dp"
android:layout_marginStart="14dp"
android:layout_marginTop="24dp"
android:layout_weight="0.23"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.11"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<Button
android:id="#+id/btn_skip"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="15dp"
android:layout_marginRight="15dp"
android:background="#color/colorPrimary"
android:text="Skip"
android:textAllCaps="true"
android:textColor="#android:color/background_light"
android:textSize="20sp"
android:textStyle="normal|bold" />
<Button
android:id="#+id/btn_submit"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginRight="20dp"
android:background="#color/colorPrimary"
android:text="Submit"
android:textAllCaps="true"
android:textColor="#android:color/background_light"
android:textSize="20sp"
android:textStyle="normal|bold" />
</LinearLayout>
</LinearLayout>
Logo_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardView="http://schemas.android.com/apk/res-auto"
android:id="#+id/logo_container"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#android:color/darker_gray"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:visibility="visible"
cardView:layout_collapseParallaxMultiplier="1.0">
<android.support.v7.widget.CardView
android:layout_width="155dp"
android:layout_height="100dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
cardView:cardBackgroundColor="#android:color/white">
<GridLayout
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/img_logo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="1"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_row="0"
android:paddingBottom="5dp"
android:paddingLeft="2.5dp"
android:paddingRight="2.5dp"
android:paddingTop="5dp">
</ImageView>
</GridLayout>
<CheckBox
android:id="#+id/checkbox"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="130dp"
android:layout_marginTop="66dp"
/>
</android.support.v7.widget.CardView>
</LinearLayout>
LogoItems.java
public class LogoItems {
//declare variables(the items displayed in the layout)
private String logo;//, name;
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
}
Main Activity.java
package com.test.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AddBrandPage extends AppCompatActivity implements OnClickListener {
//declare variables
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private DatabaseReference myRef;
private Button btn_skip;
private Button btn_submit;
//private String name;
//private String url;
List<LogoItems> brandLogo = new ArrayList<>();
//HashMap<String, String> dataSet = new HashMap<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_brand_page);
//initialize variables
btn_skip = (Button) findViewById(R.id.btn_skip);
btn_submit = (Button) findViewById(R.id.btn_submit);
myRef = FirebaseDatabase.getInstance().getReference().child("/brands");
// set the main recyclerview view in the layout
recyclerView = (RecyclerView) findViewById(R.id.recylView);
recyclerView.setHasFixedSize(true);
// set the main layoutManager of the recyclerview
layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
loadLogoImgData();
// set the recycler view adapter
adapter = new LogoAdapter(brandLogo, getBaseContext());
recyclerView.setAdapter(adapter);
//set the listener for the buttons click event
btn_skip.setOnClickListener(this);
btn_submit.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == btn_skip) {
//if skip button clicked close current window and go to user main page
finish();
startActivity(new Intent(getApplicationContext(), UserMainPage.class));
}
}
public void loadLogoImgData(){
brandLogo.clear();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value = brandSnapshot.getValue(LogoItems.class);
LogoItems brandDetails = new LogoItems();
// String name = value.getName();
String logos = value.getLogo();
//brandDetails.setName(name);
brandDetails.setLogo(logos);
brandLogo.add(brandDetails);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
LogoItemsAdapter.java
package com.test.test;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class LogoAdapter extends RecyclerView.Adapter<LogoAdapter.LogoViewHolder> {
List<LogoItems> brandLogo = new ArrayList<>();
// private AddBrandPage addBrandPage;
private Context context;
public LogoAdapter(List <LogoItems> brandLogo, Context context){
this.brandLogo = brandLogo;
this.context = context;
//addBrandPage = (AddBrandPage)context;
}
#Override
public LogoAdapter.LogoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.logo_items,parent,false);
LogoViewHolder logoViewHolder = new LogoViewHolder(view);
return logoViewHolder;
}
#Override
public void onBindViewHolder(LogoAdapter.LogoViewHolder holder, int position) {
//holder.logo.setImageURI(Uri.parse(brandLogo.get(position).getLogo()));
Picasso.with(context).load(brandLogo.get(position).getLogo()).into(holder.logo);
}
#Override
public int getItemCount() {
return brandLogo.size();
}
public static class LogoViewHolder extends RecyclerView.ViewHolder{
//declare variables
public ImageView logo;
CheckBox checkbox;
//private View itemView;
public LogoViewHolder(View itemView){
super(itemView);
//initialize variables inside the constructor
logo = (ImageView)itemView.findViewById(R.id.img_logo);
checkbox = (CheckBox)itemView.findViewById(R.id.checkbox);
// this.itemView = itemView;
}
}
}
your code seems a bit vague like here :
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value =
brandSnapshot.getValue(LogoItems.class);
LogoItems brandDetails =
new LogoItems();
// String name = value.getName();
String logos = value.getLogo();
//brandDetails.setName(name);
brandDetails.setLogo(logos);
brandLogo.add(brandDetails); } }
Change this code to :
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot brandSnapshot : dataSnapshot.getChildren()){
LogoItems value =
brandSnapshot.getValue(LogoItems.class);
brandLogo.add(value); }
startRecyclerView();
}
Firebase methods are asynchronous, your present code inflates the recylcerview synchronously which means it is loaded before the data has been set and received.
The changed code starts recyclerview asynchronously after the data has been loaded from the database. You can add a progress bar to know the status. You can set it like this (Initialize it before this method and it will be visible by default) :
mProgressBar.setVisibility(View.INVISIBLE);
startRecyclerView();
This way the code looks organised.

StaggeredGridLayoutManager with recyclerview showing only two images per page

I have taken sample code from https://github.com/chrisbanes/cheesesquare as base to show images in StaggeredGridLayoutManager. StaggeredGridLayoutManager with recyclerview showing only two images per page.
I tried almost all ways to show multiple images in full page, but its not working.
Any help would be great.
fragment_cheese_list.xml
<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:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.support.android.designlibdemo.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/color_primary_teal">
<!--<android.support.v7.widget.CardView-->
<!--xmlns:card_view="http://schemas.android.com/apk/res-auto"-->
<!--xmlns:android="http://schemas.android.com/apk/res/android"-->
<!--android:id="#+id/card_view"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--card_view:cardUseCompatPadding="true"-->
<!--card_view:cardCornerRadius="8dp"-->
<!--android:layout_marginBottom="16dp">-->
<!--<RelativeLayout-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent">-->
<!--<de.hdodenhof.circleimageview.CircleImageView-->
<!--android:id="#+id/avatar"-->
<!--android:layout_width="#dimen/list_item_avatar_size"-->
<!--android:layout_height="#dimen/list_item_avatar_size"-->
<!--android:layout_marginRight="16dp"/>-->
<ImageView
android:id="#+id/avatar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:onClick="getImageDetails" />
<TextView
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?attr/textAppearanceListItem"/>
<!--</RelativeLayout>-->
<!--</android.support.v7.widget.CardView>-->
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
CheeseListFragment.java
package com.support.android.designlibdemo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class CheeseListFragment extends Fragment {
//private RecyclerView.StaggeredGridLayoutManager mLayoutManager;
int cheeseImages[]= {R.drawable.cheese_1,R.drawable.cheese_2,R.drawable.cheese_3,
R.drawable.cheese_4,R.drawable.cheese_5};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate(R.layout.fragment_cheese_list, container, false);
RecyclerView rv = (RecyclerView) relativeLayout.findViewById(R.id.recyclerview);
//RecyclerView rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
private void setupRecyclerView(RecyclerView recyclerView) {
//recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
ArrayList<ImageDetails> placeList = getPlaces();
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, 30), placeList));
}
private List<String> getRandomSublist(String[] array, int amount) {
ArrayList<String> list = new ArrayList<>(amount);
Random random = new Random();
while (list.size() < amount) {
list.add(array[random.nextInt(array.length)]);
}
return list;
}
private ArrayList<ImageDetails> getPlaces() {
ArrayList<ImageDetails> details = new ArrayList<>();
for (int index=0; index<30;index++){
details.add(new ImageDetails(Cheeses.getRandomCheeseDrawable()));
}
return details;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
private ArrayList<ImageDetails> mImagesList;
public static class ViewHolder extends RecyclerView.ViewHolder {
public String mBoundString;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString() {
return super.toString() + " '" + mTextView.getText();
}
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items, ArrayList<ImageDetails> imageList) {
// context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
// mBackground = mTypedValue.resourceId;
mValues = items;
mImagesList = imageList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
//view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mBoundString = mValues.get(position);
holder.mTextView.setText(mValues.get(position));
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, CheeseDetailActivity.class);
intent.putExtra(CheeseDetailActivity.EXTRA_NAME, holder.mBoundString);
context.startActivity(intent);
}
});
holder.mImageView.setImageResource(mImagesList.get(position).getImageUrl());
// Glide.with(holder.mImageView.getContext())
// .load(Cheeses.getRandomCheeseDrawable())
// .fitCenter()
// .into(holder.mImageView);
}
#Override
public int getItemCount() {
return mValues.size();
}
}
}
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
chnage layout height to wrap_content:-
android:layout_height="wrap_content"

NullPointerException: Attempt to invoke virtual method 'void io.realm.Realm.beginTransaction()' on a null object reference

So I am making an app where I use an activity to introduce data about cities using Realm. I want to save the data when the floating action button is pressed but I keep getting a NullPointerExeption and when I debbug the app I see that realm in realm.beginTransaction() is null..
Can someone give an advice on why this happens? Thank you!
City class:
package com.android.bianca.cityworld2.models;
import com.android.bianca.cityworld2.app.MyApplication;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;
/**
* Created by Bianca on 25/01/2017.
*/
public class City extends RealmObject {
#PrimaryKey
private int id;
#Required
private String nombre;
#Required
private String description;
#Required
private String imagen;
public City(){
};
public City(String nombre, String description, String imagen) {
this.id = MyApplication.CityID.incrementAndGet();
this.nombre = nombre;
this.description = description;
this.imagen = imagen;
}
public int getID(){ return id;}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
}
AddEditActivity:
package com.android.bianca.cityworld2.activities;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.bianca.cityworld2.R;
import com.android.bianca.cityworld2.models.City;
import com.squareup.picasso.Picasso;
import io.realm.Realm;
public class AddEditActivity extends AppCompatActivity {
private FloatingActionButton fabSave;
private Realm realm;
private TextView textViewNombre;
private TextView textViewDescription;
private ImageView imageViewImagen;
private TextView textViewUrlFoto;
private ImageView imageViewPreview;
private City ciudadNueva;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit);
Realm.init(getApplicationContext());
Realm realm = Realm.getDefaultInstance();
bindReferences();
imageViewPreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String imageURL = textViewUrlFoto.getText().toString();
if(imageURL.equals("")) {
Toast.makeText(AddEditActivity.this, "No has introducido ningun url", Toast.LENGTH_SHORT).show();
}else {
Picasso.with(AddEditActivity.this).load(imageURL).error(R.mipmap.ic_star).fit().into(imageViewImagen);
}
}
});
fabSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
crearNuevaCiudad();
}
});
}
private void crearNuevaCiudad(){
String nombre = textViewNombre.getText().toString().trim();
String desc = textViewDescription.getText().toString().trim();
String img = textViewUrlFoto.getText().toString().trim();
ciudadNueva = new City(nombre,desc,img);
realm.beginTransaction();
realm.copyToRealm(ciudadNueva);
realm.commitTransaction();
//<Toast.makeText(AddEditActivity.this, nombre + "|"+description+"|"+img, Toast.LENGTH_SHORT).show();
}
private void bindReferences(){
fabSave = (FloatingActionButton) findViewById(R.id.fabSave);
textViewNombre =(TextView) findViewById(R.id.editTextEditAddNombre);
textViewDescription =(TextView) findViewById(R.id.editTextAddEditDescription);
textViewUrlFoto =(TextView) findViewById(R.id.editTextEditAddUrl);
imageViewImagen = (ImageView) findViewById(R.id.imageViewEditAddBackground);
imageViewPreview = (ImageView) findViewById(R.id.imageViewEditAddPreview);
}
}
MyApplication:
package com.android.bianca.cityworld2.app;
import android.app.Application;
import com.android.bianca.cityworld2.models.City;
import java.util.concurrent.atomic.AtomicInteger;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Bianca on 26/01/2017.
*/
public class MyApplication extends Application {
public static AtomicInteger CityID = new AtomicInteger();
#Override
public void onCreate() {
setUpRealmConfig();
Realm realm = Realm.getDefaultInstance();
CityID = getIdByTable(realm, City.class);
realm.close();
}
private void setUpRealmConfig() {
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
Realm.setDefaultConfiguration(config);
}
private <T extends RealmObject> AtomicInteger getIdByTable(Realm realm, Class<T> anyClass) {
RealmResults<T> results = realm.where(anyClass).findAll();
return (results.size() > 0) ? new AtomicInteger(results.max("id").intValue()) : new AtomicInteger();
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.bianca.cityworld2">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".activities.MainActivity">
</activity>
<activity android:name=".activities.AddEditActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>