empty recycler view in Fragment - java

I have an activity that contains 2 fragments
in TriFragment.java the user entres an input and click the button Sortto sort the numbers , the input entred will be sent to the second fragment StepsFragmentto display mystepsList in a Recyclerview.
i have cheked and found that mystepsListis empty even before the user enters the data (on creating the activity) so the recyclerview is not showing anything
mainactivity
public class Sorting_activity extends AppCompatActivity implements StepsFragment.OnFragmentInteractionListener,TriFragment.TriFragmentListner{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sorting_activity);
TriFragment tri = new TriFragment();
FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.triLayout,tri ,tri.getTag())
.commit();
StepsFragment steps= new StepsFragment();
manager.beginTransaction()
.replace(R.id.stepsLayout,steps ,steps.getTag())
.commit();
}
#Override
public void onFragmentInteraction(Uri uri) { }
#Override
public void onInputsent(String input) {
StepsFragment.setTextView(input);
}
}
StepsFragment
public class StepsFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private static TextView inputEntred ;
private RecyclerView RV ;
private Handler mhandler = new Handler();
public StepsFragment() {
// Required empty public constructor
}
public static void setTextView(String textentered){
inputEntred.setText(textentered);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_steps, container, false);
inputEntred =view.findViewById(R.id.inputEntred);
String[] numberList = inputEntred.getText().toString().split(",");
final Integer[] numbers = new Integer[numberList.length];
if(numberList.length !=0){
// converting the strig array to an array of integers
for (int i = 0; i < numberList.length; i++) {
try {
numbers[i] = Integer.parseInt(numberList[i]);
}
catch (NumberFormatException e){
System.out.println("error is"+e);
}
}
SelectionSort m1 = new SelectionSort();
ArrayList<String> mystepsList = m1.steps(numbers);// returns the steps numbers
if(mystepsList.isEmpty()){
System.out.println("empty list");
}else {
for (int i = 0; i < mystepsList.size(); i++)
{
System.out.println(mystepsList.get(i));
}
}
RV =view.findViewById(R.id.RV);
final StepListAdapter adapter = new StepListAdapter() ;
RV.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
RV.setLayoutManager(llm);
adapter.setList(mystepsList);
}
return view;
}
#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");
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
adapter
public class StepListAdapter extends RecyclerView.Adapter<StepListAdapter.StepListHolder> {
private ArrayList<String> etapes_list = new ArrayList<String>();
#NonNull
#Override
public StepListHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new StepListHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.log_item,parent,false));
}
#Override
public void onBindViewHolder(#NonNull StepListHolder holder, int position) {
holder.etapes.setText(etapes_list.get(holder.getAdapterPosition()));
}
#Override
public int getItemCount() {
return etapes_list.size();
}
public void setList(ArrayList<String> etapes_list ){
this.etapes_list= etapes_list;
notifyDataSetChanged();
}
#Override
public long getItemId(int position) {
return (null != etapes_list ? etapes_list.size() : 0);
}
public class StepListHolder extends RecyclerView.ViewHolder {
TextView etapes ;
public StepListHolder(#NonNull View itemView) {
super(itemView);
etapes =itemView.findViewById(R.id.txt_log);
}
}
}

Because you see you are setting a recyclerView in onCreateView method of Stepsfragment, this means your computation is done when fragment is created and not when you actully press the sort button.
modify your fragment this way and your recyclerView will works fine.
package com.example;
public class StepsFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private static TextView inputEntred ;
private RecyclerView RV ;
private Handler mhandler = new Handler();
public StepsFragment() {
// Required empty public constructor
}
public static void setTextView(String textentered){
inputEntred.setText(textentered);
//Set Your recyclerView Here.
String[] numberList = inputEntred.getText().toString().split(",");
final Integer[] numbers = new Integer[numberList.length];
if(numberList.length !=0){
// converting the strig array to an array of integers
for (int i = 0; i < numberList.length; i++) {
try {
numbers[i] = Integer.parseInt(numberList[i]);
}
catch (NumberFormatException e){
System.out.println("error is"+e);
}
}
SelectionSort m1 = new SelectionSort();
ArrayList<String> mystepsList = m1.steps(numbers);// returns the steps numbers
if(mystepsList.isEmpty()){
System.out.println("empty list");
}else {
for (int i = 0; i < mystepsList.size(); i++)
{
System.out.println(mystepsList.get(i));
}
}
final StepListAdapter adapter = new StepListAdapter() ;
RV.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
RV.setLayoutManager(llm);
adapter.setList(mystepsList);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_steps, container, false);
inputEntred =view.findViewById(R.id.inputEntred);
RV =view.findViewById(R.id.RV);
return view;
}
#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");
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
and yes try to avoid making method static for setting data in Fragment.

Related

How to load data into recyclerView

In my application i want get some data from server and show into recyclerView. For application architecture i used MVP
I wrote below codes, but after loaded data from server, not show any data into recyclerView!
I used debug mode and show me data in this break point
public void add(List<DataItem> list) {
list.addAll(list);
notifyDataSetChanged();
}
but not show me data into recyclerView!
My Activity codes :
public class ListFragment extends Fragment implements ActiveTestsContract.View {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_tester_active_tests, container, false);
//Initialize
init();
//User token log
if (!App.isEmptyString(App.getPrefs("JWT")) || !App.getPrefs("JWT").equals(ConstKeys.EMPTY)) {
userToken = App.getPrefs("JWT");
}
//Load data
getData();
return view;
}
#Override
public void updateTestsList(Data data, int page) {
testerDashboard_emptyLay.setVisibility(View.GONE);
activeTests_pullToLoader.setVisibility(View.VISIBLE);
//Get lasted page
if (page == data.getLastPage()) {
isHasLoadedAll = true;
activeTests_pullToLoader.setComplete();
}
adapter.add(data.getData());
//Complete items
isLoading = false;
nextPage = page + 1;
activeTests_pullToLoader.setComplete();
}
#Override
public void init() {
context = getActivity();
handler = new Handler(Looper.getMainLooper());
testsPresenter = new ActiveTestsPresenter(this, 3);
testerDashboard_loader = view.findViewById(R.id.testerDashboard_loader);
activeTests_pullToLoader = view.findViewById(R.id.activeTests_pullToLoader);
testerDashboard_emptyLay = view.findViewById(R.id.testerDashboard_emptyLay);
emptyLayout_editProfileBtn = view.findViewById(R.id.emptyLayout_editProfileBtn);
layoutManager = new LinearLayoutManager(context);
recyclerView = activeTests_pullToLoader.getRecyclerView();
//Adapter
adapter = new TesterActiveRecyclerAdapter(activeModel, context);
//Init recycler and adapter
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
activeTests_pullToLoader.setColorSchemeResources(R.color.colorPrimary);
}
private void getData() {
activeTests_pullToLoader.isLoadMoreEnabled(true);
activeTests_pullToLoader.setPullCallback(new PullCallback() {
#Override
public void onLoadMore() {
isLoading = true;
//Call api
testsPresenter.testsListResponse(App.recipesApi, userToken, nextPage);
}
#Override
public void onRefresh() {
adapter.clear();
isHasLoadedAll = false;
isLoading = true;
//Call api
testsPresenter.testsListResponse(App.recipesApi, userToken, 1);
}
#Override
public boolean isLoading() {
return isLoading;
}
#Override
public boolean hasLoadedAllItems() {
return isHasLoadedAll;
}
});
activeTests_pullToLoader.initLoad();
}
Adapter codes:
public class TesterActiveRecyclerAdapter extends RecyclerView.Adapter<TesterActiveRecyclerAdapter.ViewHolder> {
private List<DataItem> list;
private Context context;
public TesterActiveRecyclerAdapter(List<DataItem> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_tester_test_list, parent, false);
return new ViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
DataItem item = list.get(position);
//Name
holder.txt_name.setText(item.getTitle());
//Conditions
if (!App.isEmptyString(item.getOs()) && !App.isEmptyString(item.getType()) && !App.isEmptyString(item.getBrowser())) {
holder.txt_condition.setText(item.getType() + " | " + item.getOs() + " | " + item.getBrowser());
}
//Button actions
holder.setState(item.getState(), position);
//Price
holder.rowTests_priceTxt.setText(item.getPrice() + " Dollar");
//Animate items
Animation animation = AnimationUtils.loadAnimation(App.context,
(position > list.size() - 1) ? R.anim.down_from_top : R.anim.up_from_bottom);
holder.itemView.startAnimation(animation);
Toast.makeText(context, ""+list.get(0).getId(), Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return list.size();
}
public void add(List<DataItem> list) {
list.addAll(list);
notifyDataSetChanged();
}
public void clear() {
list.clear();
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder {
private ViewGroup root;
private TextView txt_name, txt_value, txt_condition, rowTests_priceTxt;
private RoundTextView rowTests_button;
ViewHolder(View view) {
super(view);
root = (ViewGroup) view;
txt_name = view.findViewById(R.id.txtTestListTitle);
txt_value = view.findViewById(R.id.txtTestListSublist);
txt_condition = view.findViewById(R.id.txtTestListSublist2);
rowTests_priceTxt = view.findViewById(R.id.rowTests_priceTxt);
rowTests_button = view.findViewById(R.id.rowTests_button);
}
}
How can i fix it?
You are adding data again in the same list passed in the parameter. Try to replace the below code
public void add(List<DataItem> list) {
list.addAll(list);
notifyDataSetChanged();
}
with
public void add(List<DataItem> list) {
this.list.addAll(list);
notifyDataSetChanged();
}
Clear the current list
Add the data to the adapter's list.
public void add(List<DataItem> list) {
clear();
this.list.addAll(list);
notifyDataSetChanged();
}
Your approach didn't work because you were updating the very list that you were passing in the function and not the adapter's list.
First add all data into list & than notify your adapter , after this set your adapter to recyclerview.
list.addAll(data)
adapter.notifyDataSetChanged()
val layoutManager = LinearLayoutManager(activity)
recyclerview.isNestedScrollingEnabled = false
recyclerview.layoutManager = layoutManager
recyclerview.itemAnimator = DefaultItemAnimator()
recyclerview.adapter = mAdapter

How can i pass a string value from recyclerview adapter to fragment

I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.

notifydatasetchanged() not working after onbackpressed()

My recyclerview is not updating correctly after the back button is
pressed.
The recyclerview works fine before the back button is pressed
The data is properly updated (seen in the log) but the recyclerview does not reflect the change
The purpose of the handler is to poll the database for a notification (working fine)
The notification toast is displayed everytime
I am not receiving any errors
If I can provide any other information to help do not hesitate to ask.
Main:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
recView = (RecyclerView) findViewById(R.id.recyclerViewMessages);
linearLayoutManager = new LinearLayoutManager(this) {};
linearLayoutManager.setReverseLayout(true);
recView.setLayoutManager(linearLayoutManager);
listData = (ArrayList) MessagingData.getMessageListData();
adapter = new RecyclerViewAdapterMessaging(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
final Handler h = new Handler();
final int delay = 2000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
Notify_Message_Async notify_message_async = new Notify_Message_Async(ctx);
notify_message_async.execute(NOTIFICATION, message_id);
System.out.println(global.getNotification());
if(global.getNotification()==1){
Toast.makeText(ctx, "Notified",
Toast.LENGTH_LONG).show();
try {
refresh_receive();
} catch (ExecutionException e) {
Toast.makeText(ctx, "catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (InterruptedException e) {
Toast.makeText(ctx, "catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
h.postDelayed(this, delay);
}
}, delay);
}
public void refresh_receive() throws ExecutionException, InterruptedException {
String method = "receive_message";
Receive_Live_Message_Async receive_live_message_async = new Receive_Live_Message_Async(this);
receive_live_message_async.execute(method, message_id).get();// Setup the message
adapter.setListData((ArrayList)MessagingData.getMessageListData());
adapter.notifyDataSetChanged();
global.setNotification(0);//reset notification
}
Adapter:
public class RecyclerViewAdapterMessaging extends RecyclerView.Adapter<RecyclerViewAdapterMessaging.Holder> {
private View v;
private List<List_Item_Messaging> listData;
private LayoutInflater inflater;
Global global = new Global();
private ItemClickCallback itemClickCallback;
Context context;
public interface ItemClickCallback {
void onItemClick(View v, int p);
void onSecondaryIconClick(int p);
}
public void setItemClickCallback(final ItemClickCallback itemClickCallback) {
this.itemClickCallback = itemClickCallback;
}
public RecyclerViewAdapterMessaging(List<List_Item_Messaging> listData, Context c) {
inflater = LayoutInflater.from(c);
context = c;
this.listData = listData;
}
#Override
public int getItemViewType(int position) {//0 for self... /1 for Other
List_Item_Messaging item = listData.get(position);
//ENSURE GLOBAL USERNAME NOT NULL
String other_username = item.getMessage_username();
if (other_username == null) {
((Activity) context).finish();
}
if (item.getMessage_username().trim().equals(global.getUserName())) {
System.out.println("The usernames are the same");
return 0;
} else {
System.out.println("The usernames are the NOT same");
return 1;
}
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
View view = inflater.inflate(R.layout.chat_thread, parent, false);// Self
v = view;
break;
case 1:
View view2 = inflater.inflate(R.layout.chat_thread_other, parent, false);// Not self
int width2 = global.getScreenWidth();
v = view2;
break;
}
return new Holder(v);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
List_Item_Messaging item = listData.get(position);
holder.conversation.setText(item.getMessage_conversation());
}
public void setListData(ArrayList<List_Item_Messaging> exerciseList) {
this.listData.clear();
this.listData.addAll(exerciseList);
}
#Override
public int getItemCount() {
return listData.size();
}
class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView thumbnail;
//ImageView secondaryIcon;
TextView conversation;
View message_container;
public Holder(View itemView) {
super(itemView);
conversation = (TextView) itemView.findViewById(R.id.conversation_textview);
message_container = itemView.findViewById(R.id.message_container);
message_container.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.message_container) {
itemClickCallback.onItemClick(v, getAdapterPosition());
} else {
itemClickCallback.onSecondaryIconClick(getAdapterPosition());
}
}
}
public void clearItems() {
listData.clear();
this.notifyDataSetChanged();
}
}
I have referenced the following to no solution:
notifyDataSetChanged not working on RecyclerView
smoothScrollToPosition after notifyDataSetChanged not working in android
adapter.notifyDataSetChange() not working after called from onResume()
change a little in your code
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
recView = (RecyclerView) findViewById(R.id.recyclerViewMessages);
linearLayoutManager = new LinearLayoutManager(this) {};
linearLayoutManager.setReverseLayout(true);
recView.setLayoutManager(linearLayoutManager);
// change here
if (listData != null)
listData.clear();
else listData = new <> ArrayList();
listData.addAdd((ArrayList)MessagingData.getMessageListData());
adapter = new RecyclerViewAdapterMessaging(listData, this);
recView.setAdapter(adapter);
adapter.setItemClickCallback(this);
final Handler h = new Handler();
final int delay = 2000; //milliseconds
then make a small change here
public void refresh_receive() throws ExecutionException, InterruptedException {
String method = "receive_message";
Receive_Live_Message_Async receive_live_message_async = new Receive_Live_Message_Async(this);
receive_live_message_async.execute(method, message_id).get();// Setup the message
// changing here
dataList.clear();
dataList.addAdd((ArrayList)MessagingData.getMessageListData())
adapter.setListData(dataList);
adapter.notifyDataSetChanged();
global.setNotification(0);//reset notification
}
another problem in your code, you are using receive_live_message_async AsyncTask
put your update code in onPostExecute
public class receive_live_message_async extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object o) {
// call your refresh_receive(); here
super.onPostExecute(o);
}
}
similarly when you are call receive_live_message_async.execute(); update your recyclerView in onPostExecute
#Override
protected void onPostExecute(Object o) {
dataList.clear();
dataList.addAll((ArrayList)MessagingData.getMessageListData());
adapter.notifyDataSetChanged();
super.onPostExecute(o);
}

Move from a fragment with listview adapter to new activity base on each item selected

I have done some series of research about how to make each item of the listview in fragment activity to move to another activity having getView() from swipeListadapter. The codes below contain the tab fragment containing the swipe listadapter for the list view and the setonitemclicklistener.
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
The code below is my fragment tab class
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.177.53.152/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) vi.findViewById(R.id.list);
listView.setBackgroundColor(Color.WHITE);
swipeRefreshLayout = (SwipeRefreshLayout) vi.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
//getView().setOnClickListener();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
return vi;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
switch(position) {
case 1:
intent = new Intent(getActivity().getApplicationContext(), New1.class);
startActivity(intent);
break;
case 2:
intent = new Intent(getActivity().getApplicationContext(), New2.class);
startActivity(intent);
break;
default:
intent = new Intent(getActivity().getApplicationContext(), New3.class);
startActivity(intent);
}
}
});
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
In a nutshell, whenever I click any of the item listview, the app crashes and system logcat is not giving any clue to that. I want to be able to click an item on the listview in d fragment and to be directed to a new activity. Any help will be appreciated. Thanks.

Android Tabs with same Fragment

I'm trying to implement Tabs. The Tabs will contain the exact same layout and the same fragment with only one difference - the API URL! (e.g. Trending/Newest).
My Code:
TabFragment
public class TabFragments extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
private TabHost tabHost;
private int currentTab = 0;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabhost, null);
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setOnPageChangeListener(this);
//Create correct fragment
fragments=new ArrayList<>();
fragments.add(new ItemStreamFragment());
fragments.add(new ItemStreamFragment());
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
fragments);
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.tab_1_item));
tabHost.addTab(newTab(R.string.tab_2_item));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.parseColor("#304c58"));
// tabHost.setBackgroundResource(R.drawable.tab_selector);
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final View textView = view.findViewById(android.R.id.title);
((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));
((TextView) textView).setSingleLine(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
tabHost.getTabWidget().getChildAt(i)
.findViewById(android.R.id.icon);
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;
} else {
if (view != null) {
// reduce height of the tab
view.getLayoutParams().height *= 0.77;
if (textView instanceof TextView) {
((TextView) textView).setGravity(Gravity.CENTER);
textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
}
}
tabHost.setOnTabChangedListener(TabFragments.this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int titleId) {
TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
tabSpec.setIndicator(getString(titleId));
tabSpec.setContent(new TabFactory(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
}
#SuppressWarnings("unused")
private void updateTab() {
switch (currentTab) {
case 0:
ItemStreamFragment login = (ItemStreamFragment) fragments.get(currentTab);
break;
case 1:
ItemStreamFragment register = (ItemStreamFragment) fragments
.get(currentTab);
break;
}
}
class TabFactory implements TabContentFactory {
private final Context context;
public TabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
}
TabFragmentPageAdapter
public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments
) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
And finally ItemStreamFragment
public class ItemStreamFragment extends Fragment {
private String mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getNewest/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
private final String mImages = "http://d30q95ofpjr96w.cloudfront.net/";
private ItemStream[] mObjectItem;
private int mPosition = 0;
public ItemStreamAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
mPosition = bundle.getInt("position", 0);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_itemstream, container, false);
view.setId(mPosition);
getStream(mPosition);
return view;
}
private void getStream(int position) {
switchUrl(position);
new GetRequestTask(new OnTaskCompleted() {
#Override
public void onTaskCompleted(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonResults = jsonObject.getJSONArray("results");
final int resultLength = jsonResults.length();
mObjectItem = new ItemStream[resultLength];
for (int i = 0; i < resultLength; i++) {
JSONObject item = jsonResults.getJSONObject(i);
mObjectItem[i] = new ItemStream(item.getInt("id"), item.getString("title"), mImages + "" + item.getString("thumbnail") + ".374x210." + item.getString("thumbnail_type"));
}
if (getActivity() != null) {
mAdapter = new ItemStreamAdapter(getActivity(), R.layout.list_itemstream, mObjectItem);
ListView scrollView = (ListView) getActivity().findViewById(R.id.itemstream_trend);
scrollView.setAdapter(mAdapter);
}
} catch (Exception ex) {
}
}
}).execute(mApiUrl);
}
//Needs to be tuned
private void switchUrl(int position) {
switch (position) {
case 0:
mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getTrending/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
break;
case 1:
mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getNewest/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
break;
}
}
}
And here you see what happens:
(Sry for the overlay :) )
The thing is that the first Tab is loaded with data but the second tab stays empty (it shouldn't be empty though). Not sure what is wrong here. Would be cool if you can point me in the right direction :)
For using Tabs in material design you should use TabLayout from design support library. Here is the tutorial from where you can learn this new approach.
As far as loading fragment is concern, you second fragment will be loaded with first this is complete different discussion with viewpager, so you need to have different url for each fragment and don't create fragment using new Operator. Instead create static getInstance() in Fragment class and pass the url from there and using Fragment#setArgument(Bundle) get new Fragment instance. When fragment view is created i.e in onViewCreated(...) get arguments from bundle in your case String url and call webservice which will return the respective response.
Fixed the problem:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_itemstream, container, false);
view.setId(mPosition);
getStream(mPosition,view);
return view;
}
private void getStream(int position, final View view) {
switchUrl(position);
new GetRequestTask(new OnTaskCompleted() {
#Override
public void onTaskCompleted(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonResults = jsonObject.getJSONArray("results");
final int resultLength = jsonResults.length();
mObjectItem = new ItemStream[resultLength];
for (int i = 0; i < resultLength; i++) {
JSONObject item = jsonResults.getJSONObject(i);
mObjectItem[i] = new ItemStream(item.getInt("id"), item.getString("title"), mImages + "" + item.getString("thumbnail") + ".374x210." + item.getString("thumbnail_type"));
}
if (getActivity() != null) {
mAdapter = new ItemStreamAdapter(getActivity(), R.layout.list_itemstream, mObjectItem);
ListView scrollView = (ListView) view.findViewById(R.id.itemstream_trend);
scrollView.setAdapter(mAdapter);
}
} catch (Exception ex) {
}
}
}).execute(mApiUrl);
}
Just added view to the method getStream. Now it is working! What do you think about this solution?

Categories