Implementing onClick in the Recyclerview Adapter - java

I would like to know how to implement onClick for each item in my
grid (using Recycler View and Card view) to launch a new
activity.Below is my ViewHolder class and the RecyclerView Adapter
Class
This is my RecyclerView Adapter Class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.countryName.setText(itemList.get(position).getName());
holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"This is Maps",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}
//This is my Recycler View Holder Class
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView countryName;
public ImageView countryPhoto;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
countryName = (TextView) itemView.findViewById(R.id.country_name);
countryPhoto = (ImageView) itemView.findViewById(R.id.country_photo);
}
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked Country Position = " + getPosition(), Toast.LENGTH_SHORT).show();
}
}

I use Interface as the Callback to handle this case.
First, I create an interface class inside Adapter.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
private ItemClickListener mItemClickListener;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
public void addItemClickListener(ItemClickListener listener) {
mItemClickListener = listener;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.countryName.setText(itemList.get(position).getName());
holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(position);
}
}
});
}
#Override
public int getItemCount() {
return this.itemList.size();
}
//Define your Interface method here
public interface ItemClickListener {
void onItemClick(int position);
}
}
Then, let's the Activity or Fragment implement that Interface and add the listener.
public class MyFragment extends Fragment
implements RecyclerViewAdapter.ItemClickListener {
private List<ItemObject> mItemList;
...
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
...
//Make sure mItemList not NULL
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), mItemList);
//Add Item Click listener
adapter.addItemClickListener(this);
}
#Override
public void onItemClick(int position) {
Toast.makeText(.getContext(),"Click on item: " + position,Toast.LENGTH_SHORT).show();
}
}
Hope this will help!

your code look like fine, if asking for how to creat intent to open new activity here is whet you should change
it is lazy way not recommended for best pratice
make a static variable in your Mian activty witch is hold a refrance some thing like that
public class MainActivity extends AppCompatActivity
public static Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setElevation(0);
activity=this;
}
}
and then inside your click
...
#Override
public void onClick(View v) {
Toast.makeText(.getContext(),"Click on item: " + position,Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.activity, MyOtherActivity.class));
}
...

I'm not completely clear from your initial post what your issue is, but if all you want to do is implement an OnClickListener in your RecyclerViewAdapter, just add the following:
First, change your class declaration to this:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> implements OnClickListener {
Then, add your onClick method to the class, to complete the interface.
#Override
public void onClick(View view) {
Toast.makeText(this.getContext(),"Code to change activity goes here." ,Toast.LENGTH_SHORT).show();
}
Finally, you'll need to set an OnClickListener in your adapter class.
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.setOnClickListener(this);
holder.countryName.setText(itemList.get(position).getName());
holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(position);
}
}
});
}
Now, personally I wouldn't do things this way. What I would do instead is add a private inner class to your adapter, like this:
private AdapterOnClickListener implements OnClickListener() {
private String message;
public AdapterOnClickListener (String toast) {
message = toast;
}
public void onClick (View v) {
Toast.makeText(this.getContext(),toast ,Toast.LENGTH_SHORT).show();
}
}
Then in the adapter you call:
#Override
public void onBindViewHolder(RecyclerViewHolders holder, final int position) {
holder.setOnClickListener(new AdapterOnClickListener ("Instead of a string, I can be an intent. Then in your listener, you can call (If I recall correctly) getContext().startActivity(intent), and have an activity.");
holder.countryName.setText(itemList.get(position).getName());
holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
holder.countryPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(position);
}
}
});
}

Related

NotifyDatasetchanged not working. AppCrashes after ButtonOnClick [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I've been trying to create a button that adds a new Value to my Arraylist (contries) when clicked, but it instead of adding my item(Card) the app simply crashes. I am also using Fragments. Here's my code.
That one is my Class for my FragmentPage
package com.example.barryblack;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class FragmentPage extends Fragment {
private RecyclerView.Adapter mAdapter;
private ArrayList countries;
Button btn;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment, container, false);
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
btn = view.findViewById(R.id.button_insert);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
}
});
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new MyAdapter(countries);
recyclerView.setAdapter(adapter);
return view;
}
public void InsertItem() {
countries.add("Smile");
mAdapter.notifyDataSetChanged();
}
private void CreateExampleList() {
countries = new ArrayList<String>();
countries.add("Eat");
countries.add("Kill");
}
}
This is my CustomAdapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<String> cards;
public MyAdapter(ArrayList<String> countries) {
this.cards = countries;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_item, viewGroup,
false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_country.setText(cards.get(i));
}
#Override
public int getItemCount() {
return cards.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_country;
private Button tv_button;
public ViewHolder(View view) {
super(view);
tv_country = (TextView)view.findViewById(R.id.tv_country);
}
}
}public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<String> cards;
public MyAdapter(ArrayList<String> countries) {
this.cards = countries;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.example_item, viewGroup,
false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_country.setText(cards.get(i));
}
#Override
public int getItemCount() {
return cards.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_country;
private Button tv_button;
public ViewHolder(View view) {
super(view);
tv_country = (TextView)view.findViewById(R.id.tv_country);
}
}
}
And my LogcatText
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView$Adapter.notifyDataSetChanged()' on a null object reference
at com.example.barryblack.FragmentPage.InsertItem(FragmentPage.java:60)
at com.example.barryblack.FragmentPage$1.onClick(FragmentPage.java:43)
this code private RecyclerView.Adapter mAdapter;
must be private MyAdapter mAdapter;
and this RecyclerView.Adapter adapter = new MyAdapter(countries);
to this MyAdapter mAdapter = new MyAdapter(countries);

How to change textview item color from another class?

I have one big problem ( for me )
I have some items from api in RecycleViewHolder.class in that class i tell where is xml file of that items.. Now my problem is because i have preference settings in mainactivity and when i define background color to black of whole app my text will be in the same color "black" and i can not see anything in app because of colour. Now i need your help how to change colour of textview in mainactivity,when i try to make findviewbyid in MainActivity and call method setTextColor I get nullpointexception because it is already connected to xml in RecycleViewHolder Class.
This is RecyclceViewHolder class that contains textview of price that i wanna to change colour from mainactivity.
package com.example.domo.cryptotrace;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.view.View;
/**
* Created by Antun on 31.1.2018..
*/
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView name, symbol, rank, percentChange1h, percentChange24h, percentChange7d;
public TextView price;
public RecyclerViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
name = itemView.findViewById(R.id.name);
symbol= itemView.findViewById(R.id.symbol);
rank = itemView.findViewById(R.id.
rank);
price=itemView.findViewById(R.id.price);
percentChange1h=itemView.findViewById(R.id.percent_change_1h);
percentChange24h=itemView.findViewById(R.id.percent_change_24h);
percentChange7d=itemView.findViewById(R.id.percent_change_7d);
}
#Override
public void onClick(View view) {
}
}
This is mainactivity (in this class i wanna change
RecyclerViewHolder --> itemView--> price color)
package com.example.domo.cryptotrace;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.View;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
import com.crashlytics.android.Crashlytics;
import java.util.List;
import io.fabric.sdk.android.Fabric;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
public Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
final Fabric fabric = new Fabric.Builder(this)
.kits(new Crashlytics())
.debuggable(true)
.build();
Fabric.with(fabric);
setContentView(R.layout.activity_main);
getUserList();
register=findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, LoginSys.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
getPreference();
}
//Ovo je klasa koju smo sami gore kreirali kako bi mogli odrediti boje od pozadine kroz Settings
//Tu još možeš i mjenjati text boju od texViewa sa metodom ||myTextView.setTextColor(0xAARRGGBB);||
//Ili ovako ||ContextCompat.getColor(context, R.color.your_color);||
private void getPreference() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
if (preferences.contains("color")) {
if (preferences.getString("color", "0").equals("1")) {
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
} else if (preferences.getString("color", "0").equals("2")) {
getWindow().getDecorView().setBackgroundColor(Color.BLACK);
} else if (preferences.getString("color","0").equals("3")){
getWindow().getDecorView().setBackgroundColor(Color.RED);
}else{
getWindow().getDecorView().setBackgroundColor(Color.MAGENTA);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.your_item_id) {
//A ovo je metoda za pozivanje i startanje preferences activity-a
Intent intent = new Intent(MainActivity.this, PreferencesScreenActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void getUserList() {
try {
APIService service = ApiClient.getRetrofit().create(APIService.class);
Call<List<User>> call = service.getUserData();
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
//Log.d("onResponse", response.message());
List<User> userList = response.body();
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter recyclerViewAdapter =
new RecyclerViewAdapter(userList);
recyclerView.setAdapter(recyclerViewAdapter);
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
}
});
}catch (Exception e) {}
}
}
So one more time,
I need code to change color of textview item of price from RecyclerViewHolder class.
Thank for all help, every good point of answer will be credited with thanks!
use color as a recyclerview constructor:
int color;
RecyclerViewAdapter recyclerViewAdapter =
new RecyclerViewAdapter(this, userList, color);
//////////////////////////////////////////////////////////////////////////
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder>{
private Context context;
public static List<UserList> userList;
private int color;
public UserAdapter(Context context, List<UserList> userList, int color){
super();
//Getting all the superheroes
this.color = color;
this.userList = userList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.colorText.setText(mColorText.setText);
//here you will change the text color from mainactivity
// this change color
holder.colorText.setTextColor(ContextCompat.getColor(context,color));
}
#Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView colorText;
public ViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
}
}
I didn't really get into your code but I think you could create another TextView in your .xml file with an id like "priceColored" or something.
When you will want to change the price's color, you simply do:
price = itemView.findViewById(R.id.priceColored);
The TextView with the id priceColored will have the color you want to use. If you need to figure out how to create a textview of a certain color in android, you can find it very easily online.
Hope it helps,
In RecyclerViewHolder class make one public method with color arguments and that method used in mainactivity with that class object and call that public method and pass your color code.
Make below method in RecyclerViewHolder.
public void changeColor(int color){
price.setTextColor(color)
}
and call this method in mainActivity
RecyclerViewHolderobject.changeColor(Color.BLACK)

Cant go to fragment from adapter

I have activity, and this activity is drawable menu.
inside drawable, i include some fragment, where in my fragment i show some data with adapter. i try to make action when data is clicked, then it will go to other fragment. oh yeah, i try to send some value from my adapter to fragment to.
please help me
this is my adapter..
package com.skripsi.anna.adapter;
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.TextView;
import com.skripsi.anna.MenuEdit;
import com.skripsi.anna.R;
import com.skripsi.anna.model.ModelMenu;
import java.util.List;
/**
* Created by gandhi on 6/11/17.
*/
public class BarangEditor extends RecyclerView.Adapter<BarangEditor.ViewHolder> {
private List<ModelMenu> modelMenus;
private Context context;
public BarangEditor(List<ModelMenu> modelMenus){
this.modelMenus = modelMenus;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView namaBarang,hargaBarang;
public ViewHolder(View v) {
super(v);
namaBarang = (TextView) v.findViewById(R.id.nama_barang);
hargaBarang = (TextView) v.findViewById(R.id.harga);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
ModelMenu modelMenu = modelMenus.get(position);
MenuEdit menuEdit = new MenuEdit();
menuEdit.newInstance(modelMenu.getIdMenu(),modelMenu.getNamaMenu(),modelMenu.getHargaMenu());
// i want to send this value to fragment
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_barang_editor, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ModelMenu modelMenu = modelMenus.get(position);
holder.hargaBarang.setText(modelMenu.getHargaMenu());
holder.namaBarang.setText(modelMenu.getNamaMenu());
}
#Override
public int getItemCount() {
return modelMenus.size();
}
}
And it is my fragment
package com.skripsi.anna;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MenuEdit extends Fragment {
private String idMenu,namaMenu,hargaMenu;
private OnFragmentInteractionListener mListener;
public MenuEdit() {
}
public static MenuEdit newInstance(String idMenu, String namaMenu, String hargaMenu) {
MenuEdit fragment = new MenuEdit();
Bundle args = new Bundle();
args.putString("idMenu", idMenu);
args.putString("namaMenu", namaMenu);
args.putString("hargaMenu",hargaMenu);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
idMenu = getArguments().getString("idMenu");
namaMenu = getArguments().getString("namaMenu");
hargaMenu = getArguments().getString("hargaMenu");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_edit, container, false);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
i have try this
FragmentTransaction ft = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
but it make my app FC
and it is not work
i using this code and i hope work for you
public void addFragment(Fragment fragment, boolean addToBackStack, String tag)
{
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (addToBackStack)
{
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, fragment, tag);
try{
ft.commitAllowingStateLoss();
}catch (Exception e){
}
}
[SOLVED]
i try put this code on my adapter
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, menuEdit).commit();
but it say cant resolve getSupportFragment
so its the real problem, and for solution, i write some code like this
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContent, menuEdit).addToBackStack(null).commit();
and its work
its my full adapter now
package com.skripsi.anna.adapter;
import android.os.Bundle;
import android.support.v4.app.FragmentController;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.skripsi.anna.MenuEdit;
import com.skripsi.anna.R;
import com.skripsi.anna.model.ModelMenu;
import java.util.List;
/**
* Created by gandhi on 6/11/17.
*/
public class BarangEditor extends RecyclerView.Adapter<BarangEditor.ViewHolder> {
private List<ModelMenu> modelMenus;
public BarangEditor(List<ModelMenu> modelMenus){
this.modelMenus = modelMenus;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView namaBarang,hargaBarang;
public ViewHolder(View v) {
super(v);
namaBarang = (TextView) v.findViewById(R.id.nama_barang);
hargaBarang = (TextView) v.findViewById(R.id.harga);
v.setOnClickListener(new View.OnClickListener() {
public FragmentController appCompatActivity;
#Override
public void onClick(View v) {
int position = getAdapterPosition();
ModelMenu modelMenu = modelMenus.get(position);
MenuEdit menuEdit = new MenuEdit();
Bundle bundle = new Bundle();
bundle.putString("idMenu",modelMenu.getIdMenu());
menuEdit.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContent, menuEdit).addToBackStack(null).commit();
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_barang_editor, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ModelMenu modelMenu = modelMenus.get(position);
holder.hargaBarang.setText(modelMenu.getHargaMenu());
holder.namaBarang.setText(modelMenu.getNamaMenu());
}
#Override
public int getItemCount() {
return modelMenus.size();
}
}

How to add icons to items in listview in android navigation drawer

Iam beginner in Android Development , so i followed tutorial from http://www.androidhive.info/2015/04/android-getting-started-with-material-design/ , i would like to add icons to listview in android navigation drawerm, plz help me in fixing this
here is my nav_drawer_row.xml source :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="30dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textSize="15dp"
android:textStyle="bold" />
</RelativeLayout>
Here is my NavigationDrawerAdapter.java source :
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.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by Ravi Tamada on 12-03-2015.
*/
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
}
Here is FragmentDrawer.java source:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import info.androidhive.materialdesign.R;
import info.androidhive.materialdesign.adapter.NavigationDrawerAdapter;
import info.androidhive.materialdesign.model.NavDrawerItem;
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
You need to make a custom layout for your Navigation Drawer. Then you will be able to add images and even expandable lists. Here is a tutorial for you.
http://www.tutecentral.com/android-custom-navigation-drawer
You can set drawableLeft property in xml.
Or you can set programatically.
You can use any of the following methods for setting the Drawable on TextView:
1- setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)
2- setCompoundDrawables(Left_Drawable, Top_Drawable, Right_Drawable, Bottom_Drawable)
And to get drawable from resources you can use:
getResources().getDrawable(R.drawable.your_drawable_id);

RecyclerView not updating when database changes

I am using Sugar ORM to implement Data Persistence in my app. I am displaying my database contents in a RecyclerView. The problem is SugarORM doesn't have loaders so there is no way to refresh the RecyclerView with fresh data after adding/deleting an entry to the database. I have worked around the issue for phones by reinitializing my Adapter in OnResume() and displaying it in the Recycler View. But for Tablets, the logic isn't working because the Fragment never goes to OnPause.
I need to update my the RecyclerView in my FavouritesFragment when I remove an entry in my DetailsFragment
Here's the Github link https://github.com/Hackertronix/Project-Motion/tree/Stage_2
Here's the code for both fragments
FavoritesFragment.java
package com.execube.genesis.views.fragments;
import android.app.ActivityOptions;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.utils.API;
import com.orm.SugarRecord;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Prateek Phoenix on 6/7/2016.
*/
public class FavouritesFragment extends Fragment {
public static final String TAG= "FAVOURITES";
private static final String FAVOURITE_MOVIES_ARRAY = "favourite_movies";
private List<Movie> mMovies=new ArrayList<>();
private RecyclerView mFavouritesRecyclerView;
ArrayList<Movie> moviesArrayList;
private FavouritesAdapter mAdapter;
private TabLayout mTabLayout;
public FavouritesFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
Log.v(TAG,"In OnCreate()");
super.onCreate(savedInstanceState);
}
#Override
public void onPause() {
Log.v(TAG,"OnPause() Called");
super.onPause();
}
#Override
public void onResume() {
/* Sugar ORM does not have a Loader
so to refresh the recyclerview adapter I am reinitializing it*/
Log.v(TAG,"OnResume() Called");
mMovies=Movie.listAll(Movie.class);
mAdapter=new FavouritesAdapter();
mFavouritesRecyclerView.setAdapter(mAdapter);
mFavouritesRecyclerView.invalidate();
super.onResume();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG,"In OnCreateView()");
View view = inflater.inflate(R.layout.fragment_favourites,container,false);
mFavouritesRecyclerView=(RecyclerView)view.findViewById(R.id.favourites_recyclerview);
if(savedInstanceState!=null&&savedInstanceState.containsKey(FAVOURITE_MOVIES_ARRAY))
{
Log.v(TAG,"Restoring State");
mMovies=savedInstanceState.getParcelableArrayList(FAVOURITE_MOVIES_ARRAY);
}
else {
mMovies= Movie.listAll(Movie.class);
}
if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mFavouritesRecyclerView.setLayoutManager(new
GridLayoutManager(getActivity(), 2));
}
else{
mFavouritesRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
}
mAdapter= new FavouritesAdapter();
mFavouritesRecyclerView.setAdapter(mAdapter);
mFavouritesRecyclerView.invalidate();
return view;
}
private class FavouritesHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private ImageView mPosterImageView;
private Movie mMovie;
public FavouritesHolder(View itemView) {
super(itemView);
mPosterImageView=(ImageView)itemView.findViewById(R.id.poster);
itemView.setOnClickListener(this);
}
public void bind(Movie movie)
{
mMovie=movie;
Picasso mPicasso= Picasso.with(getActivity());
mPicasso.setIndicatorsEnabled(true);
mPicasso.load(API.IMAGE_URL+API.IMAGE_SIZE_500+mMovie.getPosterPath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(mPosterImageView);
}
#Override
public void onClick(View v) {
ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(getActivity(),mPosterImageView,"posterImage");
((openDetailsListener)getActivity()).openDetails(mMovie,options);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
moviesArrayList=new ArrayList<>(mMovies);
Log.v(TAG,"Saving State");
outState.putParcelableArrayList(FAVOURITE_MOVIES_ARRAY,moviesArrayList);
super.onSaveInstanceState(outState);
}
private class FavouritesAdapter extends RecyclerView.Adapter<FavouritesHolder>
{
#Override
public FavouritesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.movie_item,parent,false);
return new FavouritesHolder(view);
}
#Override
public void onBindViewHolder(FavouritesHolder holder, int position) {
Movie movie= mMovies.get(position);
holder.bind(movie);
}
#Override
public int getItemCount() {
return mMovies.size();
}
}
public interface openDetailsListener{
void openDetails(Movie movie,ActivityOptions options);
}
}
DetailsFragment.java
package com.execube.genesis.views.fragments;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.model.Review;
import com.execube.genesis.model.Trailer;
import com.execube.genesis.utils.API;
import com.execube.genesis.utils.JSONParser;
import com.execube.genesis.utils.OkHttpHandler;
import com.orm.SugarRecord;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
import static com.execube.genesis.R.drawable.ic_favorite_black_24dp;
/**
* Created by Prateek Phoenix on 4/30/2016.
*/
public class DetailsFragment extends Fragment {
private static final String TAG = "DETAILS";
private static final int DEFAULT_NUM_COLORS = 5;
private Movie mMovie;
private Movie entry,tempMovie;
private List<Movie> movie;
public Intent intent;
private TextView mDetailTitle;
private TextView mReleaseDate;
private TextView mOverview;
private TextView mOverviewHeader;
private TextView mReviesHeader;
private TextView mTrailersHeader;
private ImageView mBackdrop;
private Toolbar mToolbar;
private RatingBar mRatingBar;
private ArrayList<Review> mReviews=new ArrayList<>();
private ArrayList<Trailer> mTrailers=new ArrayList<>();
public static final String MOVIE_REVIEWS_ARRAY ="movie_details";
private static final String MOVIE_TRAILERS_ARRAY = "movie_reviews";
private Typeface fontBold;
private Typeface fontMediumLight;
private Typeface fontMedium;
private RecyclerView mReviewRecyclerView;
private RecyclerView mTrailerRecyclerView;
private ProgressBar mReviewsProgressbar;
private ProgressBar mTrailersProgressbar;
private CoordinatorLayout mCoordinatorLayout;
private CardView mReviewsCardView;
private FloatingActionButton mFloatingActionButton;
private ReviewsAdapter mReviewAdapter;
private int NumOfReviews;
private TrailersAdapter mTrailerAdapter;
private String id;
private boolean isFav;
public DetailsFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.v(TAG,"Saving state in onSaveInstanceState");
outState.putParcelableArrayList(MOVIE_REVIEWS_ARRAY,mReviews);
outState.putParcelableArrayList(MOVIE_TRAILERS_ARRAY,mTrailers);
super.onSaveInstanceState(outState);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
mBackdrop = (ImageView) view.findViewById(R.id.details_poster);
mDetailTitle = (TextView) view.findViewById(R.id.detail_title_text);
mReleaseDate = (TextView) view.findViewById(R.id.release_date);
mOverview = (TextView) view.findViewById(R.id.overview);
mOverviewHeader = (TextView) view.findViewById(R.id.overview_header);
mReviesHeader=(TextView)view.findViewById(R.id.review_header);
mTrailersHeader=(TextView)view.findViewById(R.id.trailer_header);
mRatingBar = (RatingBar) view.findViewById(R.id.movie_rating);
mCoordinatorLayout=(CoordinatorLayout)view.findViewById(R.id.coordinator_layout);
mReviewRecyclerView= (RecyclerView)view.findViewById(R.id.review_recycler_view);
mTrailerRecyclerView=(RecyclerView)view.findViewById(R.id.trailer_recycler_view);
mReviewsProgressbar=(ProgressBar)view.findViewById(R.id.reviews_progressbar);
mTrailersProgressbar=(ProgressBar)view.findViewById(R.id.trailers_progressbar);
mFloatingActionButton=(FloatingActionButton)view.findViewById(R.id.fab);
mReviewsCardView= (CardView) view.findViewById(R.id.reviews_card);
intent = getActivity().getIntent();
Bundle bundle=getArguments();
mMovie=bundle.getParcelable("PARCEL");
tempMovie=mMovie;
id = String.valueOf(mMovie.getMovieId());
checkFav();
mFloatingActionButton.show();
assert mMovie != null;
//PREPPING THE URL FOR QUERY
String reviewQueryUrl = API.MOVIES_BASE_URL + id + "/reviews" + API.API_KEY;
String trailerQueryUrl = API.MOVIES_BASE_URL + id + "/videos" + API.API_KEY;
mDetailTitle.setText(mMovie.getTitle());
mReleaseDate.setText(mMovie.getReleaseDate());
mRatingBar.setProgress((int) mMovie.getVoteAverage());
mOverview.setText(mMovie.getOverview());
if (Build.VERSION.SDK_INT != 21) {
fontBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Bold.ttf");
fontMedium = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Medium.ttf");
fontMediumLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Book_.ttf");
mDetailTitle.setTypeface(fontBold);
mReleaseDate.setTypeface(fontMedium);
mOverview.setTypeface(fontMediumLight);
mOverviewHeader.setTypeface(fontBold);
mReviesHeader.setTypeface(fontBold);
mTrailersHeader.setTypeface(fontBold);
}
//FETCHING JSON HERE
if(savedInstanceState!=null&&savedInstanceState.containsKey(MOVIE_REVIEWS_ARRAY))
{
Log.v(TAG,"Restoring from bundle");
mReviews=savedInstanceState.getParcelableArrayList(MOVIE_REVIEWS_ARRAY);
mTrailers=savedInstanceState.getParcelableArrayList(MOVIE_TRAILERS_ARRAY);
mReviewsProgressbar.setVisibility(View.GONE);
mTrailersProgressbar.setVisibility(View.GONE);
}
else {
OkHttpHandler reviewsHandler = new OkHttpHandler(reviewQueryUrl, reviewsCallback);
reviewsHandler.fetchData();
OkHttpHandler trailersHandler= new OkHttpHandler(trailerQueryUrl, trailersCallback);
trailersHandler.fetchData();
}
Picasso.with(getActivity()).load(API.IMAGE_URL + API.IMAGE_SIZE_500 + mMovie.getPosterPath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(mBackdrop);
getActivity().startPostponedEnterTransition();
mReviewRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mReviewAdapter= new ReviewsAdapter();
mReviewRecyclerView.setAdapter(mReviewAdapter);
LinearLayoutManager layoutmanager= new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
mTrailerRecyclerView.setLayoutManager(layoutmanager);
mTrailerAdapter= new TrailersAdapter();
mTrailerRecyclerView.setAdapter(mTrailerAdapter);
return view;
}
private void checkFav() {
movie=new ArrayList<>();
movie=SugarRecord.find(Movie.class,"m_id=?",id);
if(movie.size()==0)
{
Log.v(TAG,"Null");
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
}
else {
Log.v(TAG,"NOT Null");
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_black_24dp);
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movie=SugarRecord.find(Movie.class,"m_id=?",id);
if(movie.size()>0)
{
entry = movie.get(0);
entry.delete();
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
Snackbar snackbar = Snackbar.make(mCoordinatorLayout,"Movie removed from Favourites!!",Snackbar.LENGTH_SHORT);
View view= snackbar.getView();
TextView textView = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
else
{
entry = tempMovie;
entry.save();
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_black_24dp);
Snackbar snackbar = Snackbar.make(mCoordinatorLayout,"Movie added to Favourites!!",Snackbar.LENGTH_SHORT);
View view= snackbar.getView();
TextView textView = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
});
}
//OKHTTP CALLBACK FOR NETWORK CALL
private okhttp3.Callback reviewsCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String JSONData= response.body().string();
JSONObject jsonObject = new JSONObject(JSONData);
NumOfReviews = jsonObject.getInt("total_results");
JSONParser parser = new JSONParser();
Log.v(TAG,JSONData);
mReviews=parser.parseReviews(JSONData);
} catch (JSONException e) {}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(mReviewAdapter!=null)
{
mReviewsProgressbar.setVisibility(View.GONE);
mReviewAdapter.notifyDataSetChanged();
}
}
});
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (NumOfReviews==0)
{
mReviewsCardView.setVisibility(View.INVISIBLE);
}
}
});
}
};
private okhttp3.Callback trailersCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String json1= response.body().string();
JSONParser parser= new JSONParser();
Log.v(TAG, json1);
mTrailers = parser.parseTrailers(json1);
} catch (JSONException e) {}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(mTrailerAdapter!=null)
{
mTrailersProgressbar.setVisibility(View.GONE);
mTrailerAdapter.notifyDataSetChanged();
}
}
});
}
};
private class ReviewViewHolder extends RecyclerView.ViewHolder{
private TextView mAuthorText;
private TextView mReviewText;
private Review mReview;
public ReviewViewHolder(View itemView) {
super(itemView);
mAuthorText= (TextView) itemView.findViewById(R.id.author_textview);
mReviewText= (TextView) itemView.findViewById(R.id.review_textview);
}
public void bind(Review review)
{
mReview= review;
mAuthorText.setText(mReview.getAuthor());
mReviewText.setText(mReview.getContent());
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
{
mAuthorText.setTypeface(fontBold);
mReviewText.setTypeface(fontMediumLight);
}
}
}
private class ReviewsAdapter extends RecyclerView.Adapter<ReviewViewHolder>{
#Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.review_item,parent,false);
return new ReviewViewHolder(view);
}
#Override
public void onBindViewHolder(ReviewViewHolder holder, int position) {
Review review= mReviews.get(position);
holder.bind(review);
}
#Override
public int getItemCount() {
if(mReviews==null)
{ return 0;}
else
{return mReviews.size();}
}
}
private class TrailerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mTrailerThumbnail;
private Trailer mTrailer;
public TrailerViewHolder(View itemView) {
super(itemView);
mTrailerThumbnail=(ImageView)itemView.findViewById(R.id.trailer_thumbnail);
itemView.setOnClickListener(this);
}
public void bind(Trailer trailer)
{
mTrailer=trailer;
Picasso picasso =Picasso.with(getActivity());
picasso.setIndicatorsEnabled(true);
picasso.load(API.YOUTUBE_THUMBNAIL_URL+mTrailer.getKey()+API.THUMBNAIL_QUALITY)
.into(mTrailerThumbnail);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(API.YOUTUBE_TRAILER_URL+mTrailer.getKey()));
startActivity(intent);
}
}
private class TrailersAdapter extends RecyclerView.Adapter<TrailerViewHolder>
{
#Override
public TrailerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.trailer_item,parent,false);
return new TrailerViewHolder(view);
}
#Override
public void onBindViewHolder(TrailerViewHolder holder, int position) {
Trailer trailer= mTrailers.get(position);
holder.bind(trailer);
}
#Override
public int getItemCount() {
return mTrailers.size();
}
}
}
You can use an Interface to communicate between Fragments (Here's a question I asked an year ago and the accepted answer was really easy to understand).
Then, you need to call mAdapter.notifyDataSetChanged() in your callBack method.
I propose one way to solve this.
class TabletActivity extends Activity implements DetailFragment.Callback {
public void onCreate(Bundle savedInstanceState){
//Initialise fragments
}
void onItemDelete(){
// find the Master Fragment using FragmentManager;
MasterFragment f = (MasterFragment) getFragmentManager().findFragmentById();
if (f != null){
f.somethingHasChanged();
}
}
}
class DetailFragment extends Fragment {
private Callback callback;
public onAttach(Context context){
this.callback = (Context) context;
}
public void onViewCreated(View v, Bundle b){
Button b;
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
callback.onItemDelete();
}
)
}
public interface Callback {
void onItemDelete();
}
}
class MasterFragment extends Fragment {
public void somethingHasChanged(){
adapter.notifyDatasetChanged();
}
}
DetailFragment is where we initiate the changes, MasterFragment is consuming the changes. That communication is don't via the Activity. I personally don't recommend notifyAdapterChanges in OnResume() as you proposed because there is no guarantee that onResume will be call right after the changes in you data has been made.
Read more at:
https://developer.android.com/training/basics/fragments/communicating.html

Categories