When I add a TextView to a LinearLayout, I'm generating NullPointerExceptions. I'm calling this...
public void loadPlayers() {
LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
TextView tv = new TextView(this);
for (int i = 0; i < Game.getPlayers().length; i++) {
tv.setText(String.valueOf(Game.getPlayers()[i]));
tv.setPadding(8, 8, 8, 8);
tv.setTextSize(20);
tv.setBackgroundColor(0xD0D0D0);
System.out.println("Got here!");
lv.addView(tv);
}
}
At the end of onCreate, and I'm getting "Got here!" printed on my console. The error is coming from
lv.addView(tv);
But I don't see why that is a problem. Is the layout not loaded yet? If so, how do I fix that? Below is the complete activity, xml, and logs.
MainActivity.java:
package com.example.lineupcreator;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
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.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/* My Methods */
/**
* Adds a player, gets input from button
* #return
*/
public void addPlayer(View view) {
EditText editText = (EditText) findViewById(R.id.edit_message);
String name = editText.getText().toString();
LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
TextView tv = new TextView(this);
tv.setText(String.valueOf(name));
tv.setPadding(8, 8, 8, 8);
tv.setTextSize(20);
tv.setBackgroundColor(0xD0D0D0);
lv.addView(tv);// not InformationActivity.tv just write tv
Game.newPlayer(name);
}
/**
* Loads all of the players
*/
public void loadPlayers() {
LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
TextView tv = new TextView(this);
for (int i = 0; i < Game.getPlayers().length; i++) {
tv.setText(String.valueOf(Game.getPlayers()[i]));
tv.setPadding(8, 8, 8, 8);
tv.setTextSize(20);
tv.setBackgroundColor(0xD0D0D0);
System.out.println("Got here!");
lv.addView(tv);
}
}
/* Prebuilt Methods */
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
/* My Code */
Game.init();
this.loadPlayers();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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.
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";
/**
* 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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
fragment_main.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="com.example.lineupcreator.MainActivity$PlaceholderFragment" >
<EditText android:id="#+id/edit_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/button"
android:hint="#string/player_name" />
<Button
android:id="#+id/button"
android:layout_width="64dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/edit_message"
android:layout_alignParentRight="true"
android:onClick="addPlayer"
android:text="#string/add" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/edit_message" >
<LinearLayout
android:id="#+id/player_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
android:orientation="vertical" />
</ScrollView>
</RelativeLayout>
Logs:
07-24 17:30:48.274: D/ActivityThread(22173): handleBindApplication:com.example.lineupcreator
07-24 17:30:48.274: D/ActivityThread(22173): setTargetHeapUtilization:0.75
07-24 17:30:48.274: D/ActivityThread(22173): setTargetHeapMinFree:2097152
07-24 17:30:48.548: I/System.out(22173): Got here!
07-24 17:30:48.548: D/AndroidRuntime(22173): Shutting down VM
07-24 17:30:48.548: W/dalvikvm(22173): threadid=1: thread exiting with uncaught exception (group=0x418f1ce0)
07-24 17:30:48.555: E/AndroidRuntime(22173): FATAL EXCEPTION: main
07-24 17:30:48.555: E/AndroidRuntime(22173): Process: com.example.lineupcreator, PID: 22173
07-24 17:30:48.555: E/AndroidRuntime(22173): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lineupcreator/com.example.lineupcreator.MainActivity}: java.lang.NullPointerException
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.app.ActivityThread.access$800(ActivityThread.java:145)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.os.Handler.dispatchMessage(Handler.java:102)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.os.Looper.loop(Looper.java:136)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.app.ActivityThread.main(ActivityThread.java:5144)
07-24 17:30:48.555: E/AndroidRuntime(22173): at java.lang.reflect.Method.invokeNative(Native Method)
07-24 17:30:48.555: E/AndroidRuntime(22173): at java.lang.reflect.Method.invoke(Method.java:515)
07-24 17:30:48.555: E/AndroidRuntime(22173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
07-24 17:30:48.555: E/AndroidRuntime(22173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
07-24 17:30:48.555: E/AndroidRuntime(22173): at dalvik.system.NativeStart.main(Native Method)
07-24 17:30:48.555: E/AndroidRuntime(22173): Caused by: java.lang.NullPointerException
07-24 17:30:48.555: E/AndroidRuntime(22173): at com.example.lineupcreator.MainActivity.loadPlayers(MainActivity.java:64)
07-24 17:30:48.555: E/AndroidRuntime(22173): at com.example.lineupcreator.MainActivity.onCreate(MainActivity.java:96)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.app.Activity.performCreate(Activity.java:5231)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-24 17:30:48.555: E/AndroidRuntime(22173): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
07-24 17:30:48.555: E/AndroidRuntime(22173): ... 11 more
07-24 17:35:48.735: I/Process(22173): Sending signal. PID: 22173 SIG: 9
EDIT:
It seemed to me that quaternion was on the right path, but his solution didn't work. I also tried to creating an array of TextViews, as seen below, but that also didn't work.
public void loadPlayers() {
LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
TextView[] tv = new TextView[Game.getPlayers().length];
for (int i = 0; i < Game.getPlayers().length; i++) {
tv[i] = new TextView(this);
tv[i].setText(String.valueOf(Game.getPlayers()[i]));
tv[i].setPadding(8, 8, 8, 8);
tv[i].setTextSize(20);
tv[i].setBackgroundColor(0xD0D0D0);
System.out.println("Got here!");
lv.addView(tv[i]);
}
}
Update:
I tried calling loadPlayers from addPlayer and not onCreate, and it works perfectly. The only problem is created when loadPlayers is called from onCreate
Caused by: java.lang.NullPointerException
at com.example.lineupcreator.MainActivity.loadPlayers(MainActivity.java:64)
The reason why you're getting NullPointerException is because you're trying to get a LinearLayout which is inflated in Fragment, from the Activity, specifically these lines:
public void loadPlayers() {
LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
// R.id.player_list is not inside activity_main.xml
// lv is null
...
lv.addView(tv[i]); // NullPointerException
}
}
One way to solve this is to move all the logic inside the Fragment.
Add onActivityCreated(Bundle savedInstanceState) inside the PlaceholderFragment and move both lines from onCreate() to there. This is to ensure that the code will be called after the activity is already set-up.
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/* My Code */
Game.init();
this.loadPlayers();
}
Then move loadPlayers() inside the PlaceholderFragment. However, there is no findViewById() inside a Fragment. Instead, you have to initialize the views inside onCreateView(). Don't forget to declare the variables inside the Fragment.
LinearLayout lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
lv = (LinearLayout) rootView.findViewById(R.id.player_list);
return rootView;
}
Lastly, Fragment use Context from its Activity. While you can use this in Activity to refer to its Context, in Fragment you cannot. Instead, use getActivity().
public void loadPlayers() {
// LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
TextView tv;
for (int i = 0; i < Game.getPlayers().length; i++) {
tv = new TextView(getActivity());
tv.setText(String.valueOf(Game.getPlayers()[i].getName()));
tv.setPadding(8, 8, 8, 8);
tv.setTextSize(20);
tv.setBackgroundColor(0xD0D0D0);
lv.addView(tv);
}
}
Ok, the Error is that you are trying inflate a layout component from the main activity, but your are inflating a Fragment, so, your main layout is not showing in your screen, is the fragment layout that is the top. You need move
<LinearLayout
android:id="#+id/player_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
android:orientation="vertical" />
to Fragment Layout.
If this donsn't work just tell me.
I don't think you can add the same view to a parent multiple times. You will need to move you instantiation of the new TextView into the for loop.
Your loadPlayers function should look like this:
public void loadPlayers() {
LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
for (int i = 0; i < Game.getPlayers().length; i++) {
TextView tv = new TextView(this);
tv.setText(String.valueOf(Game.getPlayers()[i]));
tv.setPadding(8, 8, 8, 8);
tv.setTextSize(20);
tv.setBackgroundColor(0xD0D0D0);
System.out.println("Got here!");
lv.addView(tv);
}
}
Hope this helps, if not you may have a bigger issue at hand =(
Related
Just wanted to share an issue that I have with a project that I am doing for a client.
Whenever I enter to my IntroActivity and press the button to take me to MenuActivity, it crashes.
Here is the error log:
02-16 18:49:49.393 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ No view found for id 0x7f090047 (com.wlodsgn.bunbunup:id/linear) for fragment FmMenu{b1e537f0 #0 id=0x7f090047}
02-16 18:49:49.393 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ Activity state:
02-16 18:49:49.423 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ Local FragmentActivity b1e1d1b8 State:
02-16 18:49:49.423 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ mCreated=falsemResumed=false mStopped=false mReallyStopped=false
02-16 18:49:49.423 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ mLoadersStarted=false
02-16 18:49:49.443 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ FragmentManager misc state:
02-16 18:49:49.443 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ mActivity=com.wlodsgn.bunbunup.MenuActivity#b1e1d1b8
02-16 18:49:49.443 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ mContainer=android.support.v4.app.FragmentActivity$2#b1e1ed08
02-16 18:49:49.453 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ mCurState=1 mStateSaved=false mDestroyed=false
02-16 18:49:49.453 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ View Hierarchy:
02-16 18:49:49.453 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ com.android.internal.policy.impl.PhoneWindow$DecorView{b1e23d08 V.E..... ... 0,0-0,0}
02-16 18:49:49.473 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.widget.LinearLayout{b1e24280 V.E..... ... 0,0-0,0}
02-16 18:49:49.473 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.view.ViewStub{b1e24da8 G.E..... ... 0,0-0,0 #102030e}
02-16 18:49:49.473 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.widget.FrameLayout{b1e25038 V.E..... ... 0,0-0,0}
02-16 18:49:49.473 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.support.v7.internal.widget.ActionBarOverlayLayout{b1e2db28 V.E..... ... 0,0-0,0 #7f09002f app:id/decor_content_parent}
02-16 18:49:49.483 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.support.v7.internal.widget.NativeActionModeAwareLayout{b1e2f758 V.E..... ... 0,0-0,0 #1020002 android:id/content}
02-16 18:49:49.483 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ [ 02-16 18:49:49.513 1208: 1208 E/FragmentManager ]
android.support.v4.widget.DrawerLayout{b1e2c058 VFE..... ... 0,0-0,0 #7f090042 app:id/drawer_layout}
02-16 18:49:49.513 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.widget.LinearLayout{b1e1fa90 V.E..... ... 0,0-0,0}
02-16 18:49:49.523 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.support.v4.view.ViewPager{b1e29568 VFED.... ... 0,0-0,0 #7f090043 app:id/pager}
02-16 18:49:49.523 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.widget.ListView{b1e44148 VFED.VC. ... 0,0-0,0 #7f090044 app:id/listView1}
02-16 18:49:49.523 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.widget.ListView{b1dd80b8 VFED.VC. ... 0,0-0,0 #7f090045 app:id/list_slidermenu}
02-16 18:49:49.523 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.support.v7.internal.widget.ActionBarContainer{b1e2fcd0 V.ED.... ... 0,0-0,0 #7f090030 app:id/action_bar_container}
02-16 18:49:49.533 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.support.v7.widget.Toolbar{b1e30898 V.E..... ... 0,0-0,0 #7f090031 app:id/action_bar}
02-16 18:49:49.533 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.widget.ImageButton{b1e39da8 VFED..C. ... 0,0-0,0}
02-16 18:49:49.533 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.widget.TextView{b1e28a60 V.ED.... ... 0,0-0,0}
02-16 18:49:49.533 1208-1208/com.wlodsgn.bunbunup E/FragmentManager﹕ android.support.v7.internal.widget.ActionBarContextView{b1e43a50 G.E..... ... 0,0-0,0 #7f090032 app:id/action_context_bar}
02-16 18:49:49.543 1208-1208/com.wlodsgn.bunbunup D/AndroidRuntime﹕ Shutting down VM
02-16 18:49:49.543 1208-1208/com.wlodsgn.bunbunup W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a87ba8)
02-16 18:49:49.573 1208-1208/com.wlodsgn.bunbunup E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.wlodsgn.bunbunup, PID: 1208
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wlodsgn.bunbunup/com.wlodsgn.bunbunup.MenuActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f090047 (com.wlodsgn.bunbunup:id/linear) for fragment FmMenu{b1e537f0 #0 id=0x7f090047}
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f090047 (com.wlodsgn.bunbunup:id/linear) for fragment FmMenu{b1e537f0 #0 id=0x7f090047}
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:882)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.Activity.performStart(Activity.java:5240)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Here is my MenuActivity.java where the error is located (Nearly at the end starts with if (fragment != null) { :
import java.util.ArrayList;
import java.util.List;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.MenuItemCompat.OnActionExpandListener;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
/**
* Created by WiLo on 2/13/2015.
*/
public class MenuActivity extends ActionBarActivity implements OnQueryTextListener, OnActionExpandListener{
/*private TextView texto;*/
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
String[] categoria = {
"Jeans"
};
int[] imagenes = {
R.drawable.veroxjeans1,
R.drawable.veroxjeans2,
R.drawable.veroxjeans3,
R.drawable.veroxjeans4,
R.drawable.veroxjeans5,
R.drawable.veroxjeans6,
R.drawable.veroxjeans7
};
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
/*texto = (TextView) findViewById(R.id.texto);*/
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// agregar un nuevo item al menu deslizante
// Menu
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Contacto
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Catologo
//navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1), true, "Estrenos"));
// old Contacto (Pedidos)
//navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
//lista
ListView lista = (ListView) findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, categoria );
lista.setAdapter(adapter);
//galeria de imagenes
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[0]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[1]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[2]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[3]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[4]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[5]));
mSectionsPagerAdapter.addfragments(PlaceholderFragment.newInstance(imagenes[6]));
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
Toast.makeText(getApplicationContext(), "Abriendo Busqueda", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
Toast.makeText(getApplicationContext(), "Cerrando Busqueda", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextSubmit(String s) {
/*texto.setText("Buscando...\n\n" + s);*/
return false;
}
#Override
public boolean onQueryTextChange(String s) {
/*texto.setText(" \n\n" + s);*/
return false;
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu3_buscar);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(searchItem, this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FmMenu();
break;
case 1:
fragment = new FmContacto();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.linear, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("BunBunUp", "MenuActivity - Error cuando se creo el fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggle
mDrawerToggle.onConfigurationChanged(newConfig);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
List<android.support.v4.app.Fragment> fragmentos;
public SectionsPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
fragmentos = new ArrayList<android.support.v4.app.Fragment>();
}
public void addfragments(android.support.v4.app.Fragment xfragment){
fragmentos.add(xfragment);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return fragmentos.get(position);
}
#Override
public int getCount() {
return fragmentos.size();
}
}
public static class PlaceholderFragment extends android.support.v4.app.Fragment {
private static final String ARG_IMAGE = "imagen";
private int imagen;
public static PlaceholderFragment newInstance(int imagen) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_IMAGE, imagen);
fragment.setArguments(args);
fragment.setRetainInstance(true);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null) {
imagen = getArguments().getInt(ARG_IMAGE);
}
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
ImageView imagenView = (ImageView) rootView.findViewById(R.id.imageView1);
imagenView.setImageResource(imagen);
return rootView;
}
}
}
Here are the rest (If needed) of the files that are linked to MenuActivity :
FmMenu.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by WiLo on 2/13/2015.
*/
public class FmMenu extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.lay_menufragment, container, false);
return rootView;
}
}
activity_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0a393d">
<!-- Linearlayout to display Fragments -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="265dp"
tools:context=".MenuActivity" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView1"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
fragment_menu.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"
tools:context=".MenuActivity$PlaceholderFragment"
android:id="#+id/linear">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageView1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
lay_menufragment.xml
<?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">
</LinearLayout>
New error log:
02-17 09:41:20.480 917-917/com.wlodsgn.bunbunup W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1ad9ba8)
02-17 09:41:20.560 917-917/com.wlodsgn.bunbunup E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.wlodsgn.bunbunup, PID: 917
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:422)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
at android.content.res.Resources.loadDrawable(Resources.java:2110)
at android.content.res.Resources.getDrawable(Resources.java:700)
at android.widget.ImageView.resolveUri(ImageView.java:638)
at android.widget.ImageView.setImageResource(ImageView.java:367)
at com.wlodsgn.bunbunup.MenuActivity$PlaceholderFragment.onCreateView(MenuActivity.java:345)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:851)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
Need more info, let me know
Any help would be appreciated
I think I have found something.
fragmentManager.beginTransaction()
.replace(R.id.linear, fragment).commit();
As you see you try to replace the layout R.id.linear with your fragment. But the R.id.linear is the RelativeLayout you use in your fragment_menu.xml. You should replace the layout in your activity_menu.xml with the current fragment. So I would suggest:
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
And in your activity_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0a393d">
<!-- Linearlayout to display Fragments -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/container">
EDIT:
For the new error: There is a problem with your memory. This often happens when ImageViews are filled by big ressources. So there is only one position where you use an ImageView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
ImageView imagenView = (ImageView) rootView.findViewById(R.id.imageView1);
imagenView.setImageResource(imagen);
return rootView;
}
As you see, your imagenView is filled by the resource imagen
imagenView.setImageResource(imagen);
Probably you get the OutOfMemoryError there. As a solution, try this:
try {
imagenView.setImageResource(imagen);
} catch (OutOfMemoryError e) {
//fill your ImageView with something smaller .. maybe a smaller resolution
Log.e("PlaceholderFragment", "Error: OutOfMemoryError")
}
Check your imagen too, whether there is a high resolution needed.
I'm having a problem building my first App. I'm using Navigation drawer to switch between fragments. But when i choose OrderFragment from Navigation drawer, app crashes.
OrderFragment has only one button showing a toast when clicked, but the app crashes before the OrderFragment loads.
The code is:
MainActivity.java
package com.example.testcocogeek;
import android.app.Activity;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String[] mListOptions;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mListOptions = getResources().getStringArray(R.array.list_options);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set adapter for the list view
mDrawerList.setAdapter (new ArrayAdapter<String> (this,
R.layout.drawer_list_item, mListOptions));
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// Set the list click listener
mDrawerList.setOnItemClickListener (new DrawerItemClickListener());
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, "Cocogeek");
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
// This method selects correct fragment.
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
Bundle args = new Bundle();
switch (position) {
case 0:
fragment = new CocogeekFragment();
break;
case 1:
fragment = new OrderFragment();
break;
case 2:
fragment = new LocatorFragment();
break;
case 3:
fragment = new ContactFragment();
break;
default:
break;
}
fragment.setArguments(args);
android.app.FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mListOptions[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
OrderFragment.java
package com.example.testcocogeek;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class OrderFragment extends Fragment implements OnClickListener {
public OrderFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView = (View) inflater.inflate(R.layout.order_fragment, container, false);
// Initialize UI views.
final Button send = (Button) getActivity().findViewById(R.id.send);
//Initialize OnClick listener.
send.setOnClickListener(this);
return mView;
}
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked" ,Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF5EE"
>
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#858585"/>
</android.support.v4.widget.DrawerLayout>
order_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/send"
/>
</LinearLayout>
logCat:
07-08 12:28:09.332: D/dalvikvm(30471): GC_FOR_ALLOC freed 165K, 2% free 16940K/17136K, paused 15ms, total 15ms
07-08 12:28:09.362: I/dalvikvm-heap(30471): Grow heap (frag case) to 35.315MB for 19655120-byte allocation
07-08 12:28:09.372: D/dalvikvm(30471): GC_FOR_ALLOC freed 2K, 1% free 36132K/36332K, paused 11ms, total 11ms
07-08 12:28:09.522: I/Adreno-EGL(30471): <qeglDrvAPI_eglInitialize:320>: EGL 1.4 QUALCOMM Build: I0404c4692afb8623f95c43aeb6d5e13ed4b30ddbDate: 11/06/13
07-08 12:28:09.542: D/OpenGLRenderer(30471): Enabling debug mode 0
07-08 12:28:11.852: D/AndroidRuntime(30471): Shutting down VM
07-08 12:28:11.852: W/dalvikvm(30471): threadid=1: thread exiting with uncaught exception (group=0x41625ba8)
07-08 12:28:11.862: E/AndroidRuntime(30471): FATAL EXCEPTION: main
07-08 12:28:11.862: E/AndroidRuntime(30471): Process: com.example.testcocogeek, PID: 30471
07-08 12:28:11.862: E/AndroidRuntime(30471): java.lang.NullPointerException
07-08 12:28:11.862: E/AndroidRuntime(30471): at com.example.testcocogeek.OrderFragment.onCreateView(OrderFragment.java:29)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.app.Fragment.performCreateView(Fragment.java:1700)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.app.BackStackRecord.run(BackStackRecord.java:684)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.os.Handler.handleCallback(Handler.java:733)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.os.Handler.dispatchMessage(Handler.java:95)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.os.Looper.loop(Looper.java:136)
07-08 12:28:11.862: E/AndroidRuntime(30471): at android.app.ActivityThread.main(ActivityThread.java:5001)
07-08 12:28:11.862: E/AndroidRuntime(30471): at java.lang.reflect.Method.invokeNative(Native Method)
07-08 12:28:11.862: E/AndroidRuntime(30471): at java.lang.reflect.Method.invoke(Method.java:515)
07-08 12:28:11.862: E/AndroidRuntime(30471): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
07-08 12:28:11.862: E/AndroidRuntime(30471): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-08 12:28:11.862: E/AndroidRuntime(30471): at dalvik.system.NativeStart.main(Native Method)
07-08 12:28:13.332: I/Process(30471): Sending signal. PID: 30471 SIG: 9
At first sight you should replace:
final Button send = (Button) getActivity().findViewById(R.id.send);
with:
final Button send = (Button) mView.findViewById(R.id.send);
R.id.send id is contained in the Fragment view mView.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So I added a <WebView> to the standard navigation drawer template and added some code to the java file. However, now the app keeps on crashing. The error it throws in the console is Error inflating class fragment
It does compile though. So how can I fix this? Should I add the <WebView> somewhere else?
activity_login.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".login">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="test.vwebviewdrawer.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
main.java
package test.webviewdrawer;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.View.OnClickListener;
//...
public class login extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
WebView myWebView = (WebView) findViewById(R.id.main_webview);
String pageUrl = "http://www.google.com";
myWebView.loadUrl(pageUrl);
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.login, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((login) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
UPDATE:
I added the error message as requested in the comment section.
06-21 19:42:52.109 17625-17625/test.webviewdrawer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: test.webviewdrawer, PID: 17625
java.lang.RuntimeException: Unable to start activity ComponentInfo{test.webviewdrawer/test.webviewdrawer.login}: android.view.InflateException: Binary XML file line #28: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #28: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:375)
at android.app.Activity.setContentView(Activity.java:1997)
at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:216)
at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:110)
at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76)
at test.webviewdrawer.login.onCreate(login.java:46)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
There's a typo in your XML layout, at this line:
android:name="test.vwebviewdrawer.NavigationDrawerFragment"
It should be:
android:name="test.webviewdrawer.NavigationDrawerFragment"
instead :-)
I have just started writing my first piece of code in an android app, however when I run it with the following section uncommented it crashes (anything else I tell you would be a useless guess):
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
With the following error log:
04-07 17:45:30.897: E/AndroidRuntime(15210): FATAL EXCEPTION: main
04-07 17:45:30.897: E/AndroidRuntime(15210): Process: com.ollieapps.helloworld, PID: 15210
04-07 17:45:30.897: E/AndroidRuntime(15210): java.lang.IllegalStateException: Could not execute method of the activity
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3823)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View.performClick(View.java:4438)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$PerformClick.run(View.java:18422)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.handleCallback(Handler.java:733)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.dispatchMessage(Handler.java:95)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Looper.loop(Looper.java:136)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.reflect.InvocationTargetException
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3818)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 9 more
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.ollieapps.helloworld.MainActivity.onButton1Click(MainActivity.java:59)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 11 more
I'm sorry if I have included to much or too little, this is my first question, also I have already searched for 3 hours.
Full Code:
package com.ollieapps.helloworld;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView; CheckBox pepBox, cheeseBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
if (savedInstanceState == null) {
getSupportFragmentManager().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
// automatically 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 onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
/**
* 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;
}
}
}
xml:
fragment:
<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: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="com.ollieapps.helloworld.MainActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pepperoni" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ExtraCheese" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButton1Click"
android:text="Show" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Plain" />
</LinearLayout>
</RelativeLayout>
Main:
<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="com.ollieapps.helloworld.MainActivity"
tools:ignore="MergeRootFrame" />
It seems you built your views inside fragment_main.xml and not activity_main.xml.
When you first create a new android project, you have these files which are automatically created and opened:
Then, when you begin, you add views (e.g: a TextView) inside fragment_main.xml file. Finally, you tried to do a basically event with this view inside your Activity, something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Using layout activity_main.xml
// You try to set a simple text on the view (TextView) previously added
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("Simple Text"); // And you get an error here!
/*
* You do an fragment transaction to add PlaceholderFragment Fragment
* on screen - this below snippnet is automatically created.
*/
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
You cannot run your app or sometimes you have only a white screen, because the views that you tried to call/display are into the wrong layout..
Solution: Move all your stuff inside onCreateView method into the Fragment class.
As DoctororDrive said in his comment
Call views and do something in the related fragment and not the parent activity.
For example, in your case, these following lines:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
might be inside your fragment because you created it in fragment_main.xml layout. Then:
// start fragment
public static class PlaceholderFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Use the layout which is displayed it's fragment_main.xml
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Find your views here!
// Don't forget to findViewById attached to the inflated view "rootView.findView..."
pepBox = (CheckBox) rootView.findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) rootView.findViewById(R.id.checkBox2);
textView = (TextView) rootView.findViewById(R.id.textView1);
/*
* Do something here: click listener, set a text, check a box..
*/
return rootView;
}
/*
* Perform other methods still inside the fragment
*/
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
}
// end fragment
if (pepBox.isChecked()) {
This line of code is failing with a NullPointerException because pepBox was declared but it's not being initialized as it should (and is therefore null at this point in the code).
Here is its declaration line:
TextView textView; CheckBox pepBox, cheeseBox;
And here is its initialization:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
The problem is that (a) this line is not be called, or (b) findViewById(R.id.checkBox1) is returning null.
If findViewByID is returning null then you probably want to refer to this question, which addresses exactly this issue. Its "related questions", down the right-hand side, should also be helpful.
I am trying to implement pageviewer in my app using this tutorial. But my app force closes. It shows android.view.InflateException: Binary XML file line #2: Error inflating class com.example.viewpager.ScrollView. Where I am going wrong? I am a beginner in android so please guide me. I thought I might have imported wrong libs as my app is supporting API 10. So I searched other answers but of no use. Here is my code:
MainActvity.java
package com.example.viewpager;
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.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new ScreenSlidePageFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
ScreenSlidePagerFragment.java
package com.example.viewpager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
actvity_main.xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragment_slide_screen_page.xml
<?xml version="1.0" encoding="utf-8"?>
<com.example.viewpager.ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:textColor="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Page 1" />
</com.example.viewpager.ScrollView>
Log cat:
android.view.InflateException: Binary XML file line #2: Error inflating class com.example.viewpager.ScrollView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581)
at android.view.LayoutInflater.inflate(LayoutInflater.java:386)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at com.example.viewpager.ScreenSlidePageFragment.onCreateView(ScreenSlidePageFragment.java:14)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
at android.view.View.measure(View.java:8313)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
at android.view.View.measure(View.java:8313)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
at android.view.View.measure(View.java:8313)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
at android.view.View.measure(View.java:8313)
at android.view.ViewRoot.performTraversals(ViewRoot.java:845)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.example.viewpager.ScrollView in loader dalvik.system.PathClassLoader[/data/app/com.example.viewpager-2.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at android.view.LayoutInflater.createView(LayoutInflater.java:471)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
... 33 more
change adapter to:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
int layouts[];
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
layouts=new int[]{R.layout.fragment_slide_screen_page1,R.layout.fragment_slide_screen_page2,R.layout.fragment_slide_screen_page3,R.layout.fragment_slide_screen_page4,R.layout.fragment_slide_screen_page5};
}
#Override
public Fragment getItem(int position) {
ScreenSlidePageFragment fragment=new ScreenSlidePageFragment();
fragment.setContent(layouts[position]);
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
and in fragment:
public class ScreenSlidePageFragment extends Fragment {
int layout;
public void setContent(int layout){
this.layout=layout;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(layout, container, false);
return rootView;
}
}
Although not sure what change you want in each fragment but the above will require you to create 5 layout xmls that you can set every time you create a new Fragment.
Even I encountered crash.
This is because I was calling mAdapter.notifyDataSetChanged(); inside
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
Later I shifted the method to
#Override
public void onPageSelected(int arg0) {
mAdapter.notifyDataSetChanged();
}
So that did the trick