Fragment is not loading from the SideMenu - java

I am trying to load a fragment from the SideMenu. There is a listview in the side menu from where I want to load a Fragment in the application. There are 3 items in the list view. A code for clicking on 0th and 3rd position is working fine, but not working for 1st position ie i==1.
what i have to do for this !
package comm.design.amer.sidemenu_new;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;<code>
public class MainActivity extends AppCompatActivity {
private ArrayList<listView> Listview = new ArrayList<listView>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slideview);
//Create the ListView Items
Listview.add(new listView("page1", "enter", R.drawable.a));
Listview.add(new listView("page2", "enter", R.drawable.b));
Listview.add(new listView("page3", "enter", R.drawable.c));
Listview.add(new listView("page4", "enter", R.drawable.d));
//Call the Adapter
mycomstumerAdapter adapter = new mycomstumerAdapter(this, Listview);
ListView listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);
//make selection
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
selectItem(i);
}
});
}
public void selectItem (int i){
if (i==0){
Toast.makeText(getApplicationContext(),"bn",Toast.LENGTH_LONG).show();}
else if (i==1) {
Fragment1 fragment0 = new Fragment1();
FragmentManager fragmentm = getFragmentManager();
fragmentm.beginTransaction()
.add(R.id.linear,fragment0)
.commit();
}
else if (i==2)
finish();
}
public class mycomstumerAdapter extends BaseAdapter {
Context context;
ArrayList<listView> Listview;
public mycomstumerAdapter(Context context, ArrayList<listView> Listview) {
this.context = context;
this.Listview = Listview;
}
#Override
public int getCount() {
return Listview.size();
}
#Override
public Object getItem(int i) {
return Listview.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View view1;
if (view == null) {
LayoutInflater inflater = getLayoutInflater();
view1 = inflater.inflate(R.layout.listview, null);
} else
view1 = view;
TextView title = (TextView) view1.findViewById(R.id.textView);
TextView detail = (TextView) view1.findViewById(R.id.textView2);
ImageView imageView = (ImageView) view1.findViewById(R.id.imageView);
title.setText(Listview.get(i).Title);
detail.setText(Listview.get(i).Detail);
imageView.setImageResource(Listview.get(i).imageView);
return view1;
}
}
}

In your code I have seen you are using add fragment instead of that try with replacing the fragment. See the below code:-
Fragment1 fragment0 = new Fragment1();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.linear,fragment0);
fragmentTransaction.commit();

Related

i have applied a Setonitemclicklistener on a custom list view but it doesn't do anything when i click the items

i have tried several methods to make my items clickable i have read about focus and added the lines in my XML file Relative layout. nothing seems to help. the click listener still doesn't seem to do anything for me.. please help!!!
this is my activity list view class:
package com.example.trezah12.adminmodule;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class AdminList extends AppCompatActivity {
CustomAdapterAdmin adapterAdmin;
ArrayList<Admin> list;
ListView list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_list);
DBhandler dBhandler = new DBhandler(this);
list = new ArrayList<>();
list1 = (ListView) findViewById(R.id.listview4);
viewData();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
}
});
}
private void viewData() {
final DBhandler dbHandler3 = new DBhandler(AdminList.this);
Cursor cursor = dbHandler3.viewData();
if (cursor.getCount() == 0){
Toast toast = Toast.makeText(getApplicationContext(), "Sorry no Data Found!!", Toast.LENGTH_SHORT);
}
else {
while (cursor.moveToNext()) {
Admin admin = new Admin();
admin.setUsername(cursor.getString(0));
list.add(admin);
list1 = (ListView) findViewById(R.id.listview4);
adapterAdmin = new CustomAdapterAdmin(list, AdminList.this);
list1.setAdapter(adapterAdmin);
}
}
}
}
below is my custom adapter class for admin:
package com.example.trezah12.adminmodule;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by trezah12 on 23/10/2018.
*/
public class CustomAdapterAdmin extends BaseAdapter {
private List<Admin> adminList = new ArrayList<Admin>();
private Context activity;
private static LayoutInflater inflater = null;
public CustomAdapterAdmin(List<Admin> adminList, Context activity) {
this.adminList = adminList;
this.activity = activity;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return adminList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.customeadmin, null);
}
Admin admin = adminList.get(position);
TextView txt1 = (TextView) v.findViewById(R.id.textView1);
txt1.setText(admin.getUsername());
TextView txt2 = (TextView) v.findViewById(R.id.textView2);
txt2.setText(admin.getPassword());
return v;
}
}
Below is my XML file for list view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/listview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
</RelativeLayout>
that is because yout did not start the activity
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
startActivity(intent);
}
});

Recyclerview with cards in a fragment shows nothing

I am trying to make an activity which has a fragment inside with a recyclerView and cards on it. Right now, it only shows the activity, the fragment is empty, and I don't know what is going on here.
This is the code of the activity, the fragment, and the adapter
Activity:
package com.laorden.goodreasons.habits;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.NavigationView;
import android.support.test.espresso.IdlingResource;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.Injection;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.statistics.StatisticsActivity;
import com.laorden.goodreasons.util.ActivityUtils;
import com.laorden.goodreasons.util.EspressoIdlingResource;
public class HabitsActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private HabitsPresenter mHabitsPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.habits_act);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// Set up the toolbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
// Set up the navigation drawer.
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
HabitsFragment habitsFragment =
(HabitsFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
if (habitsFragment == null) {
// Create the fragment
habitsFragment = HabitsFragment.newInstance();
ActivityUtils.addFragmentToActivity(
getSupportFragmentManager(), habitsFragment, R.id.contentFrame);
}
// Create the presenter
mHabitsPresenter = new HabitsPresenter(habitsFragment,
Injection.provideUseCaseHandler());
}
/* // Load previously saved state, if available.
if (savedInstanceState != null) {
TasksFilterType currentFiltering =
(TasksFilterType) savedInstanceState.getSerializable(CURRENT_FILTERING_KEY);
mTasksPresenter.setFiltering(currentFiltering);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(CURRENT_FILTERING_KEY, mTasksPresenter.getFiltering());
super.onSaveInstanceState(outState);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Open the navigation drawer when the home icon is selected from the toolbar.
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.list_navigation_menu_item:
// Do nothing, we're already on that screen
break;
case R.id.statistics_navigation_menu_item:
Intent intent =
new Intent(HabitsActivity.this, StatisticsActivity.class);
startActivity(intent);
break;
default:
break;
}
// Close the navigation drawer when an item is selected.
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#VisibleForTesting
public IdlingResource getCountingIdlingResource() {
return EspressoIdlingResource.getIdlingResource();
}
}
Fragment:
package com.laorden.goodreasons.habits;
import android.os.Bundle;
import android.support.annotation.Nullable;
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.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.ArrayList;
import java.util.List;
public class HabitsFragment extends android.support.v4.app.Fragment implements HabitsContract.View {
private HabitsContract.Presenter mPresenter;
private HabitsAdapter mListAdapter;
private RecyclerView recyclerView;
public HabitsFragment() {
// Requires empty public constructor
}
public static HabitsFragment newInstance() {
return new HabitsFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Habit> habitsList = new ArrayList<>();
habitsList.add(new Habit(R.drawable.smoke,"Quit smoking",300));
habitsList.add(new Habit(R.drawable.books,"Read more",600));
habitsList.add(new Habit(R.drawable.sleep,"Get more sleep",600));
mListAdapter = new HabitsAdapter(getContext(),habitsList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setAdapter(mListAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return root;
}
#Override
public void onResume() {
super.onResume();
mPresenter.start();
}
#Override
public void setLoadingIndicator(boolean active) {
}
#Override
public void showHabits(List<Habit> habits) {
}
#Override
public void showHabitDetailsUi(String habitId) {
}
#Override
public boolean isActive() {
return false;
}
#Override
public void setPresenter(HabitsContract.Presenter presenter) {
mPresenter = presenter;
}
}
Adapter:
package com.laorden.goodreasons.habits;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.List;
public class HabitsAdapter extends RecyclerView.Adapter<HabitsAdapter.myViewHolder> {
Context mContext;
List<Habit> mData;
public HabitsAdapter(Context mContext, List<Habit> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.card_item,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
holder.background_image.setImageResource(mData.get(position).getBackground());
holder.tv_title.setText(mData.get(position).getHabitName());
holder.tv_nbSubscribers.setText(mData.get(position).getNumSubscribers() + " Joined");
}
#Override
public int getItemCount() {
return 0;
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView background_image;
TextView tv_title,tv_nbSubscribers;
public myViewHolder(View itemView) {
super(itemView);
background_image = itemView.findViewById(R.id.card_background);
tv_title = itemView.findViewById(R.id.card_title);
tv_nbSubscribers = itemView.findViewById(R.id.card_numberUsers);
}
}
}
If you need any other code snippets, please tell me (maybe the xml
layouts)
Thanks
That is because you are returning 0 in the getItemCount method
Change this :
#Override
public int getItemCount() {
return 0;
}
To this:
#Override
public int getItemCount() {
return (mData != null ? mData.size():0);
}
you should set layout manager first
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mListAdapter);
return root;
}
also you need to change the getItemCount into
#Override
public int getItemCount() {
if(mData!=null){return mData.size();}else return 0;
}
The reason you are getting empty list because your method getItemCount returns 0.
Here is the modified method.
#Override
public int getItemCount() {
return mData!=null ? mData.size():0;
}

When I move from fragment b to fragment A after adding my new listitem, my new listitem is not showing in recyclerview

I am making note taking app.i have two fragments in my app first fragment A (ListFragment) contains the recycler adapter .
while when I press adding floating button first fragment A (ListFragment) is replaced with next fragment B(AddingFragment) in which I type new data and then again press adding floating button on fragment B(AddingFragment) to add that new data in data set and then press backfloating button on my fragment B to move back to Fragment A(with recycler adapter) .
This new data item is added to data list every time but never becomes visible in recycler adapter in Fragment A.
package com.example.anonymous.note_taking_app;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class AddingFragment extends Fragment {
public AddingFragment()
{
}
#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_adding, container, false);
return view;
}
#Override
public void onResume()
{
super.onResume();
FloatingActionButton floating = (FloatingActionButton) getActivity().findViewById(R.id.addingfloatingbutton);
floating.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("floating_button", "floating button 2 clicked");
EditText title = (EditText) getActivity().findViewById(R.id.firsttextview);
EditText detial = (EditText) getActivity().findViewById(R.id.secondtextview);
DatabaseHelper db = new DatabaseHelper(getActivity().getApplication());
boolean insert = db.insert(title.getText()+"",detial.getText()+"");
if(insert==true)
{
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter();
ListFragment.it.add(new ListItem(title.getText()+"",detial.getText()+""));
l.notifyItemInserted(ListFragment.it.size()-1);//DataSetChanged();
l.notifyDataSetChanged();
for(int i=0;i<ListFragment.it.size();i++)
{
Log.i("List item"+i+"", ListFragment.it.get(i).getNoteTitle());
}
Log.i("insertion", "is added");
}
else
{
Log.i("insertion", "is not added");
}
}
});
FloatingActionButton floatings = (FloatingActionButton) getActivity().findViewById(R.id.addcancelfloatingbutton);
floatings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStackImmediate();
}
});
}
}
//
package com.example.anonymous.note_taking_app;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
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.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Fragment;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.holderclas> implements EditDilogue.EditDilougeinterface
{
static ArrayList<ListItem> i;
Context context;
View view;
ImageButton share;
ImageButton edit;
static int lastposition;
android.app.FragmentManager fm;
public ListAdapter(ArrayList<ListItem> i,android.app.FragmentManager fm)
{
this.i=i;
this.fm=fm;
}
public ListAdapter()
{
}
#Override
public ListAdapter.holderclas onCreateViewHolder(ViewGroup parent, int viewType)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
holderclas h = new holderclas(view);
share = (ImageButton) view.findViewById(R.id.share);
edit = (ImageButton) view.findViewById(R.id.edit);
return h;
}
#Override
public void onBindViewHolder(ListAdapter.holderclas holder, final int position)
{
final int y= position;
lastposition = position;
final ListItem it = i.get(position);
holder.title.setText(it.getNoteTitle());
holder.details.setText(it.getNoteDetail());
ImageButton b =(ImageButton) view.findViewById(R.id.delete);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("size", i.size()+"");
i.remove(y);
notifyDataSetChanged();
}
});
share.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("share", "share");
}
});
edit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("edit", i.size()+"edit");
EditDilogue ed = new EditDilogue();
Bundle args = new Bundle();
args.putString("title", it.getNoteTitle());
args.putString("detail", it.getNoteDetail());
ed.setArguments(args);
ed.setTargetFragment(new ListFragment(),1);
ed.show(fm,"fragment");
}
});
}
#Override
public int getItemCount()
{
return i.size();
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = i.get(lastposition).getNoteTitle();
String olddetail = i.get(lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
public class holderclas extends RecyclerView.ViewHolder
{
TextView title;
TextView details;
public holderclas(View itemView)
{
super(itemView);
title=(TextView) itemView.findViewById(R.id.title);
details=(TextView) itemView.findViewById(R.id.detail);
}
}
}
//
package com.example.anonymous.note_taking_app;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
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.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListFragment extends Fragment implements EditDilogue.EditDilougeinterface
{
RecyclerView recyClerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
public static ArrayList<ListItem> it;
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
it = new ArrayList<>();
View view = inflater.inflate(R.layout.fragment_list, parent, false);
FloatingActionButton floating = (FloatingActionButton) view.findViewById(R.id.listfloatingbutton);
floating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Fragment frg = new AddingFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.replace(R.id.placeholder,frg);
trans.addToBackStack("addingfragment");
trans.commit();
AddingFragment()).addToBackStack("addingfragment").commit();
}
});
for(int i=0;i<5;i++)
{
ListItem t = new ListItem("Time Bank",
"Bank should contain atleast $2000 rupees then i will leave this matter") ;
it.add(t);
}
recyClerView=(RecyclerView) view.findViewById(R.id.recycle);
FragmentManager fm = getFragmentManager();
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter(it,fm);
recyClerView.setAdapter(l);
layoutManager = new LinearLayoutManager(getActivity());
recyClerView.setLayoutManager(layoutManager);
return view;
}
#Override
public void onResume()
{
super.onResume();
if(adapter!=null)
{
adapter.notifyDataSetChanged();
adapter.notifyItemInserted(ListFragment.it.size()-1);
}
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteTitle();
String olddetail = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
}

Retrofit RecyclerView not working in tab layout

I've been trying to implement a recycler view inside a fragment which displays parsed data using the retrofit library. Whenever I run the project the lists don't show and the monitor says "E/RecyclerView: No adapter attached; skipping layout". Here is my code:
MainActivity:
package com.example.ahmed.newsapp
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.design.widget.TabLayout;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int ACTIVITY_NUM = 0;
// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "<API KEY CENSORED>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager
());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout ob=(TabLayout) findViewById(R.id.sliding_tabs);
ob.setupWithViewPager(viewPager);
}
}
FragmentAdapter:
package com.example.ahmed.newsapp;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by ahmed on 3/22/2017.
*/
public class FragmentAdapter extends FragmentPagerAdapter {
private String tabs[]=new String[]{"Home","Family Members","Colors"};
public FragmentAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new HomeActivity();
case 1:
return new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 2;
}
}
NewsAdapter:
package com.example.ahmed.newsapp;
/**
* Created by ahmed on 27-08-17.
*/
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 java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private List<News> news;
private int rowLayout;
private Context context;
public static class NewsViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
public NewsViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
movieTitle = (TextView) v.findViewById(R.id.title);
data = (TextView) v.findViewById(R.id.subtitle);
movieDescription = (TextView) v.findViewById(R.id.description);
rating = (TextView) v.findViewById(R.id.rating);
}
}
public NewsAdapter(List<News> news, Context context) {
this.news = news;
// this.rowLayout = rowLayout;
this.context = context;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_news, parent, false);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder(NewsViewHolder holder, final int position) {
holder.movieTitle.setText(news.get(position).getTitle());
holder.data.setText(news.get(position).getReleaseDate());
holder.movieDescription.setText(news.get(position).getOverview());
holder.rating.setText(news.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return news.size();
}
}
HomeActivity:
package com.example.ahmed.newsapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.ContentValues.TAG;
public class HomeActivity extends Fragment {
RecyclerView recyclerView;
private final static String API_KEY = "<API KEY CENSORED>";
NewsAdapter adapter;
List<News> news,dummy;
View rootview;
public HomeActivity() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.activity_home, container, false);
if (API_KEY.isEmpty()) {
Toast.makeText(getContext(), "Please obtain your API KEY first from themoviedb.org", Toast.LENGTH_LONG).show();
return rootview;
}
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.notifyDataSetChanged();
adapter=new NewsAdapter(news,getContext());
recyclerView.setAdapter(adapter);
// adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
#Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
return rootview;
}
}
i think the problem is in your FragmentAdapter class
just remove return null; statement from your FragmentAdapter like below code
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch(position){
case 0:
fragment= new HomeActivity();
case 1:
fragment= new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return fragment;
}
change this
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
You don't need to recreate your adapter when you receive response.
It may looks like:
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new NewsAdapter(null, getActivity());
recyclerView.setAdapter(adapter);
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
...
And in NewsAdapter:
...
public void setData(Collection<News> newData) {
news.clear();
news.addAll(newData);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return news == null ? 0 : news.size();
}
...

findfragmentbyid returns null in mainActivity hosting 3 fragments under a viewpager

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);

Categories