AutoIncrement Realm failed - java

I create an activity and want to insert a new realm object
it always keep on error http null if i put getNextKey();
here is my activity
package com.example.rikirikmen.billsplit;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.rikirikmen.billsplit.Adapter.BillListAdapter;
import com.example.rikirikmen.billsplit.Adapter.MenuAdapter;
import com.example.rikirikmen.billsplit.Model.Bill;
import com.example.rikirikmen.billsplit.Model.DetailMenu;
import com.example.rikirikmen.billsplit.Model.DetailPerson;
import com.example.rikirikmen.billsplit.Model.PersonInMenu;
import com.example.rikirikmen.billsplit.Model.PersonMenuObj;
import org.w3c.dom.Text;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmList;
import io.realm.RealmObject;
public class DialogActivity extends AppCompatActivity {
Realm realm;
private RealmList<DetailPerson> person;
private RealmList<PersonInMenu> pim;
private ListView listView;
private MenuAdapter adapter;
private TextView menuName;
private TextView menuPrice;
private TextView menuQty;
private String bill;
private Button btnOke;
private Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_add_menu);
realm = Realm.getDefaultInstance();
bill = getIntent().getStringExtra("bill_ID");
btnOke = (Button) findViewById(R.id.btnOkMenu);
btnCancel = (Button) findViewById(R.id.btnCancelMenu);
menuName = (TextView) findViewById(R.id.txtMenuName);
menuPrice = (TextView) findViewById(R.id.txtMenuPrice);
menuQty = (TextView) findViewById(R.id.txtMenuQuantity);
listView = (ListView) findViewById(R.id.listViewMenu);
Toast.makeText(this, getNextKey(), Toast.LENGTH_SHORT).show();
person = realm.where(Bill.class).equalTo("Bill_ID", bill).findFirst().getDetailperson();
if (person.isEmpty()){
}
else{
adapter = new MenuAdapter(this,R.layout.row_menu, person,bill);
listView.setAdapter(adapter);
}
btnOke.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (menuName.getText().length()==0 || menuPrice.getText().length()==0|| menuQty.getText().length()==0){
Toast.makeText(DialogActivity.this, "Please fill the menu detail", Toast.LENGTH_SHORT).show();
}
else {
CharSequence priceText = menuPrice.getText();
int Price = Integer.parseInt(priceText.toString());
CharSequence qtyText = menuQty.getText();
int Qty = Integer.parseInt(qtyText.toString());
realm.beginTransaction();
DetailMenu menu = realm.createObject(DetailMenu.class);
menu.setMenuID(getNextKey());
menu.setMenuName(String.valueOf(menuName.getText()));
menu.setMenuPrice(Price);
menu.setQuantity(Qty);
for (int i = 0; i < adapter.getPersonMenuObjList().size(); i++) {
PersonInMenu pim = realm.createObject(PersonInMenu.class);
pim.setPersonID(adapter.getPersonMenuObjList().get(i).getPersonID());
pim.setStatus(adapter.getPersonMenuObjList().get(i).isStatus());
menu.personInMenus.add(pim);
}
realm.copyToRealmOrUpdate(menu);
realm.commitTransaction();
realm.close();
}
}
});
}
int getNextKey()
{
return realm.where(DetailMenu.class).max("MenuID").intValue() + 1;
}
}
here is my DetailMenu.class
package com.example.rikirikmen.billsplit.Model;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;
/**
* Created by rikirikmen on 4/24/2016.
*/
public class DetailMenu extends RealmObject {
#PrimaryKey
private int MenuID;
private int Quantity;
private String MenuName;
private int MenuPrice;
public RealmList<PersonInMenu> personInMenus;
public RealmList<PersonInMenu> getPersonInMenus() {
return personInMenus;
}
public void setPersonInMenus(RealmList<PersonInMenu> personInMenus) {
this.personInMenus = personInMenus;
}
public DetailMenu() {
super();
}
public int getMenuPrice() {
return MenuPrice;
}
public void setMenuPrice(int menuPrice) {
MenuPrice = menuPrice;
}
public int getMenuID() {
return MenuID;
}
public void setMenuID(int menuID) {
MenuID = menuID;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public int getQuantity() {
return Quantity;
}
public void setQuantity(int quantity) {
Quantity = quantity;
}
}
i dont know why is my getNextKey() is not work, because i used the same way in other activity and it works. Does anyone here have the same problem with me ?

max returns a Number or null if no objects exists. So most likely no DetailMenu objects exist and you get a NullPointerException.
Use this instead:
Number max = realm.where(DetailMenu.class).max("MenuID");
return (max != null) ? max.intValue() + 1 : 0;

Related

Calculation using JSON Data in RecyclerView and ToggleButton

I want to do calculation using JSON Data in RecyclerView with ToggleButton. When the toggle button is checked the value should change and when its not checked the value should change again for that particular RecyclerView row. The problem is when I click the ToggleButton, 2 other RecyclerView row's ToggleButton is also checked.
CODE:
Activity
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.gridlayout.widget.GridLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class GstPlanner extends AppCompatActivity implements GstPlanAdapter.GstPlanListener{
private static final String TAG = GstPlanner.class.getSimpleName();
List<String> dateNames = new ArrayList<String>();
private List<GstPlanList> GSTLisT;
private GstPlanAdapter mAdapter;
Context context;
Spinner ret_pending_drop, state_drop, nil_drop;
String URL, URL1;
ProgressBar progress_gst, Progress_Gst_Plan;
GridLayout grid_gst;
TextView txt_retry_gst, txt_state_gst, txt_ret_type, txt_final_gst;
Button btn_retry_gst, btn_submit_state, btn_submit;
String State_GET;
RecyclerView recyclerView1;
RelativeLayout Gst_Plan_Relative;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gst_planner);
Gst_Plan_Relative = findViewById(R.id.Gst_Plan_Relative);
recyclerView1 = findViewById(R.id.Recycler_Gst_Plan);
Progress_Gst_Plan = findViewById(R.id.Progress_Gst_Plan);
btn_submit_state = findViewById(R.id.btn_submit_state);
txt_state_gst = findViewById(R.id.txt_state_gst);
txt_ret_type = findViewById(R.id.txt_ret_type);
txt_retry_gst = findViewById(R.id.txt_retry_gst);
btn_retry_gst = findViewById(R.id.btn_retry_gst);
ret_pending_drop = findViewById(R.id.ret_pending_drop);
txt_final_gst = findViewById(R.id.txt_final_gst);
state_drop = findViewById(R.id.state_drop);
btn_submit = findViewById(R.id.btn_submit);
nil_drop = findViewById(R.id.nil_drop);
grid_gst = findViewById(R.id.grid_gst);
progress_gst = findViewById(R.id.progress_gst);
GSTLisT = new ArrayList<>();
mAdapter = new GstPlanAdapter(this, GSTLisT, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView1.setLayoutManager(mLayoutManager);
recyclerView1.setItemAnimator(new DefaultItemAnimator());
recyclerView1.addItemDecoration(new MyDividerItemDecoration(this, DividerItemDecoration.VERTICAL, 36));
recyclerView1.setAdapter(mAdapter);
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL1 = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString()+"&RType="+txt_ret_type.getText().toString()+"&NIL="+nil_drop.getSelectedItem().toString()+"&Month="+ret_pending_drop.getSelectedItem().toString();
Log.e("URL1",URL1);
Progress_Gst_Plan.setVisibility(View.VISIBLE);
fetchData();
GlobalValue.getit = true;
}
});
btn_submit_state.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString();
State_GET = state_drop.getSelectedItem().toString();
btn_submit_state.setVisibility(View.INVISIBLE);
state_drop.setVisibility(View.INVISIBLE);
progress_gst.setVisibility(View.VISIBLE);
fetchMonths();
}
});
btn_retry_gst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit_state.setVisibility(View.VISIBLE);
state_drop.setVisibility(View.VISIBLE);
}
});
}
private void fetchData() {
JsonArrayRequest request = new JsonArrayRequest(URL1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response == null) {
Toast.makeText(getApplicationContext(), "Couldn't fetch the Details! Please try again.", Toast.LENGTH_LONG).show();
return;
}
Gst_Plan_Relative.setVisibility(View.VISIBLE);
Progress_Gst_Plan.setVisibility(View.INVISIBLE);
List<GstPlanList> items = new Gson().fromJson(response.toString(), new TypeToken<List<GstPlanList>>() {
}.getType());
// adding contacts to contacts list
GSTLisT.clear();
GSTLisT.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
Progress_Gst_Plan.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage() +error.getCause());
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
Gst_Plan_Relative.setVisibility(View.INVISIBLE);
}
});
APP.getInstance().addToRequestQueue(request);
}
private void fetchMonths() {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject object = jsonArray.getJSONObject(0);
JSONArray arrayContacts = object.getJSONArray("Status");
for (int i = 0; i<arrayContacts.length(); i++) {
JSONObject contactObject = arrayContacts.getJSONObject(i);
dateNames.add(contactObject.getString("Month"));
}
spinnervalue(dateNames, ret_pending_drop);
txt_state_gst.setText(State_GET);
progress_gst.setVisibility(View.INVISIBLE);
grid_gst.setVisibility(View.VISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
public void spinnervalue(List<String> value, Spinner spinner1){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, value);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void AlertDialog(String s) {
try{
AlertDialog.Builder builder1 = new AlertDialog.Builder(GstPlanner.this);
builder1.setMessage(s);
builder1.setCancelable(true);
builder1.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}catch (
WindowManager.BadTokenException ex){
ex.printStackTrace();
}
}
#Override
public void onSubTotalUpdate(int total){
txt_final_gst.setText(String.valueOf(total));
}
RecyclerView Adapter
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GstPlanAdapter extends RecyclerView.Adapter<GstPlanAdapter.MyViewHolder>
implements Filterable {
private Context context;
private List<GstPlanList> GstPlanList;
private List<GstPlanList> GstPlanListFiltered;
private GstPlanListener listener;
int totalPrice;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView ret_month, due_date, penalty_amt;
Spinner nil_ret;
ToggleButton toggleSwitch;
public MyViewHolder(View view) {
super(view);
ret_month = view.findViewById(R.id.ret_month);
due_date = view.findViewById(R.id.due_date);
penalty_amt = view.findViewById(R.id.penalty_amt);
toggleSwitch = view.findViewById(R.id.switch_gst);
}
}
public GstPlanAdapter(Context context, List<GstPlanList> BiLLList, GstPlanListener listener ) {
this.context = context;
this.listener = listener;
this.GstPlanList = BiLLList;
this.GstPlanListFiltered = BiLLList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent1, int viewType1) {
View itemView = LayoutInflater.from(parent1.getContext())
.inflate(R.layout.gst_plan_view_item_row, parent1, false);
return new MyViewHolder(itemView);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
final GstPlanList bill = GstPlanListFiltered.get(position);
holder.nil_ret.setAdapter(categoriesAdapter);
holder.ret_month.setText(bill.getMonth());
holder.due_date.setText(bill.getDate());
holder.penalty_amt.setText(bill.getPenatly().toString());
totalPrice = 0;
for (int i = 0; i < GstPlanList.size(); i++) {
totalPrice += GstPlanList.get(i).getPenatly();
countTotal(totalPrice);
}
if (GlobalValue.getit == true) {
if (bill.getNIL().equals("YES")) {
holder.toggleSwitch.setChecked(true);
GlobalValue.getit = false;
} else {
holder.toggleSwitch.setChecked(false);
GlobalValue.getit = false;
}
}
holder.toggleSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILNO().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILYES().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
if (!holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILYES().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILNO().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
}
});
}
public void countTotal(int total){
listener.onSubTotalUpdate(total);
}
#Override
public int getItemCount() {
return GstPlanListFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
GstPlanListFiltered = GstPlanList;
} else {
List<GstPlanList> filteredList = new ArrayList<>();
for (GstPlanList row : GstPlanList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getDate().toLowerCase().contains(charString.toLowerCase()) || row.getMonth().toLowerCase().contains(charString.toLowerCase()) || row.getRType().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
GstPlanListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = GstPlanListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
GstPlanListFiltered = (ArrayList<GstPlanList>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface GstPlanListener {
// void onGstPlanSelected(GstPlanList bill);
void onSubTotalUpdate(int total);
}
}
GstPlanList
public class GstPlanList {
private String RType;
private String State;
private String NILNO;
private String NILYES;
private String Month;
private String Date;
private String NIL;
private int Penatly;
private int TODATE;
public GstPlanList() {
}
public Integer getPenatly() {
return Penatly;
}
public int getTODATE() {
return TODATE;
}
public String getNIL() {
return NIL;
}
public String getRType() {
return RType;
}
public String getState() {
return State;
}
public String getNILNO() {
return NILNO;
}
public String getNILYES() {
return NILYES;
}
public String getMonth() {
return Month;
}
public String getDate() {
return Date;
}
}

Button inside RecyclerView

I have a problem with my android app.
I have a RecyclerView and a click handler for it. When you click on a list item, one of the class fields is displayed on the screen. Also inside there is a button, by clicking on which another class field should be displayed. But the program throws a NullPointerException. I understand why this is happening, but I cannot understand how to modify my code, please help.
here is my Adapeter
package com.skorbr.stock_yandextest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class TickerAdapter extends RecyclerView.Adapter<TickerAdapter.TickerViewHolder> {
private List<Ticker> tickers;
private Context context;
// listener
private final Listener onTickerClickListener;
// constructor
public TickerAdapter(List<Ticker> tickers, Listener onTickerClickListener) {
this.tickers = tickers;
this.onTickerClickListener = onTickerClickListener;
}
#NonNull
#Override
public TickerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_stock_item, parent, false);
// click on RecyclerView
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onTickerClick((Ticker) v.getTag());
}
});
// click on button
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
}
});
return new TickerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
}
#Override
public int getItemCount() {
return tickers.size();
}
class TickerViewHolder extends RecyclerView.ViewHolder {
private TextView ticker;
private TextView tickerFull;
private TextView price;
private TextView priceChange;
private ImageView tickerLogo;
private Button favouriteButton;
public TickerViewHolder(#NonNull final View itemView) {
super(itemView);
ticker = itemView.findViewById(R.id.ticker);
tickerFull = itemView.findViewById(R.id.ticker_full);
price = itemView.findViewById(R.id.price);
priceChange = itemView.findViewById(R.id.price_change);
tickerLogo = itemView.findViewById(R.id.ticker_image);
favouriteButton = itemView.findViewById(R.id.button_favourite);
}
// заполнение элемента RecyclerView данными
void bind(Ticker ticker) {
double priceNow = ticker.getPrice();
double priceDayAgo = ticker.getPriceDayAgo();
String sign = "";
this.ticker.setText(ticker.getTicker());
this.tickerFull.setText(ticker.getTickerFull());
this.price.setText("$" + priceNow);
// check price
if (priceNow < priceDayAgo) {
sign = "-";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorRedDm));
} else if (priceNow > priceDayAgo) {
sign = "+";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorGreenDm));
}
// check favourites
if (ticker.isFavourite()) {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_on));
} else {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_off));
}
this.priceChange.setText(String.format("%s$%.2f (%.2f%%)", sign, Math.abs(priceNow-priceDayAgo), Math.abs(priceNow/priceDayAgo*100-100)));
this.tickerLogo.setImageResource(ticker.getTickerLogo());
}
}
interface Listener {
void onTickerClick(Ticker ticker);
void onFavouriteClick(Ticker ticker);
}
}
Here is my Main Activity
package com.skorbr.stock_yandextest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ActivityMain extends Activity {
private RecyclerView tickerList;
private TickerAdapter tickerAdapter;
private List<Ticker> tickerListList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tickerListList = tickerList();
tickerList = findViewById(R.id.tickers_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
tickerList.setLayoutManager(layoutManager);
tickerAdapter = new TickerAdapter(tickerListList, new TickerAdapter.Listener() {
#Override
public void onTickerClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTickerFull(), Toast.LENGTH_SHORT);
}
#Override
public void onFavouriteClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTicker(), Toast.LENGTH_SHORT);
}
});
tickerList.setAdapter(tickerAdapter);
}
private List<Ticker> tickerList() {
List<Ticker> tickers = new ArrayList<>();
tickers.add(new Ticker("APPL", "Apple Inc.", 138.54, 150.22, R.drawable.apple_logo, false));
tickers.add(new Ticker("TSLA", "Tesla Motors", 904.37, 753.92, R.drawable.tesla_logo, true));
tickers.add(new Ticker("GOOGL", "Alphabel Class A", 1845.90, 1845.90, R.drawable.google_logo, false));
return tickers;
}
}
Here is my class for data
package com.skorbr.stock_yandextest;
public class Ticker {
private String ticker;
private String tickerFull;
private double price;
private double priceDayAgo;
private int tickerLogo;
private boolean isFavourite;
public Ticker(String ticker, String tickerFull, double price, double priceDayAgo, int tickerLogo, boolean isFavourite) {
this.ticker = ticker;
this.tickerFull = tickerFull;
this.price = price;
this.priceDayAgo = priceDayAgo;
this.tickerLogo = tickerLogo;
this.isFavourite = isFavourite;
}
public String getTicker() {
return ticker;
}
public String getTickerFull() {
return tickerFull;
}
public double getPrice() {
return price;
}
public double getPriceDayAgo() {
return priceDayAgo;
}
public int getTickerLogo() {
return tickerLogo;
}
public boolean isFavourite() {
return isFavourite;
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
// add this line
holder.favouriteButton.setTag(ticker);
}
Or you can modify the onCreateViewHolder()
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// instead of
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
// use
onTickerClickListener.onFavouriteClick((Ticker) view.getTag());
}
});

How to retrieve array data from children node in Firebase Realtime Database Java? (Firebase Recycler Adapter)

I knew my question is similar with the other questioners but it was not solved my problem because I am still curious about how to declare the item which is the children of parent node. This is my stucture data on my Firebase:
I've tried to created the classes for my case:
DolanIemClass.java
private String name_tourism;
private String location_tourism;
private String info_tourism;
private String telepon;
private String url_photo;
private String url_photo_collage;
private double lat_location_tourism;
private double lng_location_tourism;
public DolanItemClass() {
//constructor untuk panggilan ke DataSnapshot.getValue
}
public DolanItemClass(String name_tourism, String location_tourism, String info_tourism, String telepon, String url_photo, String url_photo_collage, double lat_location_tourism, double lng_location_tourism) {
this.name_tourism = name_tourism;
this.location_tourism = location_tourism;
this.info_tourism = info_tourism;
this.telepon = telepon;
this.url_photo = url_photo;
this.url_photo_collage = url_photo_collage;
this.lat_location_tourism = lat_location_tourism;
this.lng_location_tourism = lng_location_tourism;
}
public String getUrl_photo_collage() {
return url_photo_collage;
}
public String getName_tourism() {
return name_tourism;
}
public void setName_tourism(String name_tourism) {
this.name_tourism = name_tourism;
}
public String getLocation_tourism() {
return location_tourism;
}
public void setLocation_tourism(String location_tourism) {
this.location_tourism = location_tourism;
}
public String getInfo_tourism() {
return info_tourism;
}
public void setInfo_tourism(String info_tourism) {
this.info_tourism = info_tourism;
}
public String getTelepon() {
return telepon;
}
public void setTelepon(String telepon) {
this.telepon = telepon;
}
public String getUrl_photo() {
return url_photo;
}
public void setUrl_photo(String url_photo) {
this.url_photo = url_photo;
}
public double getLat_location_tourism() {
return lat_location_tourism;
}
public void setLat_location_tourism(double lat_location_tourism) {
this.lat_location_tourism = lat_location_tourism;
}
public double getLng_location_tourism() {
return lng_location_tourism;
}
public void setLng_location_tourism(double lng_location_tourism) {
this.lng_location_tourism = lng_location_tourism;
}
}
DolanViewHolder.class
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
public class DolanImageViewHolder extends RecyclerView.ViewHolder {
private final ImageView imgDetailData;
public DolanImageViewHolder(#NonNull View itemView) {
super(itemView);
imgDetailData = itemView.findViewById(R.id.img_detail_item_data);
}
public void showImageArray(DolanItemClass dolanItemClass){
Glide.with(itemView.getContext()).load(dolanItemClass.getUrl_photo_collage()).into(imgDetailData);
}
}
And the activity class to show the list
package co.id.roningrum.firebasearrayimage;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
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.Query;
import com.google.firebase.database.ValueEventListener;
public class DetailTouristListAct extends AppCompatActivity {
private ImageView imgDetailData;
private TextView tvNamaDetail, tvAlamatDetail, tvDescDetail;
private RecyclerView rvImageDetailCollages;
private DatabaseReference databaseReference;
private ValueEventListener valueEventListener;
private FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder> firebaseRecyclerAdapter;
public static final String EXTRA_WISATA_KEY = "tourist_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_tourist_list);
String touristKey = getIntent().getStringExtra(EXTRA_WISATA_KEY);
if(touristKey == null){
throw new IllegalArgumentException("Must pass Extra");
}
imgDetailData = findViewById(R.id.img_detail_data);
tvNamaDetail = findViewById(R.id.tv_name_detail);
tvAlamatDetail = findViewById(R.id.tv_info_tourism_detail);
tvDescDetail = findViewById(R.id.tv_address_detail);
rvImageDetailCollages = findViewById(R.id.rv_photo_collage);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Tourism").child(touristKey);
rvImageDetailCollages.setLayoutManager(new GridLayoutManager(this, 2));
LoadDetailData();
}
private void ShowCollage() {
Query query = databaseReference.child("url_photo_collage");
FirebaseRecyclerOptions<DolanItemClass> options = new FirebaseRecyclerOptions.Builder<DolanItemClass>()
.setQuery(query, DolanItemClass.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull DolanImageViewHolder dolanImageViewHolder, int i, #NonNull DolanItemClass dolanItemClass) {
dolanImageViewHolder.showImageArray(dolanItemClass);
}
#NonNull
#Override
public DolanImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new DolanImageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_data, parent, false));
}
};
firebaseRecyclerAdapter.notifyDataSetChanged();
rvImageDetailCollages.setAdapter(firebaseRecyclerAdapter);
}
private void LoadDetailData() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DolanItemClass dolanItemClass = dataSnapshot.getValue(DolanItemClass.class);
tvNamaDetail.setText(dolanItemClass.getName_tourism());
tvAlamatDetail.setText(dolanItemClass.getLocation_tourism());
tvDescDetail.setText(dolanItemClass.getInfo_tourism());
Glide.with(getApplicationContext()).load(dolanItemClass.getUrl_photo()).into(imgDetailData);
ShowCollage();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(eventListener);
valueEventListener = eventListener;
}
#Override
protected void onStart() {
super.onStart();
LoadDetailData();
if(firebaseRecyclerAdapter!=null){
firebaseRecyclerAdapter.startListening();
}
}
#Override
protected void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListener);
}
}
I expected that I can show the array of url_photo_collage node but I don't have any idea for my item class.
The problem in your code is that your url_photo_collage field is declared in your DolanItemClass class of type String while in your database is an array. To solve this, change the type of your field from String to a List<String> and get it accordingly in your adapter.

ItemClickListener not working in Fragment RecyclerView with onclick

I've been following this tutorial: Tutorial
To make a json recyclerviewer with onclick, but i wanted to use Fragments instead of activities.
I've figured everything out until the point of the onClick.
My problem is the setOnItemClickListener is not taking my getActivity()
I've tried so much, but i just cant see the bright light.
If anyone could help me out that would be totally awesome!
Me only real problem is that the getActivity is giving a red line in the:
fNieuwsAdapter.setOnItemClickListener(getActivity());
NieuwsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import java.util.ArrayList;
public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
public static final String EXTRA_URL = "nieuwsImageUrl";
public static final String EXTRA_HEADING = "nieuwsHeading";
public static final String EXTRA_CONTENT = "nieuwsContent";
private RecyclerView fNieuwsRecyclerView;
private NieuwsAdapter fNieuwsAdapter;
private ArrayList<NieuwsItem> fNieuwsList;
private RequestQueue fNieuwsQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
fNieuwsRecyclerView.setHasFixedSize(true);
fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fNieuwsList = new ArrayList<>();
fNieuwsQueue = Volley.newRequestQueue(getActivity());
parseJSON();
return view;
}
private void parseJSON() {
String url = "urlissecretsorry<3butthejsonparsingworks";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public String nieuwsImageUrl;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
JSONArray attachArray = hit.getJSONArray("attachments");
for (int a = 0; a < attachArray.length(); a++) {
JSONObject attach = attachArray.getJSONObject(a);
nieuwsImageUrl = attach.getString("url");
}
String nieuwsHeading = hit.getString("title");
String nieuwsExcerpt = hit.getString("excerpt");
String nieuwsContent = hit.getString("content");
nieuwsExcerpt = html2text(nieuwsExcerpt);
fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
}
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
fNieuwsAdapter.setOnItemClickListener(getActivity());
fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
fNieuwsQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
NieuwsItem clickedItem = fNieuwsList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
startActivity(detailIntent);
}
public String html2text(String html) {
try {
return Jsoup.parse(html).text();
} catch (Exception ignored) {
return "";
}
}
}
NieuwsItem.java
public class NieuwsItem {
private String nieuwsImageUrl;
private String nieuwsHeading;
private String nieuwsExcerpt;
private String nieuwsContent;
public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
nieuwsImageUrl = imageUrl;
nieuwsHeading = heading;
nieuwsExcerpt = excerpt;
nieuwsContent = content;
}
public String getImageUrl(){
return nieuwsImageUrl;
}
public String getHeading(){
return nieuwsHeading;
}
public String getExcerpt(){
return nieuwsExcerpt;
}
public String getContent(){
return nieuwsContent;
}
}
NieuwsAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentActivity;
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;
public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {
private Context NieuwsContext;
private ArrayList<NieuwsItem> NieuwsList;
private OnItemClickListener NieuwsListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
NieuwsListener = listener;
}
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
#NonNull
#Override
public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
return new NieuwsViewHolder(v);
}
#Override
public void onBindViewHolder(NieuwsViewHolder holder, int position) {
NieuwsItem currentitem = NieuwsList.get(position);
String ImageUrl = currentitem.getImageUrl();
String Heading = currentitem.getHeading();
String Excerpt = currentitem.getExcerpt();
holder.NieuwsTextViewHeading.setText(Heading);
holder.NieuwsTextViewExcerpt.setText(Excerpt);
Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
}
#Override
public int getItemCount() {
return NieuwsList.size();
}
public class NieuwsViewHolder extends RecyclerView.ViewHolder {
public ImageView NieuwsImageView;
public TextView NieuwsTextViewHeading;
public TextView NieuwsTextViewExcerpt;
public NieuwsViewHolder(#NonNull View itemView) {
super(itemView);
NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra("EXTRA_URL");
String creatorName = intent.getStringExtra("EXTRA_HEADING");
String likeCount = intent.getStringExtra("EXTRA_CONTENT");
ImageView imageView = findViewById(R.id.nieuws_detail_image);
TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
TextView textViewContent = findViewById(R.id.nieuws_detail_content);
Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
textViewHeading.setText(creatorName);
textViewContent.setText("Likes: " + likeCount);
}
}
You cant use NieuwsAdapter.setOnItemClickListener(getActivity()); , unless your activity implements OnItemClickListener interface, but im seeing that your fragment implements OnItemClickListener, so you can use the fragment instead like this :
fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);
And by the way, you are sending the data via intent with :
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
You have to get them with the same parameters (remove the ""):
String imageUrl = intent.getStringExtra(EXTRA_URL);
String creatorName = intent.getStringExtra(EXTRA_HEADING);
String likeCount = intent.getStringExtra(EXTRA_CONTENT);
Hope this helps
change
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
to
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
this.NieuwsContext = context;
this.NieuwsList = nieuwslist;
this.NieuwsListener = mOnClickListener;
}
and this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
change to
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwsListener.onItemClick(int position);
}
});
and then in fragment You can do it like this
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position)
{
//DoSomethingHere
}
});

RrecyclerView/List setOnClickListener

I did recyclerView, and each child is "Detail".
I am now asking how to sent user to the next activity when he click on "Detail". For each click send him to the other activity.
private List<ParentObject> initData() {
TitleCreator titleCreator = TitleCreator.get(this);
List<TitleParent> titles = titleCreator.getAll();
List<ParentObject> parentObject = new ArrayList<>();
for(TitleParent title:titles)
{
List<Object> childList = new ArrayList<>();
childList.add(new TitleChild("Detail", ""));
title.setChildObjectList(childList);
parentObject.add(title);
}
return parentObject;
}
This is code where I put every child to be "Detail".
I had four Parent titles and of course four child titles. When user click on first *Parent title it open child title. Question is when user click on this child title how to send him to the other activity?
Here is my adapter fil
package com.example.user_pc.glavnastranicaprojekat.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import
com.bignerdranch.expandablerecyclerview.Adapter.ExpandableRecyclerAdapter;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import com.example.user_pc.glavnastranicaprojekat.models.TitleChild;
import com.example.user_pc.glavnastranicaprojekat.models.TitleParent;
import com.example.user_pc.glavnastranicaprojekat.R;
import
com.example.user_pc.glavnastranicaprojekat.ViewHolders.TitleChildViewHolder;
import
com.example.user_pc.glavnastranicaprojekat.ViewHolders.TitleParentViewHolder;
import java.util.List;
public class MyAdapter extends
ExpandableRecyclerAdapter<TitleParentViewHolder,TitleChildViewHolder> {
LayoutInflater inflater;
public MyAdapter(Context context, List<ParentObject> parentItemList) {
super(context, parentItemList);
inflater = LayoutInflater.from(context);
}
#Override
public TitleParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view = inflater.inflate(R.layout.list_parent,viewGroup,false);
return new TitleParentViewHolder(view);
}
#Override
public TitleChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view = inflater.inflate(R.layout.list_child,viewGroup,false);
return new TitleChildViewHolder(view);
}
#Override
public void onBindParentViewHolder(TitleParentViewHolder titleParentViewHolder, int i, Object o) {
TitleParent title = (TitleParent)o;
titleParentViewHolder._textView.setText(title.getTitle());
}
#Override
public void onBindChildViewHolder(TitleChildViewHolder titleChildViewHolder, int i, Object o) {
TitleChild title = (TitleChild)o;
titleChildViewHolder.option1.setText(title.getOption1());
titleChildViewHolder.option2.setText(title.getOption2());
}
}
TitleParent.java :
package com.example.user_pc.glavnastranicaprojekat.models;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import java.util.List;
import java.util.UUID;
public class TitleParent implements ParentObject{
private List<Object> mChildrenList;
private UUID _id;
private String title;
public TitleParent(String title) {
this.title = title;
_id = UUID.randomUUID();
}
public UUID get_id() {
return _id;
}
public void set_id(UUID _id) {
this._id = _id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public List<Object> getChildObjectList() {
return mChildrenList;
}
#Override
public void setChildObjectList(List<Object> list) {
mChildrenList = list;
}
}
Here is TitleChild.java:
package com.example.user_pc.glavnastranicaprojekat.models;
public class TitleChild {
public String option1;
public String option2;
public TitleChild(String option1, String option2) {
this.option1 = option1;
this.option2 = option2;
}
public String getOption1() {
return option1;
}
public void setOption1(String option1) {
this.option1 = option1;
}
public String getOption2() {
return option2;
}
public void setOption2(String option2) {
this.option2 = option2;
}
}
TitleCreator.java:
package com.example.user_pc.glavnastranicaprojekat.models;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public class TitleCreator {
static TitleCreator _titleCreator;
List<TitleParent> _titleParents;
public TitleCreator(Context context) {
_titleParents = new ArrayList<>();
TitleParent title = new TitleParent(String.format("Coppa"));
_titleParents.add(title);
TitleParent title1 = new TitleParent(String.format("Levante"));
_titleParents.add(title1);
TitleParent title2 = new TitleParent(String.format("Monument"));
_titleParents.add(title2);
TitleParent title3 = new TitleParent(String.format("Comming soon"));
_titleParents.add(title3);
}
public static TitleCreator get(Context context)
{
if(_titleCreator == null)
_titleCreator = new TitleCreator(context);
return _titleCreator;
}
public List<TitleParent> getAll() {
return _titleParents;
}
}
TitleChildViewHolder:
package com.example.user_pc.glavnastranicaprojekat.ViewHolders;
import android.view.View;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ChildViewHolder;
import com.example.user_pc.glavnastranicaprojekat.R;
public class TitleChildViewHolder extends ChildViewHolder {
public TextView option1,option2;
public TitleChildViewHolder(View itemView) {
super(itemView);
option1 = itemView.findViewById(R.id.option1);
option2 = itemView.findViewById(R.id.option2);
}
}
TitleParentViewHolder:
package com.example.user_pc.glavnastranicaprojekat.ViewHolders;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ParentViewHolder;
import com.example.user_pc.glavnastranicaprojekat.R;
public class TitleParentViewHolder extends ParentViewHolder {
public TextView _textView;
public ImageButton _imageButton;
public TitleParentViewHolder(View itemView) {
super(itemView);
_textView = itemView.findViewById(R.id.parentTitle);
_imageButton = itemView.findViewById(R.id.expandArrow);
}
}
MainActivity:
RecyclerView recyclerView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
recyclerView = findViewById(R.id.myRecyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyAdapter adapter = new MyAdapter(this,initData());
adapter.setParentClickableViewAnimationDefaultDuration();
adapter.setParentAndIconExpandOnClick(true);
recyclerView.setAdapter(adapter);
}
private List<ParentObject> initData() {
TitleCreator titleCreator = TitleCreator.get(this);
List<TitleParent> titles = titleCreator.getAll();
List<ParentObject> parentObject = new ArrayList<>();
for(TitleParent title:titles)
{
List<Object> childList = new ArrayList<>();
childList.add(new TitleChild("Detail", ""));
title.setChildObjectList(childList);
parentObject.add(title);
}
return parentObject;
}
titleChildViewHolder.itemView.setOnClickListener(
new OnClickListener(View v){
context.startActivity(new Intent(context,DESTINATION_ACTIVITY.class)));
}
);
Put this code inside onBindChildViewHolder
try something like this:
#Override
public void onBindChildViewHolder(TitleChildViewHolder titleChildViewHolder, int i, Object o) {
TitleChild title = (TitleChild)o;
titleChildViewHolder.option1.setText(title.getOption1());
titleChildViewHolder.option2.setText(title.getOption2());
titleChildViewHolder.option1.setOnClickListener(
new OnClickListener(View v){
context.startActivity(new Intent(context,ACTIVITY_TO_LAUNCH.class)));
}
);
}
If you need you can set an equivalent OnClickListener also on titleChildViewHolder.option2
Maybe you could add a container of views option1 and option2 so you could set only one ClickListener

Categories