_
Hello members of stackoverflow!
I worked successfully with the ViewPager (VP) on a "normal" activity.
Now I tried to use almost the same way for an Android Wear app.
In my MainActivity, which contains the VP, I faced different errors like:
Error 1: (getFragmentManager() -> "Cannot be applied"
Error 2: super(manager); -> "Cannot be applied"
Error 3: public Fragment getItem(int i); -> "Incompatible return type"
I found this thread and was able to fix those errors by changing the imports + changing the build.gradle.
How to implement view pager in Android watch?
Those are now my imports in my MainActivity.java:
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.wearable.activity.WearableActivity;
import java.util.ArrayList;
import java.util.List;
This is the rest of the MainActivity:
public class MainActivity extends WearableActivity
{
ViewPager vp; // Variable for Viewpager
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Link to layout
ViewPager vp = findViewById(R.id.vp); // Link variable to ID
SetUpViewPager(vp); // Run viewpager method
}
public void SetUpViewPager(ViewPager viewpager)
{
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getFragmentManager());
Adapter.AddPageFragment(new Fragment1(), "Fragment1"); // Load page 1 inside of ViewPager
Adapter.AddPageFragment(new Fragment2(), "Fragment2"); // Load page 2 inside of ViewPager
viewpager.setAdapter(Adapter);
}
public class MyViewPagerAdapter extends android.support.v4.app.FragmentPagerAdapter
{
private List<Fragment> MyFragment = new ArrayList<>();
private List<String> MyPageTitle = new ArrayList<>();
public MyViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
public void AddPageFragment(Fragment Frag, String Title)
{
MyFragment.add(Frag);
MyPageTitle.add(Title);
}
#Override
public Fragment getItem(int i)
{
return MyFragment.get(i);
}
#Nullable
#Override
public CharSequence getPageTitle(int position)
{
return MyPageTitle.get(position);
}
#Override
public int getCount()
{
return 2; // 2 pages total
}
}
}
Strange is that is says ViewPager vp; -> Field 'vp' is never used!
Fragment1: (Fragment2 is the same except for 2/two)
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment
{
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View fragmentOne = inflater.inflate(R.layout.fragment1, container, false); // Link view and layout
return fragmentOne;
}
}
The XML files for the fragments are just constraint layouts with each 1 button.
The content_main.xml contains the VP which accesses the activity_main.xml.
I used the same way on the normal smartphone device and it worked flawlessly.
The problem is that everytime I start the app on the Wear Emulator, it immediately crashes.
This is what Logcat says:
10-23 14:40:32.909 2203-2203/com.example.user.wearvp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.wearvp, PID: 2203
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.wearvp/com.example.user.wearvp.MainActivity}: java.lang.NullPointerException:
Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at com.example.user.wearvp.MainActivity.SetUpViewPager(MainActivity.java:35)
at com.example.user.wearvp.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Any help will be appreciated!
P.S:
If I forgot to mention anything important, please, just ask and I will give you the needed information!
Best regards
The stack trace indicates that there is no view with the id vp defined in your activity_main.xml layout file. I'm not completely sure what you mean with:
The content_main.xml contains the VP which accesses the activity_main.xml.
If vp is defined in the content_main.xml layout, then that might be the one you should use with setContentView() (instead of the current activity_main.xml).
Strange is that is says ViewPager vp; -> Field 'vp' is never used!
The local variable vp (defined inside the onCreate method) is shadowing the instance variable vp. If you need it to have object-level scope just remove ViewPager when you assign a value to it.
Related
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
/**
* Created by name on 3/13/17.
* Used for the specials tab to allow a list of days to choose what special one would like to view
*/
public class SpecialsScroll extends ListFragment implements AdapterView.OnItemClickListener{
public SpecialsScroll(){
//Empty Constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.fragment_specials_scroll, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(ArrayAdapter.createFromResource(getActivity(), R.array.days, android.R.layout.simple_list_item_1)); //Loads array into the ListFragment
getListView().setOnItemClickListener(this); //activates the listener for this Fragment class
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){ // For checking when a user taps on an option
SpecialsPage specialsPage = new SpecialsPage();
Bundle foodArgs = new Bundle();
switch (position){ // checks what option is chosen and sends respective keys as parameters
case 0:
int[] keysMonday = {R.string.boom_boom_enchiladas_key, R.string.tacos_mexican_key};
foodArgs.putIntArray("keys", keysMonday);
break;
case 1:
int[] keysTuesday = {R.string.shrimp_avocado_tacos_key, R.string.green_chile_chicken_enchiladas_key};
foodArgs.putIntArray("keys", keysTuesday);
break;
}
specialsPage.setArguments(foodArgs);
getActivity().getFragmentManager().beginTransaction().replace(R.id.container, specialsPage).addToBackStack(null).commit();
}
}
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity{
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if(getFragmentManager().findFragmentByTag("CURRENT") == null){
getFragmentManager().beginTransaction().add(R.id.container, new SpecialsScroll(), "CURRENT").commit();
}
switch (item.getItemId()) {
case R.id.special:
getFragmentManager().beginTransaction().replace(R.id.container, new SpecialsScroll(), "CURRENT").commit();
return true;
case R.id.locations:
getFragmentManager().beginTransaction().replace(R.id.container, new LocationsScroll(), "CURRENT").commit();
return true;
case R.id.order:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getFragmentManager().beginTransaction().add(R.id.container, new SpecialsScroll(), "CURRENT").commit();
}
}
So, I am trying to create a ListView and everything in the code works, but suddenly I am unable to get the xml to recognize the android:id/list attribute for some reason, I don't know why. When I click on an item in the listview in my app it still does what it should, I just really want to get rid of the error.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<TextView
android:id="#+id/text_specialsscroll"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
04-26 14:06:30.299 2576-2576
/com.namename.www.name
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.namename.www.name, PID: 2576
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.namename.www.name/com.namename.www.name.MainActivity}: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.RuntimeException: Content has view with id attribute 'android.R.id.list' that is not a ListView class
at android.app.ListFragment.ensureList(ListFragment.java:402)
at android.app.ListFragment.onViewCreated(ListFragment.java:203)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1010)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentController.execPendingActions(FragmentController.java:371)
at android.app.Activity.performStart(Activity.java:6695)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Change your id to this:
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
Before posting I checked many questions but they didn't helped me. Most of the answers says that the ViewPager is in different layout, so that is why it generating null pointer exception.
Below is my stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main Process: pdfshare.hemanthreddy.com.pdfshare, PID: 29092
java.lang.RuntimeException: Unable to start activity ComponentInfo{pdfshare.hemanthreddy.com.pdfshare/pdfshare.hemanthreddy.com.pdfshare.activities.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at pdfshare.hemanthreddy.com.pdfshare.activities.HomeScreen.onCreate(HomeScreen.java:39)
at android.app.Activity.performCreate(Activity.java:6259)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
This is my xml file where I have declared Viewpager
activity_home_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="pdfshare.hemanthreddy.com.pdfshare.activities.HomeScreen">
<android.support.v4.view.ViewPager
android:id="#+id/viewpagerhome"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
Activity class HomeScreen.java
package pdfshare.hemanthreddy.com.pdfshare.activities;
import android.graphics.Color;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarBadge;
import com.roughike.bottombar.BottomBarTab;
import com.roughike.bottombar.OnMenuTabSelectedListener;
import com.roughike.bottombar.OnTabSelectedListener;
import pdfshare.hemanthreddy.com.pdfshare.R;
import pdfshare.hemanthreddy.com.pdfshare.fragments.GroupsFragment;
import pdfshare.hemanthreddy.com.pdfshare.fragments.HomeFragment;
import pdfshare.hemanthreddy.com.pdfshare.fragments.NotificationsFragment;
import pdfshare.hemanthreddy.com.pdfshare.fragments.ProfileFragment;
public class HomeScreen extends AppCompatActivity {
ViewPager pager;
BottomBar bottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
bottomBar = BottomBar.attach(this,savedInstanceState);
pager = (ViewPager) findViewById(R.id.viewpagerhome);
MyPagerAdapter obj = new MyPagerAdapter(getSupportFragmentManager());
//the following two if statements are used to check if objects are null
if(obj.getCount()==4)
Log.e("obj","not null");
if(pager == null)
Log.e("pager","null");
pager.setAdapter(obj);
bottomBar.setItems(new BottomBarTab(R.mipmap.ic_action_home_24,"home"),
new BottomBarTab(R.mipmap.ic_action_user_group,"groups"),
new BottomBarTab(R.mipmap.ic_action_notification,"notifications"),
new BottomBarTab(R.mipmap.ic_action_profile,"profile")
);
bottomBar.setOnItemSelectedListener(new OnTabSelectedListener() {
#Override
public void onItemSelected(int position) {
T oast.makeText(getApplicationContext(),position,Toast.LENGTH_LONG).show();
pager.setCurrentItem(position);
}
});
BottomBarBadge message = bottomBar.makeBadgeForTabAt(2,"red",10);
message.show();
}
private class MyPagerAdapter extends FragmentStatePagerAdapter
{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new HomeFragment();
case 1:
return new GroupsFragment();
case 2:
return new NotificationsFragment();
case 3:
return new ProfileFragment();
default:
return new HomeFragment();
}
}
#Override
public int getCount() {
return 4;
}
}
}
E/obj: not null
E/pager: null
dont know why pager object is null.
Please help me I am trying to load 4 fragments in viewPager, thank you.
it means your variable obj of type MyPagerAdapter is null, there is an error with it's return value.
MyPagerAdapter obj = new MyPagerAdapter(getSupportFragmentManager());
That line is the problem, the problem could be in your custom adapter, or your get support fragment manager. if they were working the obj would not be null.
i bet if you comment out that line and the setadapter line it won't crash anymore, unless you have bigger problems
I am trying to link a Fragment, RecycleView and CardView using a variation of the tutorial found on:
http://www.treyrobinson.net/blog/android-l-tutorials-part-3-recyclerview-and-cardview/
Unfortunately my app crashes with the following error message:
"java.lang.IllegalStateException: RecyclerView has no LayoutManager"
I am fairly new with Android development. I tried to find similar issues on Stackoverflow but am unable to find the issue. Any help would be greatly appreciated!
Layout of the main activity: "activity_library.xml":
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LibraryActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/library_activity_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LibraryActivity"
/>
</RelativeLayout>
The main activity class "LibraryActivity.java":
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class LibraryActivity extends AppCompatActivity{
private static final String TAG = LibraryActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); /**Create the activity and populate the savedInstanceState if the activity existed but has been destroyed (otherwise savedInstanceState will return 'null'*/
setContentView(R.layout.activity_library); /** Call to the XML layout library which display the activity */
if (savedInstanceState != null) {
// Restore value of members from saved state
} else {
// Probably initialize members with default values for a new instance
}
try {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
BooksFragment bookFragment = new BooksFragment();
fragmentTransaction.add(R.id.library_activity_recycler_view,bookFragment);
/*The line below is the one generating the error - java.lang.IllegalStateException: RecyclerView has no LayoutManager*/
fragmentTransaction.commit();
}
catch(Exception e){
Log.d(TAG,"[ERROR] " + e.getMessage());
}
}
}
The layout of the fragment "fragment_books.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="match_parent"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/Book_Recycler_View"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
And the fragment class:
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BooksFragment extends Fragment {
public BooksFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_library, container, false);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView bookRecycler = (RecyclerView) v.findViewById(R.id.library_activity_recycler_view);
bookRecycler.setLayoutManager(layoutManager);
BookRecyclerViewAdapter adapter = new BookRecyclerViewAdapter();
bookRecycler.setAdapter(adapter);
/*In the line below should we return the view 'v' or the RecyclerView 'bookRecycler'??*/
return bookRecycler;
}
}
As I said I am fairly new to Android and therefore apologies if my code contains quite a few errors. Thanks for your help!
For reference the complete error log:
04-18 14:04:52.323 11225-11225/com.wldtaster.tellmeastory E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.wldtaster.tellmeastory, PID: 11225
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wldtaster.tellmeastory/com.wldtaster.tellmeastory.LibraryActivity}: java.lang.IllegalStateException: RecyclerView has no LayoutManager
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager
at android.support.v7.widget.RecyclerView.generateLayoutParams(RecyclerView.java:3393)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at com.wldtaster.tellmeastory.BooksFragment.onCreateView(BooksFragment.java:23)
at android.app.Fragment.performCreateView(Fragment.java:2053)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.Activity.performStart(Activity.java:6005)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You must return the view ie. v in the onCreateView method of the Fragment inherited class.
I am using Drawer in a Fragment Floating Button whose value is getting null.
When clicking on Drawer item it is getting closed. Can anybody explain why?
Here is my code.
package com.example.mubeen.emei;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class Category_Item extends Fragment {
FloatingActionButton fab;
public Category_Item() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveCategory fragment = new SaveCategory();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment1_container, fragment);
fragmentTransaction.commit();
getActivity().setTitle(R.string.Save_Category);
return inflater.inflate(R.layout.fragment_category__item, container, false);
}
}
}
logcat
12-26 05:22:50.952 9530-9530/com.example.mubeen.emei W/PathParser: Points are too far apart 4.000000596046461
12-26 05:22:53.902 9530-9530/com.example.mubeen.emei D/AndroidRuntime: Shutting down VM
12-26 05:22:53.902 9530-9530/com.example.mubeen.emei E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mubeen.emei, PID: 9530
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at com.example.mubeen.emei.Category_Item.button(Category_Item.java:49)
at com.example.mubeen.emei.Category_Item.onCreateView(Category_Item.java:37)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:106)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:124)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
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:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
initialize your FloatingActionButton fab in your code ..
In your onCreateView method use this.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Enter your code here to do something after clicking Floating Actionbar
}
});
I think this may help you.
I'm admittedly quite new to Android development and Java in general, having some problems with something I've seen a ton of other people search for as well, but the other solutions don't seem to be doing it for me. I had this exact code working in another file, copied it to a different program (switching from NavigationDrawer to NavigationView) and now the Fragment gives me a NullPointerException when it tries to access the TextView.
As near as I can tell I've defined the view before trying to call findViewById. I'm absolutely certain that the problem is in the method show_life1_total() with the line
TextView life1_total = (TextView) view.findViewById(R.id.life1_total);
but I can't figure out what's wrong with that line because it worked perfectly in a different file. Any help would be most appreciated.
Alternately, if there's some other way I'm supposed to be handling buttons and views in fragments, please enlighten me. They were really easy in activities, but the NavigationView forces me to use fragments, and setting up onClickListeners for every single button I intend to use in a fragment looks like it's going to be a gigantic amount of what should be unnecessary work. Maybe I'm missing something obvious.
Here's my Fragment
package com.android4dev.navigationview;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Admin on 04-06-2015.
*/
public class GameFragment extends Fragment implements View.OnClickListener{
public static Integer nlife1Total=20;
public static Integer nlife2Total=20;
View view;
Button life1_minus;
Button life1_plus;
Button life2_minus;
Button life2_plus;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_life_counter,container,false);
life1_minus = (Button) view.findViewById(R.id.life1_minus);
life1_minus.setOnClickListener(this);
life1_plus = (Button) view.findViewById(R.id.life1_plus);
life1_plus.setOnClickListener(this);
life2_minus = (Button) view.findViewById(R.id.life2_minus);
life2_minus.setOnClickListener(this);
life2_plus = (Button) view.findViewById(R.id.life2_plus);
life2_plus.setOnClickListener(this);
show_life1_total();
show_life2_total();
return view;
}
public void startNewGame()
{
nlife1Total=20;
nlife2Total=20;
//show_life1_total();
//show_life2_total();
}
public void show_life1_total() {
TextView life1_total = (TextView) view.findViewById(R.id.life1_total);
String display_life1_total = String.valueOf(nlife1Total);
life1_total.setText(display_life1_total);
}
public void show_life2_total() {
TextView life2_total = (TextView) view.findViewById(R.id.life2_total);
String display_life2_total = String.valueOf(nlife2Total);
life2_total.setText(display_life2_total);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.life1_minus:
nlife1Total--;
show_life1_total();
break;
case R.id.life1_plus:
nlife1Total++;
show_life1_total();
break;
case R.id.life2_minus:
nlife2Total--;
show_life2_total();
break;
case R.id.life2_plus:
nlife2Total++;
show_life2_total();
break;
}
}
}
The relevant view from the xml file (this is in fragment_life_counter.xml)
<TextView
android:id="#+id/life1_total"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="140sp"
android:text="#string/life1_total"
android:fontFamily="sans-serif-thin"
android:textColor="#color/life_color"
android:background="#drawable/backdrop_ubr_grixis" />
Along with the logcat
08-27 22:17:46.103 18943-18943/com.android4dev.navigationview E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.android4dev.navigationview, PID: 18943
java.lang.NullPointerException
at com.android4dev.navigationview.GameFragment.show_life1_total(GameFragment.java:69)
at com.android4dev.navigationview.GameFragment.onCreateView(GameFragment.java:54)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1016)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1197)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5293)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
You have declared a View in the method that will act as a local varibale and it will be destroyed. Make it a global or you have already declared a global View varibale initailize it.
Follow this-
Instead of--
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_life_counter,container,false);
remove the View because you have already declared it on top of the class.
make it like this--
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_life_counter,container,false);
remember you are trying to access a view object in the show_life1_total() method which is not initialized.
I hope this would help you.