Hi when I launch my app it crashes instantly reading the logcat I can see that it is cause by the sendButton in my mainActivity, from reading around I people say it has to do with the button not being initiated but as far I can see it is, I have it declared in my fragment_main.xml okay and without the button code in MainActivity.java my code loads the app grand. Any help would really be appreciate.
Logcat
06-20 08:50:18.323: E/AndroidRuntime(30036): FATAL EXCEPTION: main
06-20 08:50:18.323: E/AndroidRuntime(30036): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.draco.dragonmessage/com.draco.dragonmessage.MainActivity}: java.lang.NullPointerException
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2483)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.access$600(ActivityThread.java:178)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.os.Handler.dispatchMessage(Handler.java:107)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.os.Looper.loop(Looper.java:194)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.main(ActivityThread.java:5560)
06-20 08:50:18.323: E/AndroidRuntime(30036): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 08:50:18.323: E/AndroidRuntime(30036): at java.lang.reflect.Method.invoke(Method.java:525)
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
06-20 08:50:18.323: E/AndroidRuntime(30036): at dalvik.system.NativeStart.main(Native Method)
06-20 08:50:18.323: E/AndroidRuntime(30036): Caused by: java.lang.NullPointerException
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.draco.dragonmessage.MainActivity.onCreate(MainActivity.java:48)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.Activity.performCreate(Activity.java:5135)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1151)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
06-20 08:50:18.323: E/AndroidRuntime(30036): ... 11 more
MainActivity.java
package com.draco.dragonmessage;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* 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;
String sendMessageString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
final Button sendMessage = (Button) findViewById(R.id.messageButton);
System.out.println(sendMessage.toString());
sendMessage.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
final TextView receivedMessage = (TextView) findViewById(R.id.textReceived);
final EditText messageToSend = (EditText) findViewById(R.id.editTextSend);
sendMessageString = messageToSend.toString();
receivedMessage.setText(sendMessageString);
}
});
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
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 = getActionBar();
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.
int id = item.getItemId();
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";
/**
* 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);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
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"
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.draco.dragonmessage.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editTextSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/section_label"
android:layout_alignParentBottom="true"
android:ems="10"
android:hint="Enter message to send..." />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/section_label"
android:layout_alignTop="#+id/textReceived"
android:text="Keith"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textReceived"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/section_label"
android:layout_alignRight="#+id/editTextSend"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/messageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editTextSend"
android:layout_alignParentRight="true"
android:layout_marginRight="31dp"
android:text="Button" />
</RelativeLayout>
activity_main.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="com.draco.dragonmessage.MainActivity" >
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="#+id/navigation_drawer"
android:name="com.draco.dragonmessage.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout>
Thanks again for any help.
The Button with ID messageButton is in fragment_main.xml. With findByViewById() you are accessing to activity_main.xml (setContentView(R.layout.activity_main);.
You can add an attribute Button to the class and link the element in the onCreateView method of PlaceholderFragment. Then you can access to this button from anywhere in the activity.
Just Move the following lines to Oncreate() and change R.layout to your fragment layout. You are using a wrong layout
final TextView receivedMessage = (TextView) findViewById(R.id.textReceived);
final EditText messageToSend = (EditText) findViewById(R.id.editTextSend);
below this one
final Button sendMessage = (Button) findViewById(R.id.messageButton);
Related
So I'm making an app where the bottom navigation lets you click through different web pages and I've come across a problem. I can't seem to get it where the webview will function correctly inside the fragment class.
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_container"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="56dp">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_clever.xml
<?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">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/clever_web"></WebView>
</RelativeLayout>
cleverfragment.java (the one im currently working with)
package com.port.schoool;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
webview.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("google.com");
return inflater.inflate(R.layout.fragment_clever, null);
}
}
mainactivity.java
package com.port.schoool;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(this);
loadFragment(new ReadWorksFragment());
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fragment = new ReadWorksFragment();
break;
case R.id.navigation_dashboard:
fragment = new CleverFragment();
break;
case R.id.navigation_notifications:
fragment = new PortalFragment();
break;
}
return loadFragment(fragment);
}
}
Here is my logcat logs for the crashes:
2019-08-04 18:05:25.164 7425-7425/com.port.schoool E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.port.schoool, PID: 7425
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.webkit.WebView.findViewById(int)' on a null object reference
at com.port.schoool.CleverFragment.onCreateView(CleverFragment.java:20)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6960)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Replace your fragment with:
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_clever, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
webview = view.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("https://google.com");
}
}
Of note:
Your original code would not compile, as there is no findViewById() on Fragment
The right version of inflate() to use in onCreateView() is the one that takes the container and false as the second and third parameters
You configure your fragment's views in onViewCreated()
You need to call findViewById() on the inflated layout (view in onViewCreated()) and assign that to webview
You need to use a valid URL with loadUrl()
This sort of stuff should be covered in your book on Android app development.
I want my app to show this screen to a user in large-land mode so he can give input, press the button, and see output all on the same screen.
For any other mode, I want the two panes shown above to be shown one at a time, in this order, where the second screen appears when the user presses the button, after which pressing the back button returns to the "input" screen on the left:
What I have done works up to the point of showing correct output on the second screen but then I get "No view found for id" container and then an exception occurs
Here's xml for first screen above:
device(large-land).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:id ="#+id/linear_layout_container_in_large_land_device_xml"
android:weightSum ="3"
>
<fragment
android:name="com.dslomer64.fragments.InputFragment" android:layout_weight ="2" android:layout_width="wrap_content" android:layout_height="match_parent"
android:id ="#+id/inputFragment"
tools:layout ="#layout/input_fragment"
/>
<fragment
android:name="com.dslomer64.fragments.OutputFragment" android:layout_weight ="1" android:layout_width="wrap_content" android:layout_height="match_parent"
android:id ="#+id/outputFragment"
tools:layout ="#layout/output_fragment"
/>
</LinearLayout>
device.xml (for non-large-land)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/container"
/>
input_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id ="#+id/tvInMainFragment" android:layout_width ="wrap_content" android:layout_height="wrap_content"
android:text="How many?"
/>
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="#+id/etxIn_input_fragment"
android:text="3"
/>
<Button
android:id="#+id/btnIn_input_fragment" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Press to get output in OtherFragment"
/>
</LinearLayout>
output_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >
<TextView
android:id="#+id/txvIn_output_fragment" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Output will go here in OutputFragment"
/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device);
if (findViewById(R.id.container) != null) {
InputFragment inputFragment;
inputFragment = new InputFragment();
getFragmentManager().beginTransaction()
.add(R.id.container, inputFragment)
.commit();
}
}
}
InputFragment.java
public class InputFragment extends Fragment
{
public View onCreateView(LayoutInflater inflater,
ViewGroup viewGroup,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.input_fragment, viewGroup, false);
Button btn;
btn = (Button)view.findViewById(R.id.btnIn_input_fragment);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OutputFragment outputFragment;
outputFragment = new OutputFragment();
if (getFragmentManager().findFragmentById(R.id.inputFragment) == null) {
getActivity().setContentView(R.layout.device);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, outputFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
getActivity().setContentView(R.layout.input_fragment);
EditText etx = (EditText) getActivity().findViewById(R.id.etxIn_input_fragment);
fillFragmentOtherWithInfo(etx.getText().toString());
}
});
return view;
}
public void fillFragmentOtherWithInfo(String ks)
{
getActivity().setContentView(R.layout.output_fragment);
TextView tvOther = (TextView)getActivity().findViewById(R.id.txvIn_output_fragment);
String s = "";
for(int i = 0; i < parseInt(ks); i++)
s += ("\n" + (char)(i+65));
tvOther.setText(s);
}
}
What happens is all good up to the point of showing the output on the second screen. It does show correctly, but then I immediately get an exception that is preceded with this message, and I have no idea what to do about it:
03-02 15:59:52.987 7901-7901/com.dslomer64.fragments E/FragmentManager: No view found for id 0x7f070000 (com.dslomer64.fragments:id/container) for fragment OutputFragment{41ecc848 #1 id=0x7f070000}
container is the id of the FrameLayout in device.xml (non-large-land) that is referenced in the .add part of the fragment transaction in MainActivity onCreate. I get the same error if I use .replace instead of .add.
Here is the entire text of the error:
No view found for id 0x7f070000 (com.dslomer64.fragments:id/container) for fragment OutputFragment{41ebf0f0 #1 id=0x7f070000}
Activity state:
Local Activity 41e4d8a8 State:
mResumed=true mStopped=false mFinished=false
mLoadersStarted=true
mChangingConfigurations=false
mCurrentConfig={1.15 311mcc480mnc en_US ldltr sw600dp w600dp h888dp 213dpi lrg port finger -keyb/v/h -nav/h skin=/system/framework/framework-res.apk s.16}
Active Fragments in 41e4d9a0:
#0: InputFragment{41e6d1d8 #0 id=0x7f070000}
mFragmentId=#7f070000 mContainerId=#7f070000 mTag=null
mState=1 mIndex=0 mWho=android:fragment:0 mBackStackNesting=2
mAdded=false mRemoving=true mResumed=false mFromLayout=false mInLayout=false
mHidden=false mDetached=false mMenuVisible=true mHasMenu=false
mRetainInstance=false mRetaining=false mUserVisibleHint=true
mFragmentManager=FragmentManager{41e4d9a0 in MainActivity{41e4d8a8}}
mActivity=com.dslomer64.fragments.MainActivity#41e4d8a8
mSavedViewState=
{2131165188=android.view.AbsSavedState$1#41acfcc0, 2131165189=TextView.SavedState{41ec9d10 start=0 end=0 text=3}, 2131165190=android.view.AbsSavedState$1#41acfcc0}
#1: OutputFragment{41ebf0f0 #1 id=0x7f070000}
mFragmentId=#7f070000 mContainerId=#7f070000 mTag=null
mState=0 mIndex=1 mWho=android:fragment:1 mBackStackNesting=1
mAdded=true mRemoving=false mResumed=false mFromLayout=false mInLayout=false
mHidden=false mDetached=false mMenuVisible=true mHasMenu=false
mRetainInstance=false mRetaining=false mUserVisibleHint=true
mFragmentManager=FragmentManager{41e4d9a0 in MainActivity{41e4d8a8}}
mActivity=com.dslomer64.fragments.MainActivity#41e4d8a8
Added Fragments:
#0: OutputFragment{41ebf0f0 #1 id=0x7f070000}
Back Stack:
#0: BackStackEntry{41e6d288 #0}
mName=null mIndex=0 mCommitted=true
Operations:
Op #0: REPLACE InputFragment{41e6d1d8 #0 id=0x7f070000}
Back Stack Indices:
#0: BackStackEntry{41e6d288 #0}
#1: BackStackEntry{41ebf8d0 #1}
FragmentManager misc state:
mActivity=com.dslomer64.fragments.MainActivity#41e4d8a8
mContainer=android.app.Activity$1#41e4da18
mCurState=5 mStateSaved=false mDestroyed=false
ViewRoot:
mAdded=true mRemoved=false
mConsumeBatchedInputScheduled=false
mPendingInputEventCount=0
mProcessInputEventsScheduled=false
mTraversalScheduled=false
android.view.ViewRootImpl$NativePreImeInputStage: mQueueLength=0
android.view.ViewRootImpl$ImeInputStage: mQueueLength=0
android.view.ViewRootImpl$NativePostImeInputStage: mQueueLength=0
Choreographer:
mFrameScheduled=false
mLastFrameTime=20289147 (31 ms ago)
View Hierarchy:
com.android.internal.policy.impl.PhoneWindow$DecorView{41e50e28 V.E..... R....... 0,0-800,1216}
com.android.internal.widget.ActionBarOverlayLayout{41e51e40 V.ED.... ........ 0,0-800,1216 #1020317 android:id/action_bar_overlay_layout}
android.widget.FrameLayout{41e53548 V.E..... ......I. 0,108-800,1216 #1020002 android:id/content}
android.widget.LinearLayout{41ec5d60 V.E..... ......I. 0,0-800,1108}
android.widget.TextView{41ec6080 V.ED.... ........ 0,0-14,101 #7f070007 app:id/txvIn_output_fragment}
com.android.internal.widget.ActionBarContainer{41e53a68 V.ED.... ........ 0,33-800,108 #1020318 android:id/action_bar_container}
com.android.internal.widget.ActionBarView{41e565d0 V.E..... ........ 0,0-800,75 #1020319 android:id/action_bar}
android.widget.LinearLayout{41e56d40 V.....C. ........ 11,0-248,75}
com.android.internal.widget.ActionBarView$HomeView{41e5abe0 V.E..... ........ 0,0-75,75}
android.widget.ImageView{41e5b0b0 G.ED.... ......I. 0,0-0,0 #102025a android:id/up}
android.widget.ImageView{41e5c1a8 V.ED.... ........ 5,5-69,69 #102002c android:id/home}
android.widget.LinearLayout{41e5d680 V.E..... ........ 75,21-237,54}
android.widget.TextView{41e5db28 V.ED.... ........ 0,0-151,33 #1020265 android:id/action_bar_title}
android.widget.TextView{41e5eb40 G.ED.... ......I. 0,0-0,0 #1020266 android:id/action_bar_subtitle}
com.android.internal.view.menu.ActionMenuView{41ea45b0 V.ED.... ......ID 800,0-800,75}
com.android.internal.widget.ActionBarContextView{41e5f438 G.E..... ......ID 0,0-0,0 #102031a android:id/action_context_bar}
com.android.internal.widget.ActionBarContainer{41e61e58 G.ED.... ......ID 0,0-0,0 #102031b android:id/split_action_bar}
Looper (main, tid 1) {41e42ba0}
(Total messages: 0, idling=false, quitting=false)
id=1: thread exiting with uncaught exception (group=0x41905cf8)
id=1: uncaught exception occurred
.lang.IllegalArgumentException: No view found for id 0x7f070000 (com.dslomer64.fragments:id/container) for fragment OutputFragment{41ebf0f0 #1 id=0x7f070000}
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:882)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:698)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
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:831)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:647)
at dalvik.system.NativeStart.main(Native Method)
id=1: calling UncaughtExceptionHandler
FATAL EXCEPTION: main
Process: com.dslomer64.fragments, PID: 24665
java.lang.IllegalArgumentException: No view found for id 0x7f070000 (com.dslomer64.fragments:id/container) for fragment OutputFragment{41ebf0f0 #1 id=0x7f070000}
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:882)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:698)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
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:831)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:647)
at dalvik.system.NativeStart.main(Native Method)
The code below produces the desired activity. WITH Fragments.
MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity
{
public static boolean PORTRAIT_MODE;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.main);
PORTRAIT_MODE = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT );
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (PORTRAIT_MODE)
{
EditText inputP = (EditText)findViewById(R.id.input_in_main_portrait);
Intent outputActivity;
outputActivity = new Intent(mContext, OutputActivity.class);
outputActivity.putExtra("numberOfLetters", inputP.getText().toString());
startActivity(outputActivity);
} else
{
EditText inputL = (EditText)findViewById(R.id.input_in_main_portrait);
TextView outputL = (TextView)findViewById(R.id.txvIn_output_fragment);
outputL.setText(DoStuff.createOutput(Integer.parseInt(inputL.getText().toString())));
}
}
});
}
}
DoStuff.java
public class DoStuff
{
public static String createOutput(int k){
String s = "";
for(int i = 0; i < k; i++)
s += "\n" + (char)(i+65);
return s;
}
}
OutputActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class OutputActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent i = getIntent();
String s = i.getStringExtra("numberOfLetters");
Log.w("OutputActivity=====", "`````TRYING to be Displaying " + s + " letters in what? Portrait? " + MainActivity.PORTRAIT_MODE);
setContentView(R.layout.output_fragment);
TextView et = (TextView) findViewById(R.id.txvIn_output_fragment);
et.setText(DoStuff.createOutput(Integer.parseInt(s)));
}
}
InputFragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class InputFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
super.onCreateView(inflater, parent, savedInstanceState);
return inflater.inflate(R.layout.input_fragment, parent, false);
}
}
OutputFragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OutputFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
super.onCreateView(inflater, parent, savedInstanceState);
return inflater.inflate(R.layout.output_fragment, parent, false);
}
}
input_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id ="#+id/tvIn_main_portrait" android:layout_width ="wrap_content" android:layout_height="wrap_content"
android:text="How many?"
/>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="#+id/input_in_main_portrait"
android:text="4"
/>
<Button
android:id="#+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Press to get output"
/>
</LinearLayout>
output_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >
<TextView
android:id="#+id/txvIn_output_fragment" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Output will go here in OutputFragment"
/>
</LinearLayout>
layout\main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<fragment android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/main_fragment"
android:name="com.dslomer64.fragthis.InputFragment"
/>
</LinearLayout>
layout-land\main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"
android:layout_weight="3"
>
<fragment android:layout_width="wrap_content" android:layout_height="match_parent"
android:id="#+id/input_fragment"
android:name="com.dslomer64.fragthis.InputFragment"
/>
<fragment android:layout_width="wrap_content" android:layout_height="match_parent"
android:id="#+id/output_fragment"
android:name="com.dslomer64.fragthis.OutputFragment"
/>
</LinearLayout>
I am mainly looking for clarification and advice on this. In the app I am working on I setup a fragment for handling some basic controls and text, and moved the necessary XML from the activities layout file into the fragments layout file, without making any changes. However now when I run the app I get a NULLPOINTEREXCEPTION and it seems to be caused at line 19 in my GameStart activty when I try to set the textView by its ID. I have not changed the ID, only moved it to the fragment layout file, so I have two questions:
1) What exactly is the reason this is happening, because something similar happened before that I resolved but I don't see the reason it was happening in the reference docs on Android Developers
2) Any advice on how to fix this
Below is the GameStart activity, LogCat with the error, and the XML files in question. Thanks in advance, I've spent 2 hours now trying to find this answer.
EDITED FILES/LOGCAT BELOW
LogCat:
12-04 13:48:06.322 826-826/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at com.saphiric.simproject.GameStart.<init>(GameStart.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Starting Activity (The error occurs when the app tries to start the GameStart activity):
package com.saphiric.simproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class TitleMenu extends ActionBarActivity {
public void startGame(View view){
Intent gameStart = new Intent(this, GameStart.class);
startActivity(gameStart);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
setContentView(R.layout.activity_main_menu);
}
}
Fragment XML
<?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">
<!-- Relative layout to handle main interaction area -->
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:background="#drawable/bg_text">
<TextView
android:id="#id/storyText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="#string/story_opening_one"
android:textColor="#color/black" />
<Button
android:id="#+id/advanceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/controlsFragment"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="#drawable/button_advance"
android:onClick="advanceGame" />
<Button
android:id="#+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#id/advanceButton"
android:background="#drawable/menu_button" />
</RelativeLayout>
</RelativeLayout>
Fragment Class:
package com.saphiric.simproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Saphiric on 12/4/14.
*/
public class ControlsFragment extends Fragment {
/**
* Fragment Lifecycle Methods
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Inflates the layout resource for the fragment
return inflater.inflate(R.layout.controls_fragment, container, false);
}
#Override
public void onPause(){
}
}
GameStart activity:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity{
/**
* Necessary activity variables
*/
protected int clickCount = 0;
TextView storyText = (TextView) findViewById(R.id.storyText);
/**
* Sets up and alert dialogue builder for making decisions
* This will need to be revised during production
*/
AlertDialog.Builder decisionTime = new AlertDialog.Builder(getApplicationContext());
/**
* Handles advancing non character based conversations at the beginning
* of the story.
* If the player decides to investigate the scream, then the app loads the appropriate activity, and the same with the
* decision to leave the scene.
*/
public void advanceGame(View view){
clickCount = clickCount + 1; // Increments clickCount by 1 per click
if (clickCount == 1){
storyText.setText(R.string.story_opening_two);
} else if(clickCount == 2){
decisionTime.setTitle("Decision Time!"); // Sets the title for the decision box
decisionTime.setCancelable(false); // Sets it so that the decision can not be cancelled.
decisionTime.setPositiveButton("Investigate",new DialogInterface.OnClickListener() { // Sets up the positive button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
decisionTime.setNegativeButton("Leave the scene.",new DialogInterface.OnClickListener() { // Sets up the negative button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
}
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
}
}
GameStart Layout 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"
android:background="#drawable/bg_school_gate"
android:orientation="vertical">
<fragment
android:id="#+id/controlsFragment"
android:name="com.saphiric.simproject.ControlsFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="#layout/controls_fragment" />
</RelativeLayout>
No, you don't have any fragment here, read more on How to use fragments.
But that's not your problem it should work the way you did it.
The only problem is that you're calling findViewById in your constructor, or even before that.
findViewById only works if you have a UI, so you must do all UI initialization after setContentView in onCreate!
TextView storyText;
...
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
}
Also don't forget to call show() on decisionTime.
TextView storyText = (TextView) findViewById(R.id.storyText);
This should only be called after you set your contentview.
The final result should be:
TextView storyText;
And then on onCreate
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
1) The reason this is happening is that the view has not yet been instantiated at the time you are trying to get it's reference.
2) How to fix it: if you have a Fragment, then you should get a reference to it's View's in the Fragment.onCreateView() method. Then you can setup the Activity to talk to the Fragment to do whatever changes you need to the View.
Hi I have been creating an app that implements a cutom sliding navigation drawer. However, I keep on receiving an error shown on the title.
Logs:
10-30 15:38:20.510: E/AndroidRuntime(1863): FATAL EXCEPTION: main
10-30 15:38:20.510: E/AndroidRuntime(1863): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobextph.krispykreme/com.mobextph.krispykreme.ParentActivity}: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Handler.dispatchMessage(Handler.java:99)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Looper.loop(Looper.java:137)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invokeNative(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invoke(Method.java:511)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-30 15:38:20.510: E/AndroidRuntime(1863): at dalvik.system.NativeStart.main(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): Caused by: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1170)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.changeFragment(ParentActivity.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.onCreate(ParentActivity.java:111)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Activity.performCreate(Activity.java:5104)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
The Main Activity class is:
package com.mobextph.krispykreme;
import java.util.ArrayList;
import com.mobextph.krispykreme.constants.Constants;
import android.R.color;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
public class ParentActivity extends FragmentActivity {
private Fragment changedFragment= null;
private FragmentManager fm;
private DrawerLayout mDrawerLayout;
private LinearLayout linearLayout;
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 ArrayList<String> navDrawerItems;
private ArrayAdapter<String> adapter;
private String[] menuItem= {"ORDER", "STAMP CARD", "REWARDS", "STORES", "FAVORITES"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Drawable d;
// getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
/*Slider*/
mTitle = mDrawerTitle = getTitle();
navMenuTitles= menuItem;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, R.id.title, menuItem));
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.button_menu, //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) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().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
// changeFragment(-1);
}
fm = getSupportFragmentManager();
// DatabaseHandler db= new DatabaseHandler(this);
//
// for(int i = 0; i < 2; i++){
// db.insertFavorite(Constants.id[i], Constants.imageItem[i],
// Constants.title[i], Constants.price[i], Constants.desc[i],
// Constants.status[i]);
// }
changeFragment(-1);
}
public void changeFragment(int fragment){
FragmentTransaction transaction = fm.beginTransaction();
changedFragment = null;
switch(fragment){
case -1:
changedFragment = new HomeFragment();
// mDrawerLayout.closeDrawers();
break;
case Constants.ORDER_SCREEN_CLICKED:
changedFragment = new OrderFragment();
break;
case Constants.FAVORITES_SCREEN_CLICKED:
changedFragment = new FavoritesFragment();
break;
}
if (changedFragment != null) {
transaction.replace(R.id.fragment_holder, changedFragment);
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
mDrawerList.setItemChecked(fragment, true);
mDrawerList.setSelection(fragment);
mDrawerLayout.closeDrawer(linearLayout);
}
}
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
int fragment = 0;
if(position == 0)
fragment= Constants.ORDER_SCREEN_CLICKED;
else if(position == 4)
fragment= Constants.FAVORITES_SCREEN_CLICKED;
changeFragment(fragment);
}
}
// #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);
if(mDrawerToggle.onOptionsItemSelected(item))
return true;
switch(item.getItemId()){
default: return super.onOptionsItemSelected(item);
}
}
/**
* 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 toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The view code that shows a linear layout for the sliding drawer and a listview is:
<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" >
<FrameLayout
android:id="#+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#008265"
android:gravity= "left" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/icon_login"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="LOGIN"
android:textSize="15dp"
android:paddingLeft="5dp"
android:paddingRight="0dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="|"
android:gravity="center"
android:textSize="15dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="SIGN UP"
android:textSize="15dp"
android:paddingLeft="0dp"
android:paddingRight="5dp"/>
</LinearLayout>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="match_parent"
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:gravity= "left" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Try setting
layout_gravity="start" or layout_gravity="left"
in your left_drawer instead of gravity
I am stuck with an idea.
I am trying to implement a feature in a android application.
I have an edittext and a button, if I enter 3 in edittext
and press the button I want to go to another activity which will be having 3 buttons.
If i enter 10 I wanna go to another activity where to display 10 buttons.
I know how to make such switch, I don't know how to do it dynamically ,
I want to make for values between 0 and 10 and I don't want to have 10 fragments .
Plaese give me solution to achieve it ..
Thanks..
Untill now:
mainactivity.java:
package com.example.instances_temperature;
import com.example.instances_temperature.Tabel;
import android.content.Intent;
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.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText instances;
Button ok;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ok = (Button) findViewById(R.id.ok);
instances = (EditText) findViewById(R.id.instances);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (instances.getText().toString().length() > 0)
{
int value = Integer.parseInt(instances.getText().toString());;
if(value > 10)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value<0)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value >= 0 && value <=10)
{
schimba(v);
}
}
else
{
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
}
}
});
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);
}
/**
* 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;
}
}
public void schimba(View view){
int value = Integer.parseInt(instances.getText().toString());;
Intent intent = new Intent(this, Tabel.class);
intent.putExtra("max", value);
startActivity(intent);
}
}
activity_main.xml:
<RelativeLayout 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.example.instances_temperature.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/ShowValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Instances No.:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/instances"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="#+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/instances"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="Ok"
android:onClick="schimba" />
</RelativeLayout>
tabel.java:
package com.example.instances_temperature;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.os.Build;
public class Tabel extends ActionBarActivity {
int i;
int value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout = (LinearLayout)findViewById(R.id.container);
for(i=1;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowview = layoutinflate.inflate( R.layout.ShowMe, null);
TextView showvalue;
showvalue = (TextView) rowview.findViewById(R.id.showid);
showvalue.setText(""+value);
layout.addView(rowview);
}
//showvalue.setText(String.valueOf(getIntent().getExtras().getInt("max")));
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.tabel, 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);
}
/**
* 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_tabel,
container, false);
return rootView;
}
}
}
activity_tabel.xml
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.instances_temperature.Tabel"
tools:ignore="MergeRootFrame" >
</LinearLayout>
LinearLayout code of inflation_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/inflationn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ShowMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
LogCat error:
04-24 06:21:04.244: E/AndroidRuntime(269): FATAL EXCEPTION: main
04-24 06:21:04.244: E/AndroidRuntime(269): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.instances_temperature/com.example.instances_temperature.Tabel}: java.lang.NullPointerException
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.os.Looper.loop(Looper.java:123)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-24 06:21:04.244: E/AndroidRuntime(269): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 06:21:04.244: E/AndroidRuntime(269): at java.lang.reflect.Method.invoke(Method.java:521)
04-24 06:21:04.244: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-24 06:21:04.244: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-24 06:21:04.244: E/AndroidRuntime(269): at dalvik.system.NativeStart.main(Native Method)
04-24 06:21:04.244: E/AndroidRuntime(269): Caused by: java.lang.NullPointerException
04-24 06:21:04.244: E/AndroidRuntime(269): at com.example.instances_temperature.Tabel.onCreate(Tabel.java:42)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-24 06:21:04.244: E/AndroidRuntime(269): ... 11 more
You can get the value from the editText by...
String value= EditText.getText().toString();
Pass the value to another activity (Activity2) through Intent
Now in Activity2 you write this code in the onCreate()
for(int i=1 ; i<= value ; i++){
Button b = new Button(getApplicationContext());
LinearLayout.addView(b);
}
Answer to your edited question.....
main xml file activity_table:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
layout file to be inflated layout_inflate:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ShowValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text" />
</LinearLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout= (LinearLayout)findViewById(R.id.layout)
for(i=0;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = layoutinflate.inflate( R.layout.layout_inflate, null);
TextView showvalue;
showvalue = (TextView) rowview.findViewById(R.id.ShowValue);
showvalue.setText(""+value);
layout.addView(rowview);
}
You can retrieve the EditText value on tha Button click. And pass the Value with the intent.
In that Activity you can build your logic Using Swicth cases. Then you can add the number of Buttons dynamically (eg:- for(i=0;i<yourValue;i++) yourValue is got From intent.)