Unable to retrieve context in Fragment [duplicate] - java

This question already has answers here:
Why is my context in my Fragment null?
(4 answers)
Closed 5 years ago.
I tried to find the solution with several resources:
Retrieve Context from a fragment
Using context in a fragment
But I still got the following error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' on a null object reference
Any help will be appreciated. Thanks!
My current codes:
AnalysisActivity.java:
package com.app.component.fragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.material.components.R;
import com.material.components.fragment.FragmentTabsEvents;
import com.material.components.fragment.FragmentTabsPerformance;
import com.material.components.fragment.FragmentTabsRecommendation;
import com.material.components.utils.Tools;
import java.util.ArrayList;
import java.util.List;
public class AnalysisActivity extends AppCompatActivity {
private ViewPager view_pager;
private TabLayout tab_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_analysis);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Tools.setSystemBarColor(this,R.color.black);
view_pager = findViewById(R.id.view_pager);
setupViewPager(view_pager);
tab_layout = findViewById(R.id.tab_layout);
tab_layout.setupWithViewPager(view_pager);
}
private void setupViewPager(ViewPager viewPager) {
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(FragmentTabsPerformance.newInstance(), "PERFORMANCE");
adapter.addFragment(FragmentTabsRecommendation.newInstance(), "RECOMMENDATION");
adapter.addFragment(FragmentTabsEvents.newInstance(), "EVENTS RELATED TO YOU");
viewPager.setAdapter(adapter);
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
FragmentTabsPerformance.java:
package com.app.component.fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.material.components.R;
import com.material.components.utils.Tools;
import java.util.ArrayList;
import java.util.List;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;
public class FragmentTabsPerformance extends Fragment {
private Context context;
public FragmentTabsPerformance() {
this.context = getActivity().getApplicationContext();
List<PointValue> values = new ArrayList<>();
values.add(new PointValue(0, 2));
values.add(new PointValue(1, 4));
values.add(new PointValue(2, 3));
values.add(new PointValue(3, 4));
//In most cased you can call data model methods in builder-pattern-like manner.
Line line = new Line(values).setColor(Color.BLUE).setCubic(true);
List<Line> lines = new ArrayList<>();
lines.add(line);
LineChartData data = new LineChartData();
data.setLines(lines);
LineChartView chart = new LineChartView(this.getContext());
chart.setLineChartData(data);
}
public static FragmentTabsPerformance newInstance() {
FragmentTabsPerformance fragment = new FragmentTabsPerformance();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_tabs_performance, container, false);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_1), R.drawable.image_8);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_2), R.drawable.image_9);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_3), R.drawable.image_15);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_4), R.drawable.image_14);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_5), R.drawable.image_12);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_6), R.drawable.image_2);
Tools.displayImageOriginal(getActivity(), (ImageView) root.findViewById(R.id.image_7), R.drawable.image_5);
return root;
}
}

This exception occurred since you called the getActivity() in the construction method when the fragment is not attached to an activity. You may refer to the API guides about the lifecycle methods about fragment with activity. In your case, you may use getContext() instead of getActivity() method to get the context of fragment.

getActivity() only available after Fragment is attached to activity. So, getActivity() in Fragment constructor will return null. Check fragment life cycle for more detail

Related

Get values from json in fragment

I am trying to get info from a JSON into a card view, I've made this application in a separate project and it works but now i am trying to integrate it with the actual application. I am using fragments for the actual application.
package com.example.loginfirebase.news;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.loginfirebase.R;
import com.google.android.gms.common.api.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class NewsFragment extends Fragment {
RecyclerView recyclerView;
List<Anunturi> anunturiLi;
private static String JSON_URL = "";
Adapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public NewsFragment() {
// Required empty public constructor
}
public static NewsFragment newInstance(String param1, String param2) {
NewsFragment fragment = new NewsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(container==null){
Log.v("Container",": Containerul este null");
}
// Inflate the layout for this fragment
Context aplicationcontext = getActivity().getApplicationContext();
//Context thiscontext = container.getContext();
RecyclerView recyclerView=container.findViewById(R.id.anunturiList);
if (recyclerView==null){
Log.v("recycler view value","is null");
}
Context fragmentcontext=container.getContext();
anunturiLi = new ArrayList<>();
extractAnunturi(aplicationcontext,fragmentcontext);
Log.v("Aplication context", String.valueOf(aplicationcontext));
return inflater.inflate(R.layout.fragment_news, container, false);
}
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// RecyclerView recyclerView=view.findViewById(R.id.anunturiList);
//
//
// }
private void extractAnunturi(Context aplicationcontext,Context fragmentcontext) {
//TODO: FIX
Context mContext;
mContext = fragmentcontext;
Log.v("Activity non null","activity:"+getActivity());
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject anunturiObject = response.getJSONObject(i);
Anunturi anunturi = new Anunturi();
anunturi.setTitle(anunturiObject.getString("titlu_anunt"));
Log.v("Tag anunturi title:",anunturi.getTitle());
anunturi.setAutor(anunturiObject.getString("autor_anunt".toString()));
Log.v("Tag anunturi title:",anunturi.getAutor());
anunturi.setCoverImage(anunturiObject.getString("cover_image"));
Log.v("Tag anunturi title:",anunturi.getCoverImage());
anunturi.setAnuntURL(anunturiObject.getString("url"));
Log.v("Tag anunturi title:",anunturi.getAnuntURL());
anunturi.setText_anunt(anunturiObject.getString("text_anunt"));
Log.v("Tag anunturi title:",anunturi.getText_anunt());
anunturiLi.add(anunturi);
} catch (JSONException e) {
e.printStackTrace();
}
}
//TODO FIX
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new Adapter(getApplicationContext(), anunturiLi);
recyclerView.setAdapter(adapter);
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//nimic
}
});
queue.add(jsonArrayRequest);
}
}
and i get this error
F:\LoginFirebase\app\src\main\java\com\example\loginfirebase\news\NewsFragment.java:127: error: cannot find symbol
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
^
symbol: method getApplicationContext()
I've tried passing context as parametre and changing to:
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
adapter = new Adapter(getActivity().getApplicationContext(), anunturiLi);
recyclerView.setAdapter(adapter);
But i get this error
2021-04-11 19:37:42.632 26960-26960/com.example.loginfirebase D/AndroidRuntime: Shutting down VM
2021-04-11 19:37:42.633 26960-26960/com.example.loginfirebase E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.loginfirebase, PID: 26960
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at com.example.loginfirebase.news.NewsFragment$1.onResponse(NewsFragment.java:127)
at com.example.loginfirebase.news.NewsFragment$1.onResponse(NewsFragment.java:103)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
The adapter code:
package com.example.loginfirebase.news;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.loginfirebase.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
LayoutInflater inflater;
List<Anunturi> anunturi;
public Adapter(Context ctx, List<Anunturi> anunturi){
this.inflater= LayoutInflater.from(ctx);
this.anunturi=anunturi;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.custom_list_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//bind the data
holder.titlu_anunt.setText(anunturi.get(position).getTitle());
holder.autor_anunt.setText(anunturi.get(position).getAutor());
Picasso.get().load(anunturi.get(position).getCoverImage()).into(holder.img_anunt);
holder.text_anunt.setText(anunturi.get(position).getText_anunt());
}
#Override
public int getItemCount() {
return anunturi.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titlu_anunt,autor_anunt,text_anunt;
ImageView img_anunt;
public ViewHolder(#NonNull View itemView) {
super(itemView);
titlu_anunt=itemView.findViewById(R.id.anunt_title);
autor_anunt=itemView.findViewById(R.id.anunt_autor);
text_anunt=itemView.findViewById(R.id.txt_anunt);
img_anunt=itemView.findViewById(R.id.anunt_image);
}
}
}
Solution
Had to put the code in onViewCreated
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView=view.findViewById(R.id.anunturiList);
//View view = inflater.inflate(R.layout.fragment_news, container, false);
anunturiLi = new ArrayList<>();
extractAnunturi();
}
When you're doing this:
RecyclerView recyclerView=container.findViewById(R.id.anunturiList);
You are assigning the Recycler View to a local variable, so your recyclerView field is still null. When you use it below, it causes the NPE.
You have to assign it to the recyclerView field:
recyclerView=container.findViewById(R.id.anunturiList);

Android: E/RecyclerView: No adapter attached; skipping layout

so i have a tabbed activity that contains 3 tabs as fragments, each tab has a RecyclerView.
I checked all the answered questions on here and on other sites, everything seems fine, yet it doesn't work!
here's my Code:
MainActivity.java:
package esprit.tn.mywaterproject;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.time.Duration;
import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("test","test log");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Chat avec un
résponsable", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e("frag number", "frag test number
:"+getArguments().getInt(ARG_SECTION_NUMBER));
if (getArguments().getInt(ARG_SECTION_NUMBER)==1){
Log.e("frag test1", "frag test TEST1");
new Eaux_Fragment();
return inflater.inflate(R.layout.fragment_eaux,
container,false);
}
if (getArguments().getInt(ARG_SECTION_NUMBER)==2){
Log.e("frag test2", "frag test TEST2");
return inflater.inflate(R.layout.fragment_piscine,
container,false);
}
if (getArguments().getInt(ARG_SECTION_NUMBER)==3){
Log.e("frag test3", "frag test TEST3");
return inflater.inflate(R.layout.fragment_electricite, container,false);
}
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
Here's my Adapter
ProduitAdapter.java :
package esprit.tn.mywaterproject;
import android.content.Context;
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.TextView;
import java.util.ArrayList;
import java.util.List;
import esprit.tn.mywaterproject.Entities.Produit_Eau;
public class ProduitAdapter extends
RecyclerView.Adapter<ProduitAdapter.ViewHolder> {
private Context context;
private List<Produit_Eau> list;
public ProduitAdapter( Context context, ArrayList<Produit_Eau> list) {
this.context=context;
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.e("LOG IN ADAPTER","TEST ADAPTER");
View v =
LayoutInflater.from(context).inflate(R.layout.single_produit_eau, parent,
false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Produit_Eau prod_eau = list.get(position);
holder.text_single_prod_nom.setText(prod_eau.getNom());
holder.text_single_prod_description.setText(prod_eau.getDescription());
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView text_single_prod_nom, text_single_prod_description;
public ViewHolder(View itemView) {
super(itemView);
text_single_prod_nom = itemView.findViewById(R.id.single_prod_nom);
text_single_prod_description =
itemView.findViewById(R.id.single_prod_description);
}
}
}
And Here's one of the fragments
Eau_Fragment.java
package esprit.tn.mywaterproject.Fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
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.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
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.JsonArrayRequest;
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.util.ArrayList;
import java.util.List;
import esprit.tn.mywaterproject.Entities.Produit_Eau;
import esprit.tn.mywaterproject.ProduitAdapter;
import esprit.tn.mywaterproject.R;
/**
* A simple {#link Fragment} subclass.
*/
public class Eaux_Fragment extends Fragment {
private RecyclerView recyclerList;
private LinearLayoutManager linearLayoutManager;
private ArrayList<Produit_Eau> produit_eauList;
private ProduitAdapter adapter;
private String UrlShowProducts = "http://192.168.1.7:3003/prodeau";
private LinearLayout linearLayout;
public Eaux_Fragment() {
Log.e("Test Eau Fragment","EAU FRAG TEST");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragmentd
View view = inflater.inflate(R.layout.fragment_eaux, container, false);
linearLayoutManager = new
LinearLayoutManager(getActivity().getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
DividerItemDecoration(recyclerList.getContext(),
linearLayoutManager.getOrientation());
adapter = new ProduitAdapter(getActivity().getApplicationContext(),
produit_eauList);
recyclerList = getActivity().findViewById(R.id.eau_prod_list);
recyclerList.setHasFixedSize(true);
recyclerList.setLayoutManager(linearLayoutManager);
produit_eauList = new ArrayList<>();
getData();
recyclerList.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
private void getData() {
JsonArrayRequest jsonArrayRequest = new
JsonArrayRequest(UrlShowProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Produit_Eau produit_eau = new Produit_Eau();
produit_eau.setNom(jsonObject.getString("name"));
produit_eau.setDescription(jsonObject.getString("description"));
produit_eauList.add(produit_eau);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue =
Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(jsonArrayRequest);
}
}
Edit:
The problem i'm facing here is that Eau_Fragment is not showing in the application. i've deleted every other fragment and kept only this one to test it, the fragment is displayed empty, and the only error i got is the one mentionned above.
It's only a warning but if you're concerned about it, then set the adapter before the layout manager:
recyclerList = getActivity().findViewById(R.id.eau_prod_list);
recyclerList.setAdapter(adapter);
recyclerList.setHasFixedSize(true);
recyclerList.setLayoutManager(linearLayoutManager);
Because it triggers layout update immediately when you set layout manager, which looks for the adapter eventually.
I am not sure what is the problem you are facing, but one thing I noticed, is that you are not using Eaux_Fragment in your SectionsPagerAdapter so you need change :
return PlaceholderFragment.newInstance(position + 1);
to
return Eaux_Fragment(position + 1);
and do not forget to add the newInstance method to Eaux_Fragment
public static Eaux_Fragment newInstance(int position) {
Eaux_Fragment fragment = new Eaux_Fragment();
Bundle args = new Bundle();
args.putString(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}

How to pass an arraylist to a fragment from adapter?

Actually, I am adding objects in ArrayList from a RecyclerAdapter and I have written a function for getting the arraylist in adapter.And I am getting the arraylist from that function in MainActivity.But whenever I am trying to pass that arraylist from MainActivity to a Fragment it is giving NullPointer(Null value).
Help me.
package com.example.codingmounrtain.addtocartbadgecount.adapter;
import android.content.Context;
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.ImageView;
import android.widget.TextView;
import com.example.codingmounrtain.addtocartbadgecount.activity.MainActivity;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<Movie> cartmovies = new ArrayList<>();
public interface Listener {
void onSelectMovie(int position);
}
Context context;
private final ArrayList<Movie> movies;
private final Listener listener;
public RecyclerAdapter(Context context, ArrayList<Movie> movies,Listener listener) {
this.context = context;
this.movies = movies;
this.listener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.productName.setText(movies.get(position).getTitle());
Picasso.with(context).load(movies.get(position).getPhoto()).centerCrop().resize(400,400).into(holder.productImage);
holder.productImage.setImageResource(movies.get(position).getPhoto());
holder.productImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onSelectMovie(position);
}
});
holder.addRemoveBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!movies.get(position).isAddedTocart())
{
Log.v("tej","tej");
movies.get(position).setAddedTocart(true);
Log.v("t","t");
holder.addRemoveBt.setText("Remove");
Movie movie = movies.get(position);
cartmovies.add(movie);
Log.v("t","t");
if(context instanceof MainActivity)
{
((AddorRemoveCallbacks)context).onAddProduct();
}
}
else
{
movies.get(position).setAddedTocart(false);
Movie movie = movies.get(position);
cartmovies.remove(movie);
holder.addRemoveBt.setText("Add");
((AddorRemoveCallbacks)context).onRemoveProduct();
}
}
});
}
public ArrayList<Movie> getArrayList(){
return cartmovies;
}
#Override
public int getItemCount() {
return movies.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView productImage;
TextView productName;
Button addRemoveBt;
public MyViewHolder(View itemView) {
super(itemView);
productImage=(ImageView) itemView.findViewById(R.id.productImageView);
productName=(TextView) itemView.findViewById(R.id.productNameTv);
addRemoveBt=(Button)itemView.findViewById(R.id.addButton);
}
}
}
MainActivity.java
package com.example.codingmounrtain.addtocartbadgecount.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.example.codingmounrtain.addtocartbadgecount.Converter;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import com.example.codingmounrtain.addtocartbadgecount.fragment.CartFragment;
import com.example.codingmounrtain.addtocartbadgecount.fragment.SearchFragment;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import java.util.ArrayList;
import java.util.Iterator;
public class MainActivity extends AppCompatActivity implements AddorRemoveCallbacks,RecyclerAdapter.Listener{
ArrayList<Movie> cartmovies = new ArrayList<>();
ArrayList<Movie> movies = new ArrayList<>();
RecyclerView mRecyclerView;
RecyclerAdapter mAdapter;
private static int cart_count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("MovieShop");
getSupportActionBar().show();
movies.add(new Movie("Stree","A town is held in the grip of terror by tales of a mysterious woman who calls men by their name and then abducts them, leaving their clothes behind.","Rajkummar Rao","Shraddha Kapoor","Amar Kaushik",4.0f,R.drawable.stree));
movies.add(new Movie("Nun","When a young nun at a cloistered abbey in Romania takes her own life, a priest with a haunted past and a novitiate on the threshold of her final vows are sent by the Vatican to investigate. ","Demián Bichir","Taissa Farmiga","Corin Hardy",2.5f,R.drawable.nun));
movies.add(new Movie("Savita Damodar Paranjpe","The lives of a married couple are turned upside down when hard truths come to light.","Subodh Bhave","Trupti Madhukar Toradmal","Swapna Waghmare Joshi",3.5f,R.drawable.savita));
movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));
movies.add(new Movie("MI","Ethan Hunt and the IMF team join forces with CIA assassin August Walker to prevent a disaster of epic proportions.","Tom Cruise","Rebecca Ferguson","Christopher McQuarrie",4.0f,R.drawable.mi));
movies.add(new Movie("Searching","After David Kim (John Cho)'s 16-year-old daughter goes missing, a local investigation is opened and a detective is assigned to the case. ","John Cho","Debra Messing","Aneesh Chaganty",2.5f,R.drawable.searching));
movies.add(new Movie("SURYA"," Indian Telugu-language action film written and directed by Vakkantham Vamsi in his directorial debut. ","Allu Arjun","Anu Emmanuel","Vakkantham Vamsi",3.5f,R.drawable.surya));
movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new RecyclerAdapter(this, movies,this);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.cart_action);
menuItem.setIcon(Converter.convertLayoutToImage(MainActivity.this,cart_count,R.drawable.ic_shopping_cart_white_24dp));
MenuItem menuItem2 = menu.findItem(R.id.search_action);
menuItem2.setIcon(R.drawable.ic_search_black_24dp);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
cartmovies = mAdapter.getArrayList();
Movie movie = null;
Iterator<Movie> iter = cartmovies.iterator();
while ( iter .hasNext() == true )
{
movie = iter.next();
Log.v("tejjjj",movie.getTitle());
}
// cartmovies.get(0).getTitle();
if(id==R.id.cart_action){
Bundle bundle = new Bundle();
bundle.putSerializable("catmovies",cartmovies);
Fragment fragment = new CartFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.contentLayout, fragment)
.addToBackStack("MainActivity")
.commit();
}
if(id==R.id.search_action){
Bundle bundle = new Bundle();
// bundle.putString("query", editSearch.getText().toString());
bundle.putSerializable("movies",movies);
Fragment fragment = new SearchFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.contentLayout, fragment)
.addToBackStack("MainActivity")
.commit();
// search(searchStr, movies);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAddProduct() {
cart_count++;
Log.v("stej",""+cart_count);
invalidateOptionsMenu();
Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie added to cart !!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
#Override
public void onRemoveProduct() {
cart_count--;
Log.v("tej",""+cart_count);
invalidateOptionsMenu();
Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie removed from cart !!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
#Override
public void onSelectMovie(int position) {
Movie movie = movies.get(position);
// Toast.makeText(this, "selected movie: " + movie.getTitle(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("title",movie.getTitle());
intent.putExtra("director",movie.getDirector());
intent.putExtra("actors",movie.getActors());
intent.putExtra("actresses",movie.getActresses());
intent.putExtra("info",movie.getDescription());
intent.putExtra("photo",movie.getPhoto());
intent.putExtra("rating",movie.getRating());
startActivity(intent);
}
}
CartFragment.java
package com.example.codingmounrtain.addtocartbadgecount.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
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.LinearLayout;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.activity.DetailActivity;
import com.example.codingmounrtain.addtocartbadgecount.adapter.MovieListAdapter;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import java.util.ArrayList;
import java.util.Iterator;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class CartFragment extends Fragment implements View.OnClickListener, MovieListAdapter.Listener {
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
Unbinder unbinder;
MovieListAdapter adapter;
RecyclerAdapter madapter;
ArrayList<Movie> movies = new ArrayList<>();
ArrayList<Movie> movies1 = new ArrayList<>();
public CartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_cart, null);
unbinder = ButterKnife.bind(this, layout);
adapter = new MovieListAdapter(getActivity(),movies,this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Movie Cart");
// movies1 =(ArrayList<Movie>) savedInstanceState.getParcelable("movies");
// buttonSearch.setOnClickListener(this);
return layout;
}
#Override
public void onResume() {
super.onResume();
getList();
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
void getList(){
Bundle bundle = getArguments();
movies1 =(ArrayList<Movie>) bundle.getSerializable("cartmovies");
Iterator<Movie> iter = movies1.iterator();
Movie movie = null;
while(iter.hasNext() == true){
movie = iter.next();
movies.add(movie);
adapter.notifyDataSetChanged();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onSelectMovie(int position) {
Movie movie = movies.get(position);
Intent intent = new Intent(getActivity(),DetailActivity.class);
intent.putExtra("title",movie.getTitle());
intent.putExtra("director",movie.getDirector());
intent.putExtra("actors",movie.getActors());
intent.putExtra("actresses",movie.getActresses());
intent.putExtra("info",movie.getDescription());
intent.putExtra("photo",movie.getPhoto());
intent.putExtra("rating",movie.getRating());
startActivity(intent);
}
}
Write a get method inside your adapter then call it from your activity or fragment.
public ArrayList<Object> getArrayList() {
return yourArrayList;
}
Inside your activity you can get this like, yourAdapterObject.getArrayList();
Try to pass it via bundle.
First create a model class which will be passed. It should implement Serializable
public class MyModel implements Serializable {
private ArrayList<Data> datas;
public MyModel(ArrayList<Data> datas) {
this.datas = datas
}
}
Then put your data to the bundle
Bundle bundle = new Bundle();
bundle.putSerializable();
Finally put that bundle instance to your fragment
myFragment.setArguments(bundle);
You can pass your array list to fragment by setting arguments for that fragment. But for that, the type of object your array list contains should extend Serializable. Then make a getInstance() method in your fragment that returns an instance of your fragment and wherever you are opening your fragment call that getInstance() method and pass your Array list.
getSupportFragmentManager().beginTransaction()
.add(containerId, YourFragment.getInstance(yourArrayList), tag)
.commitAllowingStateLoss();
The sample code snippet for getInstance() method in your fragment is:
public static YourFragment getInstance( ArrayList<Object> yourArrayList) {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(Constants.YOUR_LIST,yourArrayList);
YourFragment yourFragment = new YourFragment();
yourFragment.setArguments(bundle);
return yourFragment;
}
Now, you can get your arraylist by calling getArguments() wherever need in your fragment. Also, make sure to check for null Arguments. The sample code for this is:
if (getArguments()!=null && getArguments().containsKey(Constants.YOUR_LIST) && getArguments().getParcelableArrayList(Constants.YOUR_LIST) != null){
ArrayList<Object> yourlist = getArguments().getParcelableArrayList(Constants.YOUR_LIST);
}
Now, by making this list global you can access it anywhere in the fragment. Hope, it helps.

Error in java file ,yosemiteadapter.java(ViewPageAdapter), making an tour app, app is crashing

I am making a tour app, it structure is like this:
First activity shows seasons like Summer, Winter, Spring, Autumn. After selecting any season, another activity pops up with locations around the world best suited for that season. After selecting any one location, another activity will pop up with 2 to 3 images with the description, and we will slide through these images. That's it. To make it more accessible, I tried adding this code to NawDrawer activity:
Debugging Error Message Image
Originally the ViewPagerAdapter.java was for Hawaii (check the image), but I created exact same as Yoshimiteadapter.java for Yosemite, but it's not working.
I apologize for the inconvenience caused by the files :) ,it's messy ,but desperate help is needed:
Link to android studio project zip file
There are total 7 java files and 12 activity files although I have an error in yosemiteadapter.Java line no 35 , error message is as follows:
04-16 12:00:09.563 12511-12511/com.example.android.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.myapplication, PID: 12511
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.example.android.myapplication.yoshimiteadapter.instantiateItem(yoshimiteadapter.java:35)
**Code for the app as follows,I have block quoted the line of error **
yoshimiteadapter.java
package com.example.android.myapplication;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by sanchitdeshmukh on 17/03/18.
*/
public class yoshimiteadapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer []images1 ={R.drawable.yosemite1,R.drawable.yoshemite2,R.drawable.yoshemite3};
private Integer []strings1 = {R.string.yoshimite};
public yoshimiteadapter(Context context) {
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.custom_layout_yos, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
imageView.setImageResource(images1[position]);
TextView textView = (TextView)view.findViewById(R.id.textView);
textView.setText(strings1[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view,0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
#Override
public int getCount() {
return images1.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
}
yosemite.java
package com.example.android.myapplication;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class yoshemite extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yoshemite);
viewPager = (ViewPager)findViewById(R.id.yoshimite);
yoshimiteadapter yoshimiteadapter = new yoshimiteadapter(this);
viewPager.setAdapter(yoshimiteadapter);
}
}
ViewPagerAdapter.java
package com.example.android.myapplication;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by sanchitdeshmukh on 17/03/18.
*/
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer []images ={R.drawable.napalicoast,R.drawable.haleakaaa,R.drawable.roadtohana};
private Integer []strings = {R.string.haleaka,R.string.napali,R.string.Paragraph_hawaii};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view =layoutInflater.inflate(R.layout.custom_layout, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
TextView textView = (TextView)view.findViewById(R.id.textView);
textView.setText(strings[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
I found the solution , it's related to this:
textView.setText(strings1[position]);
I have only one string, three images, which causes the error. [position] should be set to '0'; so the modification is like this:
textView.setText(strings1[0]);

Connect Fragment from Activity

I have an activity and already made fragment. In my activity, when I click on login button then the loader will show. After the loader become invisible, then I just need to attach that fragment. The fragment has already been created in some other class. I just need to attach that fragment when the circular loader become invisible and my fragment has already been created in some other class but I need to just attach that fragment.
MainActivity.java
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
if (loader_fragment != null) {
AVLoadingIndicatorView loader = loader_fragment.getView().findViewById(R.id.loder_login);
loader.setVisibility(View.INVISIBLE);
timer.cancel();
}
Home_Screen home_screen = (Home_Screen) getFragmentManager().findFragmentById(R.id.Home_screen_fragment);
fragmentManager1 = getFragmentManager();
fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmentTransaction1.setCustomAnimations(
R.animator.slide_in_left,
R.animator.slide_out_left,
R.animator.slide_in_right,
R.animator.slide_out_right);
Home_screen_student home_screen_student = new Home_screen_student();
fragmentTransaction1.attach(R.id.Home_screen_fragment, home_screen_student);
fragmentTransaction1.commit();
}
};
HomeScreenFragment.java
package com.example.user.attendance;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.NavigationView.OnNavigationItemSelectedListener;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class Home_Screen extends Fragment implements OnNavigationItemSelectedListener {
DrawerLayout navigation_drawer;
NavigationView navigationView;
Button logout_Yes_button,logout_no_button, home_screen_take_attendance_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View Home_screen = inflater.inflate(R.layout.navigation_drawer,container,false);
android.support.v7.widget.Toolbar toolbar =
(android.support.v7.widget.Toolbar) Home_screen.findViewById(R.id.custom_action_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
navigation_drawer = (DrawerLayout) Home_screen.findViewById(R.id.drawer_layout);
navigationView = (NavigationView) Home_screen.findViewById(R.id.Navigation_view_for_teacher);
Logcat error:
04-22 18:45:31.966 26404-26404/? E/Zygote: no v2
04-22 18:45:54.221 26404-26404/com.example.user.attendance E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.attendance, PID: 26404
java.lang.NullPointerException: Attempt to write to field 'android.app.FragmentManagerImpl android.app.Fragment.mFragmentManager' on a null object reference
at android.app.BackStackRecord.doAddOp(BackStackRecord.java:461)
at android.app.BackStackRecord.replace(BackStackRecord.java:496)
at android.app.BackStackRecord.replace(BackStackRecord.java:488)
at com.example.user.attendance.MainActivity$3$2.run(MainActivity.java:181)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7402)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Help me.
Do you use viewPager in your activity?
You may need to process from one activity to another
Try this trailer:
ViewPager viewPager = (ViewPager) findViewById(R.id.rew1);
viewPager.setAdapter(new CustomPagerAdapter(this));
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
//
public enum CustomPagerEnum {
HomeFragment (R.string.tab_text_1, R.layout.Home_screen_fragment),
private int mTitleResId;
private int mLayoutResId;
CustomPagerEnum(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
//
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
home.CustomPagerEnum customPagerEnum = home.CustomPagerEnum.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(customPagerEnum.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return home.CustomPagerEnum.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
home.CustomPagerEnum customPagerEnum = home.CustomPagerEnum.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
My language is German but I hope I understand your problem well!

Categories