L'erreur a commencé à apparaître uniquement après que j'ai commencé à utiliser des fragments dans le projet.
voici mon code ..
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;
private MyPagerAdapter adapter;
public static final int product_result = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment navigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_nav_drawer);
navigationDrawerFragment.setUp(R.id.fragment_nav_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
mPager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(adapter);
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
mTabs.setDistributeEvenly(true);
mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabText);
int bgColor = ContextCompat.getColor(this, R.color.colorPrimary);
mTabs.setBackgroundColor(bgColor);
mTabs.setSelectedIndicatorColors(ContextCompat.getColor(MainActivity.this, R.color.colorAccent));
mTabs.invalidate();
mTabs.setViewPager(mPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.navigate) {
startActivity(new Intent(this, SubActivity.class));
}
if (id == R.id.TabActivity) {
startActivity(new Intent(this, ActivityUsingTabLibrary.class));
}
if (id == R.id.VectorTest) {
startActivity(new Intent(this, VectorTestActivity.class));
}
return super.onOptionsItemSelected(item);
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
int icons[] = {R.drawable.home, R.drawable.hot_article, R.drawable.dizzy_person};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position){
case product_result:
fragment = FragmentProduct.newInstance("","");
break;
}
return fragment;
}
@Override
public CharSequence getPageTitle(int position) {
Drawable drawable = ResourcesCompat.getDrawable(getResources(), icons[position], null);
drawable.setBounds(0, 0, 36, 36);
ImageSpan imageSpan = new ImageSpan(drawable);
SpannableString spannableString = new SpannableString(" ");
spannableString.setSpan(imageSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
@Override
public int getCount() {
return 3;
}
}
}
c'est mon fragment.class où je passe toast jsonObject.
public class FragmentProduct extends Fragment {
public static final String product_url = "http://oasisgroups.com/oApp/product.php";
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
public FragmentProduct() {
// Required empty public constructor
}
public static FragmentProduct newInstance(String param1, String param2) {
FragmentProduct fragment = new FragmentProduct();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static String getRequestUrl(int limit) {
return product_url + "&limit=" + limit;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getmRequestQueue();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getRequestUrl(10),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
L.t(getActivity(), response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_product, container, false);
}
}
trace de la pile
02-29 12:10:01.047 17100-17100/com.mydesign.rockstar.materialdesignexample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mydesign.rockstar.materialdesignexample, PID: 17100
Java.lang.NullPointerException: Attempt to invoke virtual method 'void Android.support.v4.app.Fragment.setMenuVisibility(boolean)' on a null object reference
at Android.support.v4.app.FragmentStatePagerAdapter.instantiateItem(FragmentStatePagerAdapter.Java:116)
at Android.support.v4.view.ViewPager.addNewItem(ViewPager.Java:870)
at Android.support.v4.view.ViewPager.populate(ViewPager.Java:1086)
at Android.support.v4.view.ViewPager.populate(ViewPager.Java:952)
at Android.support.v4.view.ViewPager.onMeasure(ViewPager.Java:1474)
at Android.view.View.measure(View.Java:18804)
at Android.widget.LinearLayout.measureVertical(LinearLayout.Java:901)
at Android.widget.LinearLayout.onMeasure(LinearLayout.Java:630)
at Android.view.View.measure(View.Java:18804)
at Android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.Java:940)
at Android.view.View.measure(View.Java:18804)
at Android.view.ViewGroup.measureChildWithMargins(ViewGroup.Java:5954)
at Android.widget.FrameLayout.onMeasure(FrameLayout.Java:194)
at Android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.Java:135)
at Android.view.View.measure(View.Java:18804)
at Android.view.ViewGroup.measureChildWithMargins(ViewGroup.Java:5954)
at Android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.Java:1465)
at Android.widget.LinearLayout.measureVertical(LinearLayout.Java:748)
at Android.widget.LinearLayout.onMeasure(LinearLayout.Java:630)
at Android.view.View.measure(View.Java:18804)
at Android.view.ViewGroup.measureChildWithMargins(ViewGroup.Java:5954)
at Android.widget.FrameLayout.onMeasure(FrameLayout.Java:194)
at Android.view.View.measure(View.Java:18804)
at Android.view.ViewGroup.measureChildWithMargins(ViewGroup.Java:5954)
at Android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.Java:1465)
at Android.widget.LinearLayout.measureVertical(LinearLayout.Java:748)
at Android.widget.LinearLayout.onMeasure(LinearLayout.Java:630)
at Android.view.View.measure(View.Java:18804)
at Android.view.ViewGroup.measureChildWithMargins(ViewGroup.Java:5954)
at Android.widget.FrameLayout.onMeasure(FrameLayout.Java:194)
at com.Android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.Java:2643)
at Android.view.View.measure(View.Java:18804)
at Android.view.ViewRootImpl.performMeasure(ViewRootImpl.Java:2112)
at Android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.Java:1228)
at Android.view.ViewRootImpl.performTraversals(ViewRootImpl.Java:1464)
at Android.view.ViewRootImpl.doTraversal(ViewRootImpl.Java:1119)
at Android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.Java:6060)
at Android.view.Choreographer$CallbackRecord.run(Choreographer.Java:858)
at Android.view.Choreographer.doCallbacks(Choreographer.Java:670)
at Android.view.Choreographer.doFrame(Choreographer.Java:606)
at Android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.Java:844)
at Android.os.Handler.handleCallback(Handler.Java:746)
at Android.os.Handler.dispatchMessage(Handler.Java:95)
at Android.os.Looper.loop(Looper.Java:148)
at Android.app.ActivityThread.main(ActivityThread.Java:5443)
at Java.lang.reflect.Method.invoke(Native Method)
at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:728)
at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:618)
j'ai aussi vu le même problème dans ce link et j'applique sa solution mais cela ne fonctionnera pas pour moi .. je suis toujours bloqué, aidez-moi .
oh oui .. j'ai finalement trouvé mon erreur .. tout d'abord il n'y a pas d'erreur dans mon code. tout va bien.
je dispose de trois onglets et je ne passe que pour un tablayout et les deux autres deviennent nuls. Je dois donc appliquer trois instructions de commutation.
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position){
case product_result:
fragment = FragmentProduct.newInstance("","");
break;
}
return fragment;
}
au lieu
public Fragment getItem(int num) {
Fragment fragment = null;
switch (num) {
case TAB_PRODUCT_RESULT:
fragment = FragmentProduct.newInstance("", "");
break;
case TAB_SECOND:
fragment = MyFragment.getInstance(num);
break;
case TAB_THIRD:
fragment = MyFragment.getInstance(num);
break;
}
return fragment;
}
c'est tout..
Je pense que le problème est dans la méthode public Fragment getItem(int position)
de votre MyPagerAdapter
. Votre extrait de code ci-dessous renvoie des fragments null
.
Fragment fragment = null;
switch(position){
case product_result:
fragment = FragmentProduct.newInstance("","");
break;
}
return fragment;
Vous obtenez uniquement un vrai fragment pour la position 0
, car product_result
est initialisé à 0
. Dans tous les autres cas, il retourne null. Modifiez le fragment de code ci-dessus pour toujours renvoyer une instance de fragment non null.
J'ai eu un problème similaire, j'ai essayé de supprimer le fragment null et cette erreur de cause. Null check a résolu le problème. Vérifiez vos transactions de fragments. Vous ne pouvez pas ajouter de fragment nul.
Fragment fragment = null;
if (fragment != null)
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment, "id").commit();