I got a problem with the date of my SharedPreferences. I am using 5 Fragment wher you can dynamically add item to a RecyclerView. The Problem is that when ever I save my data on a particular fragment and reload the app the value that has been saved loads into every single Fragment of mine.It actually save the data to the Fragment it is on.I am using Gson to save my ArrayList of items
This is my Fragment (Fragment0 from 5 in total, the others are just copied and refactored)
package com.example.barryblack;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FragmentPage0 extends Fragment {
private ExampleAdapter mAdapter;
private EditText editTask;
ArrayList<MyItem> items;
private Button insertbtn;
private Button stateButton;
private TextView taskText;
private String task;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment0, container, false);
loadData();
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(500);
mAdapter = new ExampleAdapter(items);
recyclerView.setAdapter(mAdapter);
taskText = view.findViewById(R.id.tv_country);
insertbtn = view.findViewById(R.id.button_insert);
editTask = view.findViewById(R.id.editTask);
stateButton = view.findViewById(R.id.tv_button);
insertbtn.setEnabled(false);
editTask.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String taskInput = editTask.getText().toString().trim();
insertbtn.setEnabled(!taskInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
task = editTask.getText().toString().trim();
}
});
insertbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
SaveData();
editTask.setText(null);
}
});
return view;
}
private void SaveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("task list", json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<MyItem>>() {
}.getType();
items = gson.fromJson(json, type);
if (items == null) {
items = new ArrayList();
}
}
public void InsertItem() {
items.add(new MyItem(task, stateButton));
mAdapter.notifyItemInserted(items.size());
}
private void CreateExampleList() {
items = new ArrayList<MyItem>();
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder
viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
items.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
SaveData();
}
};
}
This is my Adapter. I think the problem is inside the OnCreateViewHolder but im not quiet sure
package com.example.barryblack;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<MyItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
private EditText topicName;
public Button mButton;
private int clicks = 1;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TOPIC = "topic";
public static final String CLICKS = "clicks";
public ExampleViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_country);
mButton = itemView.findViewById(R.id.tv_button);
topicName = itemView.findViewById(R.id.editText);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicks++;
if (clicks % 2 == 0) {
mButton.setBackgroundResource(R.drawable.button_green);
}else
mButton.setBackgroundResource(R.drawable.button_red);
}
});
}
}
public ExampleAdapter(ArrayList<MyItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
MyItem currentItem = mExampleList.get(position);
holder.mTextView.setText(currentItem.getTaskText());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Use this for your fragments. So every fragment has his own SharedPreferences
private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";
private static final String SHARED_PREFS_FRAGMENT_B = "fragmentB";
...
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A , MODE_PRIVATE);
Related
I need to open another activity from a custom adapter, just like a list and then when I click on that, it will take to another activity and get a data from database and show it in the text view,
the problem is in SearchAdapter.java in the context.startActivity(intent);
here's my searchAdapter.java
package Adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
//import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.manualdiagnosiskeperawatan.R;
import com.example.manualdiagnosiskeperawatan.isiDiagnosis;
import java.util.List;
import Model.Daftar;
class SearchViewHolder extends RecyclerView.ViewHolder{
public TextView judul, diagnosis;
public SearchViewHolder(View itemView) {
super(itemView);
judul = itemView.findViewById(R.id.judul);
diagnosis = itemView.findViewById(R.id.textViewIsi);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder>
{
private Context context;
private List<Daftar> data;
public SearchAdapter(Context context, List<Daftar> data) {
this.context = context;
this.data = data;
}
#Override
public SearchViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.layout_item,parent,false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(final SearchViewHolder holder, final int position)
{
holder.judul.setText(data.get(position).getJudul());
//open activity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, data.get(position).getDiagnosis(),Toast.LENGTH_SHORT).show();
//this code, isn't working
Intent intent = new Intent(context, isiDiagnosis.class);
intent.putExtra("did",data.get(position).getDid());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
}
and here is my isiDiagnosis.java which will be opened when I clicked the list from the SearchAdapter.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
import Model.Daftar;
public class isiDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
List<Daftar> daftars = new ArrayList<>();
private TextView judul, diagnosis;
private String DID = "judul";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_isi_diagnosis);
DID = getIntent().getStringExtra("judul");
database = new Database(this);
diagnosis = (TextView) findViewById(R.id.textViewIsi);
//init DB
loadData(DID);
}
private void loadData(String did) {
//i don't really know how to code, just see from the youtube, so i made this myself
// database.getDiagnosis();
// String diagnosis = daftars.get(database.getDiagnosis());
// database.getDiagnosis(diagnosis.setText());
}
}
here's my searchDiagnosis.java
package com.example.manualdiagnosiskeperawatan;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.ListViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Adapter;
import android.widget.ListView;
import com.mancj.materialsearchbar.MaterialSearchBar;
import java.util.ArrayList;
import java.util.List;
import Adapter.SearchAdapter;
import Database.Database;
public class searchDiagnosis extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
Database database;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
#Override
protected void onStart() {
super.onStart();
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_diagnosis);
//init view
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar =(MaterialSearchBar) findViewById(R.id.search_bar);
//init DB
database = new Database(this);
//Setup search bar
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for(String search:suggestList){
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled) {
// recyclerView.setAdapter(adapter);
//if close Search, just restore default
adapter = new SearchAdapter(getBaseContext(),database.getDaftar());
recyclerView.setAdapter(adapter);
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//Init adapter default set all result
adapter = new SearchAdapter(this,database.getDaftar());
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getDataByJudul(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getJudul();
materialSearchBar.setLastSuggestions(suggestList);
}
}
here's my Daftar.class
package Model;
public class Daftar {
public int id;
public String did, judul, diagnosis;
public Daftar(int id,String did, String judul, String diagnosis) {
this.id = id;
this.did = did;
this.judul = judul;
this.diagnosis = diagnosis;
}
public Daftar() {
}
public int getId() {
return id;
}
public String getDid() {
return did;
}
public void setDid(String did) {
this.did = did;
}
public void setId(int id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
}
Look I don't know what kind of database is this, but I know that you are not receiving the intent extra correctly:
In your isiDiagnosis:
............
//get the did like this
DID = getIntent().getStringExtra("did");
.......
loadData(DID);
//loading the data is up to you according to the database
private void loadData(String did) {.........}
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
}
});
I'm working on an employee attendance attendance applicaion, for that I'm listing employee namelist from my MySQL database to android RecyclerView. Everything is working fine. But what I actually wanted is, I want to update my attendance table with the CheckBox values, my table contains 3 columns id,emp_id,emp_attn, If the checkbox is checked for an employee, the app should post it as checked ! So how can i identify each checkbox in my recyclerview,
MyAdapter.java
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.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Akshay N Shaju on 10/20/2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private List<Listitems> listitemses;
private Context context;
public MyAdapter(List<Listitems> listitemses, Context context) {
this.listitemses = listitemses;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Listitems listitem = listitemses.get(position);
holder.CbHead.setText(listitem.getHead());
holder.textViewDesc.setText(listitem.getDesc());
holder.CbHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,listitem.getHead(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return listitemses.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public CheckBox CbHead;
public TextView textViewDesc;
public LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
CbHead = (CheckBox) itemView.findViewById(R.id.CbHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDisc);
linearLayout = (LinearLayout) itemView.findViewById(R.id.LinearLyout1);
}
}
}
MainActivity.java
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "https://xxxxxxx.com/sample.json";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Listitems> listitemses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listitemses = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("employee");
for(int i=0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
Listitems item = new Listitems(
o.getString("name"),
o.getString("id"),
o.getString("image")
);
listitemses.add(item);
}
adapter = new MyAdapter(listitemses,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
ListItems.java
/**
* Created by Akshay N Shaju on 10/20/2017.
*/
public class Listitems {
private String head;
private String desc;
private String imageurl;
public Listitems(String head, String desc, String imageurl) {
this.head = head;
this.desc = desc;
this.imageurl = imageurl;
}
public String getHead() {
return head;
}
public String getDesc() {
return desc;
}
public String getImageurl() {
return imageurl;
}
}
Here in my adapter I tried an onClick Listner, which toast the employee name when checked and it worked ! but how can I get all the checkbox status and post it to my database table when save button clicked.
Store the state in your ListItem, whenever the state of the CheckBox changes:
public class Listitems {
...
public bool isChecked;
...
}
Instead of onClick, listen to the state change instead:
holder.CbHead.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listitem.isChecked = isChecked
}
});
Finally when binding, make sure to reflect the checked state of the CheckBox:
holder.CbHead.setText(listitem.getHead());
holder.CbHead.setChecked(listitem.isChecked)
You are using a recycler view so while the CheckBox is still on screen it will hold your "checked" state. However once it scrolls off screen, it will be recycled. Hence you need to store the state somewhere, your own ListItem is the best bet
I am trying to write different functionalities for my FloatingActionButton depending on the fragment that the mainActivity is currently hosting. Yet for for reason in my onClick() method, getSupportFragmentManager().findFragmentById() returns null.
I haven't seen any examples of this question implemented with a viewpager and I am curious if there is a different approach I have to take.
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
public class MainActivity extends FragmentActivity {
private Adapter mAdapter;
private ViewPager mViewPager;
private static FloatingActionButton bButton;
private static String UID;
private Intent intent;
public static String getUID(){
return UID;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new Adapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.vPager);
mViewPager.setAdapter(mAdapter);
intent = getIntent();
UID = intent.getStringExtra("uid");
bButton = (FloatingActionButton)findViewById(R.id.bButton);
bButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragContainer);
if(fragment == null){
Log.e("TAG","FRAGMENT IS NULL!!");
}
else{
Log.e("TAG","FRAGMENT IS NOT NULL!!");
}
}
});
}
}
NewsFeedFragment
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.mycompany.neighbors.R;
import com.mycompany.neighbors.SinglePost;
import java.util.ArrayList;
/**
* Created by joshua on 5/25/2016.
*/
public class NewsFeedFragment extends ListFragment implements AdapterView.OnItemClickListener{
private ListView lv;
private TextView tvUserName;
private TextView tvStatus;
private ArrayList<SinglePost> posts = new ArrayList<>();
private static final String POSTS_PATH = "MY_PATH";
private Firebase postsRef;
// private static final String FRAGMENT_POST = "post";
public void postFragment(){
Log.d("TAG", "Doing something else");
PostFragment postFragment = new PostFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragContainer,postFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onViewCreated(View v, Bundle s){
lv = getListView();
lv.setOnItemClickListener(this);
}
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_post_feed_item,parent,false);//changed
tvUserName = (TextView)v.findViewById(R.id.tvUN);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
postsRef = new Firebase(POSTS_PATH);
postsRef.addChildEventListener(new com.firebase.client.ChildEventListener() {
#Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
SinglePost post = dataSnapshot.getValue(SinglePost.class);
post.setKey(dataSnapshot.getKey());
posts.add(0, post);
if(posts.size() > 0) {
PostAdapter adapter = new PostAdapter(posts);
setListAdapter(adapter);
}else{
Toast toast = Toast.makeText(getActivity(),"No data", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
SinglePost p = ((PostAdapter) getListAdapter()).getItem(position);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
private class PostAdapter extends ArrayAdapter<SinglePost>{
public PostAdapter(ArrayList<SinglePost> singlePost){
super(getActivity(),android.R.layout.simple_list_item_1,singlePost);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_post_feed_item,null);
}
SinglePost p = getItem(position);
TextView tvUserName = (TextView)convertView.findViewById(R.id.tvUN);
tvUserName.setText(p.getUserName());
TextView tvStatus = (TextView)convertView.findViewById(R.id.tvStatus);
tvStatus.setText(p.getStatus());
return convertView;
}
}
}
I have 2 other fragments but i'll post one as an example. Here is my adapter for the viewpager.
Adapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.mycompany.neighbors.Fragments.MapFragment;
import com.mycompany.neighbors.Fragments.NewsFeedFragment;
import com.mycompany.neighbors.Fragments.ProfileFragment;
/**
* Created by joshua on 5/25/2016.
*/
public class Adapter extends FragmentPagerAdapter {
private String Fragment[] = {"Posts" , "Map" , "Profile"};
public Adapter(FragmentManager fm){
super (fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new NewsFeedFragment();
case 1:
return new MapFragment();
case 2:
return new ProfileFragment();
default:
return null;
}
}
#Override
public int getCount(){return Fragment.length;}
#Override
public CharSequence getPageTitle(int position) {
return Fragment[position];
}
}
Please check below link, It has very good explanation for your problem:
http://tamsler.blogspot.in/2011/11/android-viewpager-and-fragments-part-ii.html
Or you can try below code snippet:
1.Where you add fragment in view pager or view pager adapter:
MyFragment myFragment = MyFragment.newInstance();
mPageReferenceMap.put(index, "Some Tag");
getSupportFragmentManager().beginTransaction().add(myFragment,"Some Tag").commit();
2.To get the tag for the currently visible page, you then call:
int index = mViewPager.getCurrentItem();
String tag = mPageReferenceMap.get(index);
3.and then get the fragment page:
Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);
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