I am trying to call a fragment that acts as a side bar menu but when I try to run my app it says application has stopped. I have been trying all the ways I found on the internet. This is what I made so far.
activity_main.xml
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.user.sample.MainActivity">
<TextView
android:onClick="menuHeader"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="☰"
android:layout_alignParentTop="true"
android:background="#931d21"
android:gravity="center_vertical"
android:paddingLeft="10dp" />
<fragment
android:name="com.example.user.sample.MenuFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment_container" />
</LinearLayout
MainActivity.java
package com.example.user.sample;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
public class MainActivity extends FragmentActivity {
private MenuFragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void menuHeader(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment = new MenuFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
MenuFragment.java
package com.example.user.sample;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {#link OnListFragmentInteractionListener}
* interface.
*/
public class MenuFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public MenuFragment() {
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static MenuFragment newInstance(int columnCount) {
MenuFragment fragment = new MenuFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
// void onListFragmentInteraction(DummyItem item);
}
}
LOGCAT
02-10 10:11:19.236 3643-3643/com.example.user.sample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.sample, PID: 3643
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.sample/com.example.user.sample.MainActivity}: android.view.InflateException: Binary XML file line #23: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3190)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.view.InflateException: Binary XML file line #23: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:450)
at android.app.Activity.setContentView(Activity.java:2366)
at com.example.user.sample.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.RuntimeException: com.example.user.sample.MainActivity#197f8eef must implement OnListFragmentInteractionListener
at com.example.user.sample.MenuFragment.onAttach(MenuFragment.java:75)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1231)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1472)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1691)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3413)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:450)
at android.app.Activity.setContentView(Activity.java:2366)
at com.example.user.sample.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
The fragment will show when the ☰ is clicked. But the app crashes because of the existence of fragment inside the acitvity layout.
I already have a layout for the fragment and I didn't make any changes to it so I don't know if I need to post it here. Thanks
Your error is this
.RuntimeException: com.example.user.sample.MainActivity#197f8eef must implement OnListFragmentInteractionListener
So your activity needs to implement OnListFragmentInteractionListener.
So add
public class MainActivity extends FragmentActivity implements
OnListFragmentInteractionListener{
....
Related
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.
I am a complete beginner when it comes to Android and programming in general. have tried to find solutions everywhere, tried them all but never worked so I gave up and decided to post this question. Every time I press the button, the app crashes. I want the app to go to whatever fragment when I press a button.
Take a look at my codes in github and tell me what you think.
MainActivity.java
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
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.TextView;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
Fragment someFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void onClick(View v) {
final int id = v.getId();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
switch (id) {
case R.id.button1:
ft.replace(R.id.fragmenttab3, new FragmentTab3(), "fragment_screen");
ft.commit();
// your code for button1 here GOT TO FIND A WAY TO OUTPUT A MESSAGE WHEN CLICKED
break;
case R.id.button2:
ft.replace(R.id.fragmenttab2, new FragmentTab2(), "fragment_screen");
ft.commit();
// your code for button2 here
//DON'T FORGET TO ADD android:onClick="onClick" IN ACTIVITY_MAIN.XML BUTTON SEGMENT
break;
case R.id.button3:
ft.replace(R.id.fragmenttab1, new FragmentTab1(), "fragment_screen");
ft.commit();
// your code for button3 here
//DON'T FORGET TO ADD android:onClick="onClick" IN ACTIVITY_MAIN.XML BUTTON SEGMENT
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
// return PlaceholderFragment.newInstance(position + 1); I COMMENTED THIS ONE OUT
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
FragmentTab3 fragmenttab3 = new FragmentTab3();
return fragmenttab3;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
FragmentTab2.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Button;
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab2.xml
View view = inflater.inflate(R.layout.fragmenttab2, container, false);
return view;
}
}
fragmenttab2.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmenttab2"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Fragment2" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button2"
android:onClick="onClick"
android:layout_marginTop="13dp" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button3"
android:onClick="onClick"
android:layout_marginTop="69dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="56dp"
android:layout_marginStart="56dp"
android:layout_marginTop="51dp"
android:onClick="onClick"
android:text="#string/button1" />
</FrameLayout>
Error log
05-25 13:04:56.928 2858-2858/com.example.guest3.swipetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.guest3.swipetest, PID: 2858
java.lang.IllegalArgumentException: No view found for id 0x7f0d0089 (com.example.guest3.swipetest:id/fragmenttab1) for fragment FragmentTab1{1c4f0f6 #3 id=0x7f0d0089 fragment_screen}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1293)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
You are trying to place a fragment into the activity's R.id.fragmenttab1 container. But Activity has no such a view, as the error says.
No view found for id 0x7f0d0089 (com.example.guest3.swipetest:id/fragmenttab1)
I am writing a simple app to learn Java, specifically how to manage fragment transactions.
The app has one MainActivity and three fragments (FragmentDefault, added to the MainActivity by default; and Fragments one and two, which can be added on a button click in MainActivity).
My app can handle on fragment transaction, but crashes during the second, regardless of the order of the transactions.
The MainActivity.java file is as follows:
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
transaction.replace(R.id.fragment_container, frag1);
transaction.commit();
transaction.addToBackStack(null);
}
public void openFrag2(View view) {
transaction.replace(R.id.fragment_container, frag2);
transaction.commit();
transaction.addToBackStack(null);
}
}
with .XML file:
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
transaction.replace(R.id.fragment_container, frag1);
transaction.commit();
transaction.addToBackStack(null);
}
public void openFrag2(View view) {
transaction.replace(R.id.fragment_container, frag2);
transaction.commit();
transaction.addToBackStack(null);
}
}
My three fragment files are essentially identical with java files:
package com.example.connor.fragmenttestapp;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
}
and .XML files:
<FrameLayout 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="com.example.connor.fragmenttestapp.Fragment1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/frag1_text"
android:id="#+id/textView" />
</FrameLayout>
The logcat file for this error shows :
02-01 21:01:51.608 15413-15413/com.example.connor.fragmenttestapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.connor.fragmenttestapp, PID: 15413
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10896)
at android.view.View$PerformClick.run(View.java:22546)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10896)
at android.view.View$PerformClick.run(View.java:22546)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.IllegalStateException: commit already called
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:630)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:603)
at com.example.connor.fragmenttestapp.MainActivity.openFrag2(MainActivity.java:37)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5702)
at android.widget.TextView.performClick(TextView.java:10896)
at android.view.View$PerformClick.run(View.java:22546)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
What is causing this error and how can I fix the code to avoid it?
You need to begin a transaction each time instead of creating only one.
You can have a single FragmentManager, but must beginTransition every time.
package com.example.connor.fragmenttestapp;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentDefault fragDefault = new FragmentDefault();
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = = getSupportFragmentManager();
if (savedInstanceState == null) {
fm.beginTransaction()
.add(R.id.fragment_container, fragDefault)
.commit();
}
}
public void openFrag(View view) {
fm.beginTransition().replace(R.id.fragment_container, frag1)
.addToBackStack(null).commit();
}
public void openFrag2(View view) {
fm.beginTransition().replace(R.id.fragment_container, frag2);
.addToBackStack(null).commit();
}
}
You can use this two functions
public void openNoHistoryFragment(Fragment fragment) {
FragmentTransaction ft = getActivity().getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.container,
fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commitAllowingStateLoss();
}
public void openFragment(Fragment fragment) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
// transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
create this each time when your want to make transaction.
transaction = getSupportFragmentManager().beginTransaction();
I am new to android programming and I am trying to write a simple application that switches between two Fragments. I started a new project with a blank activity template that already included a Fragment. I think this could be where I am going wrong, but I am lost. Every time I launch and click the button the app crashes. It throws a must implement OnFragmentInteractionListener error from MyFragment2's onAttach method. If I comment that method out it add's the new Fragment on top of the old one. I have been through just about every tutorial I can find. I do not see where my code is going wrong. I'm sure it is something easy and I am going to feel pretty stupid when I finally figure it out. Any help would be appreciated. Thanks in advance.
My main activity:
package com.example.misanthropic.fragments;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
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.os.Build;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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 onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// matically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void buttonClicked(View v){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment2 myFragment = new Fragment2();
fragmentTransaction.replace(R.id.fragment_main, myFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
The MyFragment2 I would like to swap in:
package com.example.misanthropic.fragments;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Fragment2.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Fragment2#newInstance} factory method to
* create an instance of this fragment.
*
*/
public class Fragment2 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Fragment2.
*/
// TODO: Rename and change types and number of parameters
public static Fragment2 newInstance(String param1, String param2) {
Fragment2 fragment = new Fragment2();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Fragment2() {
// 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_fragment2, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
My main xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main"
tools:ignore="MergeRootFrame" />
My Initial Fragment 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Main$PlaceholderFragment"
android:id="#+id/fragment_main">
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="165dp"
android:onClick="buttonClicked" />
</RelativeLayout>
The replacement Fragment XML:
<FrameLayout 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="com.example.misanthropic.fragments.Fragment2">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
Figured it out. I was calling the wrong id in the replace method.
fragmentTransaction.replace(R.id.fragment_main, myFragment);
should have been:
fragmentTransaction.replace(R.id.container, myFragment);
below find all my code and xml. My problem is that the spinner (in code spinner1) is null for some reason I can't determine and I get no errors other than the app failing to run. Any help would be appreciated!
activity_main.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".MainActivity" />
MainActivity.java:
package com.example.passwordplayground;
import java.util.Locale;
import com.example.MyApplication.EncryptionSpinner;
import com.example.MyApplication.MyApplication;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
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.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Spinner spinner1 = (Spinner) findViewById(R.id.encryptionSpin);
if (spinner1 == null)
System.out.println("Spinner1 is null");
else
System.out.println("Funcion is null");
spinner1.setOnItemSelectedListener(new EncryptionSpinner());
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(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.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return ("Practicality").toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if (getArguments().getInt(ARG_SECTION_NUMBER)==1) {
rootView = inflater.inflate(R.layout.encryption,container, false);
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==2) {
rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText("I'm second!");
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==3) {
//dummyTextView.setText("I'm third");
}
else if (getArguments().getInt(ARG_SECTION_NUMBER)==4) {
//dummyTextView.setText("I'm fourth and last!");
}
return rootView;
}
}
}
encryption.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
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=".MainActivity$Encryption" >
<Spinner
android1:id="#+id/encryptionSpin"
android1:layout_width="fill_parent"
android1:layout_height="wrap_content"
android1:layout_alignParentTop="true"
android1:layout_centerHorizontal="true"
android1:layout_marginTop="14dp"
android1:background="#color/orange"
android1:entries="#array/cryptArray" />
</RelativeLayout>
EncryptionSpinner.java:
package com.example.MyApplication;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class EncryptionSpinner implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Toast toast = Toast.makeText(MyApplication.getAppContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG);
toast.show();
System.out.println(parent.getItemAtPosition(pos).toString());
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
Logcat Error:
04-09 01:16:28.637: I/System.out(1440): Spinner1 is null
04-09 01:16:28.657: D/AndroidRuntime(1440): Shutting down VM
04-09 01:16:28.657: W/dalvikvm(1440): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
04-09 01:16:28.692: E/AndroidRuntime(1440): FATAL EXCEPTION: main
04-09 01:16:28.692: E/AndroidRuntime(1440): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.passwordplayground/com.example.passwordplayground.MainActivity}: java.lang.NullPointerException
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.os.Handler.dispatchMessage(Handler.java:99)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.os.Looper.loop(Looper.java:137)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-09 01:16:28.692: E/AndroidRuntime(1440): at java.lang.reflect.Method.invokeNative(Native Method)
04-09 01:16:28.692: E/AndroidRuntime(1440): at java.lang.reflect.Method.invoke(Method.java:525)
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-09 01:16:28.692: E/AndroidRuntime(1440): at dalvik.system.NativeStart.main(Native Method)
04-09 01:16:28.692: E/AndroidRuntime(1440): Caused by: java.lang.NullPointerException
04-09 01:16:28.692: E/AndroidRuntime(1440): at com.example.passwordplayground.MainActivity.onCreate(MainActivity.java:65)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.Activity.performCreate(Activity.java:5133)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-09 01:16:28.692: E/AndroidRuntime(1440): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-09 01:16:28.692: E/AndroidRuntime(1440): ... 11 more
Layouts' Gui:
if you want to user spinner from activity_main then you have to put it in that file because right now its not their and it is in encryption.xml file.
make activity_main.xml like below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
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=".MainActivity$Encryption" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black"
tools:context=".MainActivity" />
<Spinner
android1:id="#+id/encryptionSpin"
android1:layout_width="fill_parent"
android1:layout_height="wrap_content"
android1:layout_alignParentTop="true"
android1:layout_centerHorizontal="true"
android1:layout_marginTop="14dp"
android1:background="#color/orange"
android1:entries="#array/cryptArray" />
</RelativeLayout>
You have inflated the layout activity_main in your activity and you are trying to access the Spinner which is not in your activity_main layout.
In that point you are getting error. As the Spinner does not resides in your activity_main layout.
So will have to initialize your Spinner in DummySectionFragment onCreateView method as below:
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
if (getArguments().getInt(ARG_SECTION_NUMBER)==1) {
rootView = inflater.inflate(R.layout.encryption,container, false);
Spinner spinner1 = (Spinner)rootView.findViewById(R.id.encryptionSpin);
}
you see there is null pointer exception.
means you have no control on the components you are using.
this could be caused due to two reason
1. two components have same ids.
2. wrong defined layout.
in your case you are using layout
R.layout.activity_main
while your layout name is
R.layout.encryption
change the name of layout and you are ready to go.
You putting ViewPager in activity_mail layout and Spinner in encryption.xml if u setting content view as any one of xml. so any one ll identify another one will not be identify. It will throw the null pointer exception.
R.layout.activity_main having ViewPager
R.layout.encryption having Spinner
if u set setcontentView(R.layout.activity_main) then findViewById(R.id.encryptionSpin); line will throw null pointer.
if u set setcontentView(R.layout.encryption) then mViewPager = (ViewPager) findViewById(R.id.pager); line will throw null pointer.