Solution: updated dependecies
I want to make an app with three tabs, setup with a ViewPager and TabLayout. I'm using FragmentPagerAdapter. Layouts and activities are error-free, but still the app crashes. Activities, layouts and crashreport below.
2019-08-11 14:03:15.791 25598-25598/ga.rndevelopment.inventory E/AndroidRuntime: FATAL EXCEPTION: main
Process: ga.rndevelopment.inventory, PID: 25598
java.lang.BootstrapMethodError: Exception from call site #42 bootstrap method
at com.google.android.material.tabs.TabLayout$TabView.addOnLayoutChangeListener(TabLayout.java:2592)
at com.google.android.material.tabs.TabLayout$TabView.update(TabLayout.java:2508)
at com.google.android.material.tabs.TabLayout$TabView.setTab(TabLayout.java:2437)
at com.google.android.material.tabs.TabLayout.createTabView(TabLayout.java:1501)
at com.google.android.material.tabs.TabLayout.newTab(TabLayout.java:855)
at com.google.android.material.tabs.TabLayout.populateFromPagerAdapter(TabLayout.java:1477)
at com.google.android.material.tabs.TabLayout.setPagerAdapter(TabLayout.java:1468)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1379)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1340)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1320)
at ga.rndevelopment.inventory.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:7458)
at android.app.Activity.performCreate(Activity.java:7448)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3382)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3587)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2185)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7593)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Caused by: java.lang.ClassCastException: Bootstrap method returned null
at com.google.android.material.tabs.TabLayout$TabView.addOnLayoutChangeListener(TabLayout.java:2592)
at com.google.android.material.tabs.TabLayout$TabView.update(TabLayout.java:2508)
at com.google.android.material.tabs.TabLayout$TabView.setTab(TabLayout.java:2437)
at com.google.android.material.tabs.TabLayout.createTabView(TabLayout.java:1501)
at com.google.android.material.tabs.TabLayout.newTab(TabLayout.java:855)
at com.google.android.material.tabs.TabLayout.populateFromPagerAdapter(TabLayout.java:1477)
at com.google.android.material.tabs.TabLayout.setPagerAdapter(TabLayout.java:1468)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1379)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1340)
at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1320)
at ga.rndevelopment.inventory.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:7458)
at android.app.Activity.performCreate(Activity.java:7448)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3382)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3587)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2185)
at android.os.Handler.dispatchMessage(Handler.java:112)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7593)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
2019-08-11 14:03:15.810 25598-25598/ga.rndevelopment.inventory I/Process: Sending signal. PID: 25598 SIG: 9
MainActivity
package ga.rndevelopment.inventory;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = findViewById(R.id.viewPager);
setupViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TabOne(), "ONE");
adapter.addFragment(new TabTwo(), "TWO");
adapter.addFragment(new TabThree(), "THREE");
viewPager.setAdapter(adapter);
}
}
activity_main
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
android:layout_gravity="top" />
</androidx.viewpager.widget.ViewPager>
</RelativeLayout>
PagerAdapter
package ga.rndevelopment.inventory;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> FragmentList = new ArrayList<>();
private final List<String> FragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public Fragment getItem(int position) {
return FragmentList.get(position);
}
#Override
public int getCount() {
return FragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
FragmentList.add(fragment);
FragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return FragmentTitleList.get(position);
}
}
TabOne
package ga.rndevelopment.inventory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
public class TabOne extends Fragment {
public TabOne() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_standard, container, false);
}
}
As Android Studio doesn't throw an error anywhere, I don't know in which class I need to search for eventual missing parts of code. Anyone some reproduction ideas?
Thanks in advance
Caused by: java.lang.ClassCastException: Bootstrap method returned
null
work on this one...casting goes wrong with null values.
Related
I am trying to add a player using Sliding Up Panel but the app crashes on startup. If you want to see my full code;
https://github.com/Kailash8460/poptune.git
MainActivity.java
package com.example.poptunemusicplayerapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import com.example.poptunemusicplayerapplication.fragments.MainFragment;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
public class MainActivity extends AppCompatActivity {
private static final int KEY_PER = 123;
private SlidingUpPanelLayout panelLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{Manifest.permission.READ_EXTERNAL_STORAGE}, KEY_PER);
return;
}
else {
UiInitialize();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case KEY_PER:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
UiInitialize();
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void UiInitialize() {
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
panelLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
Fragment fragment = new MainFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment);
transaction.commit();
/*List<Song> songList = new SongLoader().getAllSongs(this);
for (Song song : songList){
Log.i("DATA","Title:" + song.title);
}*/
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<com.sothree.slidinguppanel.SlidingUpPanelLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/sliding_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
app:umanoPanelHeight="68dp"
app:umanoShadowHeight="4dp"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="#+id/control_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</com.sothree.slidinguppanel.SlidingUpPanelLayout>
MainFragment.java
Here there is no issue on SongsFragment, ArtistFragment and AlbumFragment files, because I have run this application before adding the sliding up panel and that was successfully run but after adding this Sliding Up Panel application crashes on startup.
package com.example.poptunemusicplayerapplication.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.poptunemusicplayerapplication.R;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
public class MainFragment extends Fragment {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
setUpViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
private void setUpViewPager(ViewPager viewPager) {
FragmentAdapter adapter = new FragmentAdapter(getActivity().getSupportFragmentManager());
adapter.AddFragments(new SongsFragment(), "Songs");
adapter.AddFragments(new ArtistFragment(), "Artist");
adapter.AddFragments(new AlbumFragment(), "Album");
viewPager.setAdapter(adapter);
}
private class FragmentAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentList = new ArrayList<>();
private List<String> titleList = new ArrayList<>();
public FragmentAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void AddFragments(Fragment fragment, String title) {
fragmentList.add(fragment);
titleList.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
}
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentmainlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.MainFragment">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appbar"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="#+id/toolbar"
app:layout_scrollFlags="scroll|enterAlways"
android:background="?attr/colorPrimary"
app:popupTheme="#style/Theme.AppCompat.Light"/>
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabs"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_pager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Errors
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.poptunemusicplayerapplication, PID: 28426
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.poptunemusicplayerapplication/com.example.poptunemusicplayerapplication.MainActivity}: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.sothree.slidinguppanel.SlidingUpPanelLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2988)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3073)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7025)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.sothree.slidinguppanel.SlidingUpPanelLayout
Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class com.sothree.slidinguppanel.SlidingUpPanelLayout
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
at com.example.poptunemusicplayerapplication.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:7258)
at android.app.Activity.performCreate(Activity.java:7249)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1222)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2941)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3073)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7025)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.IllegalArgumentException: gravity must be set to either top or bottom
at com.sothree.slidinguppanel.SlidingUpPanelLayout.setGravity(SlidingUpPanelLayout.java:366)
at com.sothree.slidinguppanel.SlidingUpPanelLayout.<init>(SlidingUpPanelLayout.java:288)
at com.sothree.slidinguppanel.SlidingUpPanelLayout.<init>(SlidingUpPanelLayout.java:270)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
at com.example.poptunemusicplayerapplication.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:7258)
at android.app.Activity.performCreate(Activity.java:7249)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1222)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2941)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3073)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1734)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7025)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
getting error at MainActivity.java:39
Line 39 of MainActivity.java:-
setContentView(R.layout.activity_main);
After looking at the layout in the demo app for SlidingUpPanelLayout, I see it is expecting the android:gravity attribute to be set, not android:layout_gravity.
Try this instead for your layout:
<?xml version="1.0" encoding="utf-8"?>
<com.sothree.slidinguppanel.SlidingUpPanelLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/sliding_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
app:umanoPanelHeight="68dp"
app:umanoShadowHeight="4dp"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="#+id/control_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</com.sothree.slidinguppanel.SlidingUpPanelLayout>
Hey Everyone this is my first android app I'm new in Android development. When I try to run this app on my device suddenly it crashes.
And my app crash when I try to log in
This is the main code of JAVA
package com.example.javanots;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirestoreRegistrar;
import com.google.firebase.firestore.Query;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import java.text.BreakIterator;
public class NotesActivity extends AppCompatActivity {
FloatingActionButton mcreatenotefab;
private FirebaseAuth firebaseAuth;
RecyclerView mrecyclerview;
StaggeredGridLayoutManager staggeredGridLayoutManager;
FirebaseUser firebaseUser;
FirebaseFirestore firebaseFirestore;
FirestoreRecyclerAdapter<firebasemodel,NoteViewHolder> noteAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
mcreatenotefab=findViewById(R.id.createnotefab);
firebaseAuth=FirebaseAuth.getInstance();
//Get Data From Particular User Not from All user
firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
firebaseFirestore=FirebaseFirestore.getInstance();
getSupportActionBar().setTitle("All Notes");
mcreatenotefab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NotesActivity.this,Createnote.class));
}
});
//For Get All notes of User
Query query = firebaseFirestore.collection("notes").document(firebaseUser.getUid()).collection("mynotes").orderBy("title",Query.Direction.ASCENDING);
FirestoreRecyclerOptions<firebasemodel> allusernotes = new FirestoreRecyclerOptions.Builder<firebasemodel>().setQuery(query,firebasemodel.class).build();
noteAdapter = new FirestoreRecyclerAdapter<firebasemodel, NoteViewHolder>(allusernotes) {
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, int position, #NonNull firebasemodel firebasemodel) {
noteViewHolder.notetitle.setText(firebasemodel.getTitle());
noteViewHolder.notecontent.setText(firebasemodel.getContent());
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notes_layout,parent,false);
return new NoteViewHolder(view);
}
};
setContentView(R.layout.notes_layout);
mrecyclerview.findViewById(R.id.recyclerview);
mrecyclerview.setHasFixedSize(true);
staggeredGridLayoutManager=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mrecyclerview.setLayoutManager(staggeredGridLayoutManager);
mrecyclerview.setAdapter(noteAdapter);
}
public class NoteViewHolder extends RecyclerView.ViewHolder
{
private TextView notetitle;
private TextView notecontent;
LinearLayout mnote;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
notetitle=itemView.findViewById(R.id.notetitel);
notecontent=itemView.findViewById(R.id.notecontent);
mnote=itemView.findViewById(R.id.note);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.logout: firebaseAuth.signOut();
finish();
startActivity(new Intent(NotesActivity.this,MainActivity.class));
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
noteAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
noteAdapter.startListening();
if(noteAdapter!=null)
{
noteAdapter.startListening();
}
}
}
This is my XML codes
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NotesActivity">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/createnotefab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom|end"
android:layout_marginRight="30dp"
android:layout_marginBottom="30dp"
android:background="#A1F4FB"
android:src="#drawable/ic_baseline_add_24"
app:maxImageSize="40dp">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
I'm getting a List of Error I don't know how to solve it
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.javanots, PID: 24241
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javanots/com.example.javanots.NotesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3835)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4011)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2325)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8633)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
at com.example.javanots.NotesActivity.onCreate(NotesActivity.java:86)
at android.app.Activity.performCreate(Activity.java:8207)
at android.app.Activity.performCreate(Activity.java:8191)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3808)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4011)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2325)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8633)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Please Explain My problem's solution.
You are trying to call "findViewById" on mrecyclerview, that's not initialized yet (it's value is null).
It seems you are trying to do the right (bind the recyclerview), but the wrong way.
Give it a try by changing
mrecyclerview.findViewById(R.id.recyclerview);
to
mrecyclerview = (RecyclerView) findViewById(R.id.recyclerview);
After that, you'll be able to call methods on recyclerview, like .setAdapter(), ...
You had declared an object by the name mrecyclerview right? In line 86 of your code, instead of mrecyclerview.findViewById(R.id.recyclerview), try mrecyclerview = findViewById(R.id.recyclerview). Your error lines show that the problem was caused by a NullPointerException - Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
all. I'm having a problem.
I am trying to make an application, wherein a navigation-drawer is the source of navigation. In this application, I have some fragments with activities. The problem is, that if I run my profile fragment (which have uses tablayout and recyclerview) in an application for itself, it works. The application when it runs in it's own application.
However, when I attempt to add it to an application, wherein it should be a fragment in a navigation drawer, the application can compile, but when I click on the menuitem in the emulator, it crashes.
I will add the code I have at the moment:
Main Activity
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.content.Intent;
import com.example.sustainably.ui.myprofile.MainActivityProfile;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_friends, R.id.nav_messages, R.id.nav_bookmarks, R.id.nav_myprofile, R.id.nav_discoverforums, R.id.nav_settings, R.id.nav_logout)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public boolean onNavigationItemSelected(MenuItem item) {
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (menuItem.getItemId()) {
case R.id.nav_home:
// code here
break;
case R.id.nav_friends:
// code here
break;
case R.id.nav_messages:
// code here
break;
case R.id.nav_bookmarks:
// code here
break;
case R.id.nav_myprofile:
Intent intent=new Intent(MainActivity.this, MainActivityProfile.class);
startActivity(intent);
break;
case R.id.nav_discoverforums:
//code here
break;
case R.id.nav_settings:
//code here
break;
case R.id.nav_logout:
//code here
break;
}
DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
return false;
}
}
and in the profile fragment package i have 6 java classes:
BookmarkModel.java
private String Title;
private int Photo;
public BookmarkModel() {
}
public BookmarkModel(String title, int photo) {
Title = title;
Photo = photo;
}
// Getter
public String getTitle() {
return Title;
}
public int getPhoto() {
return Photo;
}
// Setter
public void setTitle(String title) {
Title = title;
}
public void setPhoto(int photo) {
Photo = photo;
}
}
MainActivityProfile.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.example.sustainably.R;
import com.google.android.material.tabs.TabLayout;
public class MainActivityProfile extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_myprofile);
tabLayout = (TabLayout) findViewById(R.id.tablayout_id);
viewPager = (ViewPager) findViewById(R.id.viewpager_id);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
// Add Fragment Here
adapter.AddFragment(new PublicBookmarkFragment(), "Public Bookmarks");
adapter.AddFragment(new LatestPostsFragment(), "Latest Posts");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_outline_bookmarks_24);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_outline_textsms_24);
}
}
PublicBookmarkFragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.sustainably.R;
import java.util.ArrayList;
import java.util.List;
public class PublicBookmarkFragment extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<BookmarkModel> lstBookmarkModel;
public PublicBookmarkFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.public_bookmarks_fragment, container, false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.bookmarks_recyclerview);
RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(), lstBookmarkModel);
myrecyclerview.setLayoutManager(new GridLayoutManager(getContext(), 2));
myrecyclerview.setAdapter(recyclerAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstBookmarkModel = new ArrayList<>();
lstBookmarkModel.add(new BookmarkModel("Salad", R.drawable.annapelzer));
lstBookmarkModel.add(new BookmarkModel("Pasta", R.drawable.brookelark_1));
lstBookmarkModel.add(new BookmarkModel("Fruit Salad", R.drawable.brookelark_2));
lstBookmarkModel.add(new BookmarkModel("Smoothies with fruit", R.drawable.brookelark_3));
lstBookmarkModel.add(new BookmarkModel("Soup", R.drawable.cala));
lstBookmarkModel.add(new BookmarkModel("Lobster Salad", R.drawable.davide_cantelli));
lstBookmarkModel.add(new BookmarkModel("Breakfast Toast with Berries", R.drawable.joseph_gonzales));
}
}
RecyclerViewAdapter
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.sustainably.R;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
Context mContext;
List<BookmarkModel> mData;
public RecyclerViewAdapter(Context mContext, List<BookmarkModel> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_bookmarks, parent, false);
MyViewHolder vHolder = new MyViewHolder(v);
return vHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.tv_title.setText(mData.get(position).getTitle());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tv_title;
private ImageView img;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
tv_title = (TextView) itemView.findViewById(R.id.title_bookmarks);
img = (ImageView) itemView.findViewById(R.id.img_bookmarks);
}
}
}
ViewPagerAdapter
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
}
#Override
public int getCount() {
return lstTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment (Fragment fragment, String title) {
lstFragment.add(fragment);
lstTitles.add(title);
}
}
fragment_myprofile.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myprofile"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<include
layout="#layout/profile_header"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/TabContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tablayout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabIconTint="#color/dark_green"
app:tabIndicatorColor="#color/dark_green"
app:tabInlineLabel="true"
app:tabMode="fixed"
app:tabRippleColor="#color/light_green"
app:tabSelectedTextColor="#color/dark_green"
app:tabTextAppearance="#style/TextAppearance.AppCompat.Small"></com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpager_id"></androidx.viewpager.widget.ViewPager>
</LinearLayout>
</LinearLayout>
public_bookmarks_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bookmarks_recyclerview">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
item_bookmarks.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardUseCompatPadding="true"
app:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/img_bookmarks"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/title_bookmarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/dark_green"
android:padding="5dp"
android:text="#string/title"
android:textSize="16sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
I'm new at asking questions in here, so if I missed some information you need, or messed something up, please tell me what you need, and I will provide that aswell. Hope you can help.
For clarification as requested:
Logcat errormessages when I click on the menu
2021-05-06 15:28:54.971 18053-18053/com.example.sustainably E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sustainably, PID: 18053
java.lang.ClassCastException: com.example.sustainably.ui.myprofile.MainActivityProfile cannot be cast to androidx.fragment.app.Fragment
at androidx.fragment.app.Fragment.instantiate(Fragment.java:548)
at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57)
at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:390)
at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:162)
at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:58)
at androidx.navigation.NavController.navigate(NavController.java:1066)
at androidx.navigation.NavController.navigate(NavController.java:944)
at androidx.navigation.NavController.navigate(NavController.java:877)
at androidx.navigation.ui.NavigationUI.onNavDestinationSelected(NavigationUI.java:97)
at androidx.navigation.ui.NavigationUI$3.onNavigationItemSelected(NavigationUI.java:453)
at com.google.android.material.navigation.NavigationView$1.onMenuItemSelected(NavigationView.java:217)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985)
at com.google.android.material.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:416)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mobile_navigation"
app:startDestination="#+id/nav_home">
<fragment
android:id="#+id/nav_home"
android:name="com.example.sustainably.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home" />
<fragment
android:id="#+id/nav_friends"
android:name="com.example.sustainably.ui.friends.FriendsFragment"
android:label="#string/menu_friends"
tools:layout="#layout/fragment_friends" />
<fragment
android:id="#+id/nav_bookmarks"
android:name="com.example.sustainably.ui.bookmarks.BookmarksFragment"
android:label="#string/menu_bookmarks"
tools:layout="#layout/fragment_bookmarks" />
<fragment
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
<fragment
android:id="#+id/nav_discoverforums"
android:name="com.example.sustainably.ui.discoverforums.DiscoverForumsFragment"
android:label="#string/menu_discoverforums"
tools:layout="#layout/fragment_discoverforums" />
<fragment
android:id="#+id/nav_messages"
android:name="com.example.sustainably.ui.messages.MessagesFragment"
android:label="#string/menu_messages"
tools:layout="#layout/fragment_messages" />
</navigation>
The code in it's entirety: https://github.com/CabCabz/SustainablyProblem.git
suggestion:
I analyzed your code, you should not used default navigation drawer setup with mobile_navigation.xml.
Setup drawer menu without mobile_navigation.xml: https://stackoverflow.com/a/67389269/12660050
Solution:
1) As you are using default drawer with mobile_navigation.xml you do not need to
use onNavigationItemSelected() method. So, before doing anything remove it from
your Main Activity.
2) Go to the mobile_navigation.xml file and change tag name fragment to activity in which you are using as a MainActivityProfile.java.
Before:
<fragment
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
After:
<activity
android:id="#+id/nav_myprofile"
android:name="com.example.sustainably.ui.myprofile.profileRecycle.MyProfileFragment"
android:label="#string/menu_myprofile"
tools:layout="#layout/fragment_myprofile" />
By changing only this you can solve your problem!!
Sorry for the code dump, I'm new to android and don't know where the problem is. I'm trying to implement swipe views in my android app and I'm having some trouble. I tried following this tutorial and this video but I'm getting some errors. I want the tabbed interface in my MainActivity
Here is my MainActivity.java
package com.loomius.loomius;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new FixedTabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
I'm getting this error for getSupporFragmentManager()
'FixedTabsPagerAdapter(android.app.FragmentManager)' in 'com.loomius.loomius.FixedTabsPagerAdapter' cannot be applied to '(android.support.v4.app.FragmentManager)'
and here is my FixedTabsPagerAdapter.java
package com.loomius.loomius;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
import values.MatchesFragment;
import values.SuggestedSongsFragment;
import values.UserFragment;
public class FixedTabsPagerAdapter extends FragmentPagerAdapter{
public FixedTabsPagerAdapter (FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new SearchFragment();
case 1:
return new UserFragment();
case 2:
return new MatchesFragment();
case 3:
return new SuggestedSongsFragment();
default:
return null;
}
}
Context context;
#Override
public CharSequence getPageTitle (int position) {
switch(position) {
case 0:
return context.getResources().getString(R.string.search_frag_title);
case 1:
return context.getResources().getString(R.string.user_frag_title);
case 2:
return context.getResources().getString(R.string.matches_frag_title);
case 3:
return context.getResources().getString(R.string.sugg_frag_title);
default:
return null;
}
}
}
I'm getting this error for the return type Fragment in the overridden method getItem
'getItem(int)' in 'com.loomius.loomius.FixedTabsPagerAdapter' clashes with 'getItem(int)' in 'android.support.v13.app.FragmentPagerAdapter'; attempting to use incompatible return type
I put the android.support.v4.view.ViewPager widget in my activity_main.xml right below the android.support.v7.widget.Toolbar widget.
Look at your FixedTabPagerAdapter constructor, you are trying to catch the reference of android.app.FragmentManager instance while passing the fragment manager of type android.support.v4.app.FragmentManagerwhich are two different classes.
Change the type of FragmentManager in your FixedTabPageAdapter to android.support.v4.app.FragmentManager and it should fix the issue.
For sliding pages with tabs do following.
Download or copy following two files on github and paste your project.
this is same as on developers.google.com except setDistributeEvenly method.
https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/SlidingTabLayout.java
https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/SlidingTabStrip.java
activity_main.xml
<your.package.name.SlidingTabLayout
android:clickable="true"
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</your.package.name.SlidingTabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
MyAdapter.java (Here i used two pages only)
class MyPagerAdapter extends FragmentPagerAdapter
{
String[] title = {"All","Favourites"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
if (position==0)
fragment= new All();
if (position==1)
fragment= new Favourites();
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
tab_view.xml (view of tab only , if you want u can also use ImageView here)
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/tab_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text=""
android:padding="15dp"
android:textStyle="bold"
android:textSize="25dp"
/>
</FrameLayout>
MainActivity.java
private SlidingTabLayout tabLayout;
private ViewPager pager;
tabLayout= (SlidingTabLayout) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
tabLayout.setCustomTabView(R.layout.tab_view,R.id.tab_title);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabLayout.setDistributeEvenly(true);
tabLayout.setViewPager(pager);
I have a Fragment Activity with customAdapter, but setAdapter returns me a nullpointerexception.
In the CustomAdapter I return a ParseQuery.
I cannot extend Fragment to ListFragment because then tabs stop working.
Please help me find the error.
MainActivity.java
package com.comunadigital.cuidatemasmaterial;
import android.app.ListFragment;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.comunadigital.cuidatemasmaterial.fragments.FragmentDirectorio;
import com.comunadigital.cuidatemasmaterial.fragments.FragmentFichas;
import com.comunadigital.cuidatemasmaterial.fragments.FragmentForo;
import com.comunadigital.cuidatemasmaterial.fragments.FragmentMedicinas;
import com.parse.GetCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;
public class MainActivity extends ActionBarActivity implements MaterialTabListener {
public static final String TAG = MainActivity.class.getSimpleName();
protected ProgressBar mProgressBar;
//int representing our 0th tab corresponding to the Fragment where search results are dispalyed
public static final int TAB_FICHAS = 0;
//int corresponding to our 1st tab corresponding to the Fragment where box office hits are dispalyed
public static final int TAB_DIRECTORIO = 1;
//int corresponding to our 2nd tab corresponding to the Fragment where upcoming movies are displayed
public static final int TAB_MEDICINAS = 2;
// int corresponde al cuarto tab
public static final int TAB_FORO = 3;
//int corresponding to the number of tabs in our Activity
public static final int TAB_COUNT = 4;
private Toolbar mToolbar;
private ViewGroup mContainerToolbar;
private MaterialTabHost mTabHost;
private ViewPager mPager;
private ViewPagerAdapter mAdapter;
//private FragmentDrawer mDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupTabs();
setupDrawer();
}
private void setupDrawer() {
mToolbar = (Toolbar) findViewById(R.id.app_bar);
mContainerToolbar = (ViewGroup) findViewById(R.id.container_app_bar);
//set the Toolbar as ActionBar
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.iconbar);
try{
getSupportActionBar().setDisplayShowHomeEnabled(true);
}catch(NullPointerException e){
e.printStackTrace();
}
}
private void setupTabs() {
mTabHost = (MaterialTabHost) findViewById(R.id.materialTabHost);
mPager = (ViewPager) findViewById(R.id.viewPager);
mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
//when the page changes in the ViewPager, update the Tabs accordingly
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mTabHost.setSelectedNavigationItem(position);
}
});
//Add all the Tabs to the TabHost
for (int i = 0; i < mAdapter.getCount(); i++) {
mTabHost.addTab(
mTabHost.newTab()
.setIcon(mAdapter.getIcon(i))
.setTabListener(this));
}
}
#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.logoutButton) {
/*
* Log current user out using ParseUser.logOut()
*/
ParseUser.logOut();
Intent intent = new Intent(this, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(MaterialTab materialTab) {
//when a Tab is selected, update the ViewPager to reflect the changes
mPager.setCurrentItem(materialTab.getPosition());
}
#Override
public void onTabReselected(MaterialTab materialTab) {
}
#Override
public void onTabUnselected(MaterialTab materialTab) {
}
//FragmentStatePagerAdapter
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
//AQUI PONEMOS LOS ICONOS GRAFICOS
int icons[] = {R.drawable.ficha,
R.drawable.doctor,
R.drawable.medicina,
R.drawable.foro};
FragmentManager fragmentManager;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
fragmentManager = fm;
}
#Override
public Fragment getItem(int num) {
Fragment fragment = null;
// L.m("getItem called for " + num);
switch (num) {
case TAB_FICHAS:
fragment = FragmentFichas.newInstance(getApplicationContext());
break;
case TAB_DIRECTORIO:
fragment = FragmentDirectorio.newInstance();
break;
case TAB_MEDICINAS:
fragment = FragmentMedicinas.newInstance();
break;
case TAB_FORO:
fragment = FragmentForo.newInstance();
break;
}
return fragment;
}
#Override
public int getCount() {
return TAB_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return getResources().getStringArray(R.array.tabs)[position];
}
private Drawable getIcon(int position) {
return getResources().getDrawable(icons[position]);
}
}
}
FragmentFichas.java
package com.comunadigital.cuidatemasmaterial.fragments;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
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 com.comunadigital.cuidatemasmaterial.DoctoresActivity;
import com.comunadigital.cuidatemasmaterial.MainActivity;
import com.comunadigital.cuidatemasmaterial.R;
import com.comunadigital.cuidatemasmaterial.adapters.CustomAdapter;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseUser;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentFichas#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentFichas extends Fragment {
private static Context mContext;
private ParseQueryAdapter<ParseObject> mainAdapter;
public FragmentFichas() {
// Required empty public constructor
}
public static FragmentFichas newInstance(Context context) {
mContext = context;
return new FragmentFichas();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView mList = (ListView) getActivity().findViewById(R.id.list);
CustomAdapter urgentTodosAdapter = new CustomAdapter(getActivity());
mList.setAdapter(urgentTodosAdapter);
urgentTodosAdapter.loadObjects();
}
#Override
public void onResume() {
super.onResume();
//urgentTodosAdapter.loadObjects();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fichas, container, false);
/*
mList = (ListView) getActivity().findViewById(R.id.list);
urgentTodosAdapter = new CustomAdapter(container.getContext());
mList.setAdapter(urgentTodosAdapter);
urgentTodosAdapter.loadObjects();
*/
return view;
}
}
CustomAdapter.java
package com.comunadigital.cuidatemasmaterial.adapters;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.parse.ParseFile;
import com.parse.ParseImageView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseUser;
import com.comunadigital.cuidatemasmaterial.R;
/**
* Created by proyectos1 on 15/07/2015.
*/
public class CustomAdapter extends ParseQueryAdapter<ParseObject> {
public CustomAdapter(Context context) {
// Use the QueryFactory to construct a PQA that will only show
// Todos marked as high-pri
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery<ParseObject> create() {
ParseQuery query = new ParseQuery("FichasMedicas");
query.whereEqualTo("user", ParseUser.getCurrentUser());
return query;
}
});
}
// Customize the layout by overriding getItemView
#Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.urgent_item, null);
}
super.getItemView(object, v, parent);
// Add and download the image
ParseImageView todoImage = (ParseImageView) v.findViewById(R.id.icon);
ParseFile imageFile = object.getParseFile("foto");
if (imageFile != null) {
todoImage.setParseFile(imageFile);
todoImage.loadInBackground();
}
// Add the title view
TextView titleTextView = (TextView) v.findViewById(R.id.text1);
titleTextView.setText(object.getString("nombre"));
// Add a reminder of how long this item has been outstanding
//TextView timestampView = (TextView) v.findViewById(R.id.timestamp);
//timestampView.setText(object.getCreatedAt().toString());
return v;
}
}
ActivityMain.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<it.neokree.materialtabs.MaterialTabHost
android:id="#+id/materialTabHost"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_below="#+id/app_bar"
app:accentColor="#color/colorAccent"
app:hasIcons="true"
app:iconColor="#android:color/white"
app:primaryColor="#color/colorPrimary" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="#+id/materialTabHost"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
FragmentFichas.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
LogError
07-20 15:46:45.375 9596-9596/com.comunadigital.cuidatemasmaterial E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.comunadigital.cuidatemasmaterial, PID: 9596
java.lang.NullPointerException
at com.comunadigital.cuidatemasmaterial.fragments.FragmentFichas.onCreate(FragmentFichas.java:59)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1766)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:917)
at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:846)
at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:860)
at android.support.v4.app.FragmentStatePagerAdapter.setPrimaryItem(FragmentStatePagerAdapter.java:152)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1103)
at android.support.v4.view.ViewPager.populate(ViewPager.java:951)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1473)
at android.view.View.measure(View.java:16497)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:868)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
You need to get the ListView from the inflated View in the Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fichas, container, false);
//It's not in the Activity layout:
//mList = (ListView) getActivity().findViewById(R.id.list);
//It's in the Fragment layout:
mList = (ListView) view.findViewById(R.id.list);
urgentTodosAdapter = new CustomAdapter(getActivity());
mList.setAdapter(urgentTodosAdapter);
urgentTodosAdapter.loadObjects();
return view;
}
Also be sure to declare urgentTodosAdapter as an instance variable:
public class FragmentFichas extends Fragment {
private static Context mContext;
private ParseQueryAdapter<ParseObject> mainAdapter;
private CustomAdapter urgentTodosAdapter; //added
//.............