• So i'm creating 2 fragments, testing "Inter-fragment communication" pattern:
• FragmentA contains a ListView, FragmentB contains a TextView.
In portrait mode: MainActivity contains FragmentA(listview), if user click on an item then move to AnotherActivity which contains FragmentB(textview) with some text..
• In lanescape mode: MainActivity contains both FragmentA and B..
• My lanescape mode worked fine, by in portrait mode if i click on an item, its crashed.
FragmentA.java:
public class FragmentA extends Fragment implements OnItemClickListener {
ListView list;
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_layout_a, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
list = (ListView) getActivity().findViewById(R.id.listView1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.titles, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
Log.d("this", "Done setting listview");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
comm.respone(arg2);
}
void setCommunicator(Communicator c) {
comm = c;
}
public interface Communicator {
public void respone(int index);
}
}
FragmentB.java:
public class FragmentB extends Fragment {
TextView display;
String[] data;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_layout_b, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
display = (TextView) getActivity().findViewById(R.id.textView1);
Resources res = getResources();
data = res.getStringArray(R.array.detail);
Log.d("this", "Fragment B created ");
super.onActivityCreated(savedInstanceState);
}
void changeText(int index) {
display.setText(data[index]);
Log.d("this", "changing text");
}
}
MainActivity.java:
public class MainActivity extends Activity implements FragmentA.Communicator {
FragmentA f1;
FragmentB f2;
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
f1 = (FragmentA) manager.findFragmentById(R.id.fragment1);
f1.setCommunicator(this);
Log.d("this", "setCommunicator");
}
#Override
public void respone(int index) {
// TODO Auto-generated method stub
f2 = (FragmentB) manager.findFragmentById(R.id.fragment2);
Log.d("this", "f2 referenced from Main");
if (f2 != null && f2.isVisible())// landscape
{
f2.changeText(index);
} else // portrait
{
Intent i = new Intent(this, AnotherActivity.class);
i.putExtra("index", index);
startActivity(i);
}
}
}
AnotherActivity.java:
public class AnotherActivity extends Activity {
FragmentB f2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
Log.d("this", "Another Activity");
f2 = (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2);
Log.d("this","fragment2 in Another Activity");
Intent i = getIntent();
int index = i.getIntExtra("index", 0);
Log.d("this", "Get intent extras");
if (f2 != null)
{
f2.changeText(index);
Log.d("this", "changing text in Another Activity");
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.fragmentdemo_2.MainActivity" >
<fragment
android:id="#+id/fragment1"
android:name="com.example.fragmentdemo_2.FragmentA"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
activity_another.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.fragmentdemo_2.AnotherActivity" >
<fragment
android:id="#+id/fragment2"
android:name="com.example.fragmentdemo_2.FragmentB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
fragment_layout_a.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" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="#addbb3"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
fragment_layout_b.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="..."
android:background="#22c936"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fragmentdemo_2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AnotherActivity"
android:label="#string/title_activity_another" >
<intent-filter>
<action android:name="android.intent.action.ANOTHERACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
• Logcat:
09-30 11:38:40.406: E/AndroidRuntime(14991): FATAL EXCEPTION: main
09-30 11:38:40.406: E/AndroidRuntime(14991): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragmentdemo_2/com.example.fragmentdemo_2.AnotherActivity}: java.lang.NullPointerException
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.app.ActivityThread.access$700(ActivityThread.java:150)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.os.Handler.dispatchMessage(Handler.java:99)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.os.Looper.loop(Looper.java:137)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.app.ActivityThread.main(ActivityThread.java:5279)
09-30 11:38:40.406: E/AndroidRuntime(14991): at java.lang.reflect.Method.invokeNative(Native Method)
09-30 11:38:40.406: E/AndroidRuntime(14991): at java.lang.reflect.Method.invoke(Method.java:511)
09-30 11:38:40.406: E/AndroidRuntime(14991): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
09-30 11:38:40.406: E/AndroidRuntime(14991): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
09-30 11:38:40.406: E/AndroidRuntime(14991): at dalvik.system.NativeStart.main(Native Method)
09-30 11:38:40.406: E/AndroidRuntime(14991): Caused by: java.lang.NullPointerException
09-30 11:38:40.406: E/AndroidRuntime(14991): at com.example.fragmentdemo_2.FragmentB.changeText(FragmentB.java:38)
09-30 11:38:40.406: E/AndroidRuntime(14991): at com.example.fragmentdemo_2.AnotherActivity.onCreate(AnotherActivity.java:27)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.app.Activity.performCreate(Activity.java:5267)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
09-30 11:38:40.406: E/AndroidRuntime(14991): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
09-30 11:38:40.406: E/AndroidRuntime(14991): ... 11 more
• Logcat with filter "this" :
09-29 22:02:16.098: D/this(7795): setCommunicator
09-29 22:02:16.098: D/this(7795): Done setting listview
09-29 22:02:36.848: D/this(7795): f2 referenced from Main
09-29 22:02:36.948: D/this(7795): Another Activity
09-29 22:02:36.948: D/this(7795): fragment2 in Another Activity
09-29 22:02:36.948: D/this(7795): Get intent extras
Please help, thanks in advance! (I'm a newbie in Java-Android)
The problem was that you were not following the proper hierarchy of the fragment and activity. You can always access the views and methods of fragments after you load the fragment.
In your case you were indirectly passing the value from MainActivity to FragmentA and from FragmentA you were opening AnotherActivity which contains your FragmentB. In your case your were trying to pass value through intent from one fragment to another using an Intent, which not a valid way. You can always pass values between fragments through Bundle and get it from Bundle.
Check out my changes below ,its working now. and do relevant changes according to your need.
Just do the following changes in your all the classes.
MainActivity.java
public class MainActivity extends Activity {
FragmentA f1;
FragmentB f2;
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
f1 = (FragmentA) manager.findFragmentById(R.id.fragment1);
Log.d("this", "setCommunicator");
}
/* #Override
public void respone(int index) {
// TODO Auto-generated method stub
f2 = (FragmentB) manager.findFragmentById(R.id.fragment2);
Log.d("this", "f2 referenced from Main");
if (f2 != null && f2.isVisible())// landscape
{
f2.changeText(index);
} else // portrait
{
Intent i = new Intent(this, AnotherActivity.class);
i.putExtra("index", index);
startActivity(i);
}
}*/
}
FragmentA.java
public class FragmentA extends Fragment implements OnItemClickListener {
ListView list;
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_layout_a, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
list = (ListView) getActivity().findViewById(R.id.listView1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.titles, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
Log.d("this", "Done setting listview");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(FragmentA.this.getActivity(), AnotherActivity.class);
i.putExtra("index", arg2);
startActivity(i);
}
void setCommunicator(Communicator c) {
comm = c;
}
public interface Communicator {
public void respone(int index);
}
}
AnotherActivity.java
public class AnotherActivity extends Activity {
FragmentB f2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
FragmentManager mang = getFragmentManager();
Log.d("this", "Another Activity");
Log.d("this", "fragment2 in Another Activity");
Intent i = getIntent();
int index = i.getIntExtra("index", 0);
Bundle bund = new Bundle();
bund.putInt("val", index);
f2 = (FragmentB) mang.findFragmentById(R.id.fragment2);
f2.changeText(index);
Log.d("this", "Get intent extras");
}
}
FragmentB.java
public class FragmentB extends Fragment {
TextView display;
String[] data;
int val;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View m_view;
m_view = inflater.inflate(R.layout.fragment_layout_b, container, false);
display = (TextView) m_view.findViewById(R.id.textView1);
Resources res = getActivity().getResources();
data = res.getStringArray(R.array.titles);
Log.d("this", "Fragment B created ");
return m_view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
public void changeText(int index) {
val=getActivity().getIntent().getIntExtra("index",0);
display.setText(data[val]);
Log.d("this", "changing text");
}
}
Related
i am new in android and i was trying to make my app works in all phones
it works in 23 API and don't work in 19 API kitkat it crashes each time i open the application
Is there a way to fix this problem ?
and could you tell me what was my problem and explain it to me,
public class MainActivity extends AppCompatActivity {
private Button ButtonStart,ButtonReset ;
private TextView Number ;
private CountDownTimer myTimer ;
private MediaPlayer TimePassesSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
ButtonReset = (Button)findViewById (R.id.button2);
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
}
public void addListerOnButton () {
ButtonStart.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if (ButtonStart.getText ().toString () != "Stop") {
int StartTime = Integer.parseInt (Number.getText ().toString ());
myTimer = new CountDownTimer (StartTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
ButtonStart.setText ("Stop");
Number.setText (""+millisUntilFinished / 1000);
}
public void onFinish() {
Number.setText("60");
ButtonStart.setText ("Start");
TimePassesSound.setLooping(false);
TimePassesSound.start();
}
}.start();
} else {
ButtonStart.setText ("Start");
myTimer.cancel ();
}
}
}
);
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
-- Error messages
Process: com.aabdelrahman730yahoo.mydesign, PID: 3627
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aabdelrahman730yahoo.mydesign/com.aabdelrahman730yahoo.mydesign.MainActivity}: java.lang.NullPointerException
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.NullPointerException
at com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
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)
Main Activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_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.aabdelrahman730yahoo.mydesign.MainActivity"
android:touchscreenBlocksFocus="false"
android:background="#34416a">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:id="#+id/textView"
android:singleLine="true"
android:textSize="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
That's was my full problem i hope someone could help me with
You are calling the method of the view without initializing it.
You need to initialize the view first and then call the method
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
Check this,
As #Rod_ mentioned and from error log, it clearly states that view is not initialized.
java.lang.NullPointerException
at
com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at
com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
Make sure following buttons were initialized in your java code.
ButtonStart and ButtonReset -- Buttonreset is not initialized here it seems.
Change your code like below.
under oncreate
ButtonStart = (Button)findViewById (R.id.button);
ButtonReset = (Button)findViewById (R.id.button_); --> You missed it ..
Number = (TextView)findViewById (R.id.textView);
addListerOnButton ();
addListerOnButton2 ();
Hope it seems clear..!!
UPDATE:
You may not initialized the media player.
The problem may be also due to usage of media player. Kindly check the code below.
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
in your case
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
Add the above lines befor calling the functions.
I always get a NullPointerException when I try to access a fragment from inside my main activity. No matter what I do.
The issue is that I use TabsPagerAdapter and ViewPager and I don't know how to get the inflated views (the fragment's onCreate() method returns the inflated view already).
The goal is to get access to an element inside the fragment and hide or show it dynamically by a single background thread which should also do this for more fragments.
MainActivity.java
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener
{
/* swipe view */
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private android.app.ActionBar actionBar;
// tab titles
private String[] tabs = { "Basic", "Advanced", "Settings"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* init swipe views */
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(mAdapter);
actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/* addTab returns void, how to geht my fragements and their views???*/
for (String tabName : tabs)
actionBar.addTab(actionBar.newTab().setText(tabName).setTabListener(this));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
#Override
public void onPageScrollStateChanged(int arg0) {}
});
}
public void testFunction()
{
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.layout.fragment_page1);
GridLayout gridlayout = (GridLayout) fragmentPage1.getRootView().findViewById(R.id.adBannerBasicLayout);
gridlayout.setVisibility(GridLayout.VISIBLE); /* THATS MY GOAL */
}
FragmentPage1.java
public class FragmentPage1 extends Fragment {
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_page1, container, false);
/* HERE IT IS WORKING FINE,
but later I want to make it visible again
from code OUTSIDE FragmentPage1 ??? */
GridLayout gridlayout = (GridLayout) rootView.findViewById(R.id.adBannerBasicLayout);
gridlayout.setVisibility(GridLayout.GONE);
return rootView;
}
/* so I tried this, but also get always NullPointerException */
public View getRootView()
{
return rootView;
}
}
fragment_page1.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/settings_scroll_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="vertical"
android:rowCount="12"
android:columnCount="5"
>
<!-- Some Banner Ads I want to hide show -->
<!-- I want to access this from everywhere! -->
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adBannerBasicLayout"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:rowCount="3"
android:columnCount="1"
android:layout_row="0"
android:layout_column="0"
android:layout_columnSpan="5">
<Space
android:layout_width="0dp"
android:layout_height="5dp"
android:layout_row="0"
android:layout_column="0"
/>
<com.google.android.gms.ads.AdView
android:id="#+id/adBannerBasic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxxxxxxxxxxx"
android:layout_row="1"
android:layout_column="0"
>
</com.google.android.gms.ads.AdView>
<Space
android:layout_width="0dp"
android:layout_height="5dp"
android:layout_row="2"
android:layout_column="0"
/>
</GridLayout>
<!-- more stuff... -->
</GridLayout>
</ScrollView>
Please help me out, I'm totally stuck!
THANKS!
EDIT:
The scond line in testFunction() throws the NullPointerException:
GridLayout gridlayout = (GridLayout) fragmentPage1.getRootView().findViewById(R.id.adBannerBasicLayout);
because getSupportFragmentManager() always returns null:
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.layout.fragment_page1);
Logcat Outoput
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3969)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19330)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3964)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19330)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.tzapp.smote.MainActivity.testFuntion(MainActivity.java:393)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3964)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19330)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
You are using the wrong static value from the auto generated R file!
Instead of using R.layout.fragment_page1 which references the XML resource you should use R.id.fragment_page1 which should be the id of the fragment in your R.layout.activity_main XML file at /res/layout/activity_main.xml
R.layout references XML layout files
R.id references individual XML nodes (Views, Fragments etc.)
So in short, change:
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.layout.fragment_page1);
To:
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.id.fragment_page1);
And make sure that your fragment id in /res/layout/activity_main.xml is set to R.id.fragment_page1 like so:
<fragment android:name="com.example.yourpackage.FragmentPage1"
android:id="#+id/fragment_page1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
you use getSupportFragmentManager() to get fragment.
Please double check if your FragmentPage1 extends a android.support.v4.app.Fragment;
not a
android.Fragment;
After updating SDK and repository, there is new trouble. I cant build anymore and I dont want to compile on level 23 :(
Information:Gradle tasks [clean, :app:generateDebugSources, :app:generateDebugTestSources]
:app:clean
:app:preBuild
:app:preDebugBuild
:app:checkDebugManifest
:app:preReleaseBuild
:app:prepareComAndroidSupportAppcompatV72300Library
:app:prepareComAndroidSupportSupportV42300Library
:app:prepareComGoogleAndroidGmsPlayServicesAds750Library
:app:prepareComGoogleAndroidGmsPlayServicesAnalytics750Library
:app:prepareComGoogleAndroidGmsPlayServicesBase750Library
:app:prepareComInstabugLibraryInstabugcore161Library
:app:prepareComInstabugLibraryInstabugsupport161Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources
:app:mergeDebugResources
:app:processDebugManifest
:app:processDebugResources
C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.0\res\values-v23\values-v23.xml
Error:(1) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(1) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
Error:Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
C:\Users\Tom\AppData\Local\Android\sdk\build-tools\21.1.2\aapt.exe package -f --no-crunch -I C:\Users\Tom\AppData\Local\Android\sdk\platforms\android-21\android.jar -M C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\manifests\full\debug\AndroidManifest.xml -S C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\res\debug -A C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\assets\debug -m -J C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\generated\source\r\debug -F C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\res\resources-debug.ap_ --debug-mode --custom-package org.tzapp.smote -0 apk --output-text-symbols C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\symbols\debug
Error Code:
1
Output:
C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\res\debug\values-v23\values.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\res\debug\values-v23\values.xml:20: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
Information:BUILD FAILED
Information:Total time: 40.157 secs
Information:3 errors
Information:0 warnings
Also I found another answer, which is I think most satisfying :)
I forgot to mention that there is another class. It all comes from that stupid piece of example code for Swipe Views which is avaible somewhere on developers.google.com ...
Everytime I tried to access the FragmentPages via my TabPagerAdapter class using the stupid getItem(int i) method, I created a new Fragment() :-/ Very irritating!
Class TabsPagerAdapter from bad google example
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm, MainActivity mainActivity){
super(fm);
}
// page index, fragment selector
#Override
public Fragment getItem(int index) {
switch (index)
{
case 0: return new FragmentPage1(); // bad practice
case 1: return new FragmentPage2(); // why should one do that?
case 2: return new FragmentPage3();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
What a piece of crap ^^ And I just copied it over and then totally forgot about it's existence ;)
Moved instanciation of fragments to constructor and keeped them for later use. Works perfectly now.
Class TabsPagerAdapter after optimization
public class TabsPagerAdapter extends FragmentPagerAdapter {
// hosted fragments
private FragmentPage fragmentPageBasic;
private FragmentPage fragmentPageAdvanced;
private FragmentPage fragmentPageSettings;
//constructor
public TabsPagerAdapter(FragmentManager fm, MainActivity mainActivity){
super(fm);
fragmentPageBasic = new FragmentPage();
fragmentPageBasic.setMainActivity(mainActivity);
fragmentPageBasic.setLayoutResource(R.layout.fragment_page1);
fragmentPageBasic.setAdBannerResource(R.id.adBannerBasic);
fragmentPageBasic.setAdBannerLayoutResource(R.id.adBannerBasicLayout);
fragmentPageAdvanced = new FragmentPage();
fragmentPageAdvanced.setMainActivity(mainActivity);
fragmentPageAdvanced.setLayoutResource(R.layout.fragment_page2);
fragmentPageAdvanced.setAdBannerResource(R.id.adBannerAdvanced);
fragmentPageAdvanced.setAdBannerLayoutResource(R.id.adBannerAdvancedLayout);
fragmentPageSettings = new FragmentSettingsPage();
fragmentPageSettings.setMainActivity(mainActivity);
fragmentPageSettings.setLayoutResource(R.layout.fragment_page3);
fragmentPageSettings.setAdBannerResource(R.id.adBannerSettings);
fragmentPageSettings.setAdBannerLayoutResource(R.id.adBannerSettingsLayout);
}
// page index, fragment selector
#Override
public Fragment getItem(int index) {
switch (index)
{
case 0: return fragmentPageBasic;
case 1: return fragmentPageAdvanced;
case 2: return fragmentPageSettings;
}
return null;
}
#Override
public int getCount() {
return 3;
}
// GETTERS
public FragmentPage getFragmentPageBasic() {return fragmentPageBasic;}
public FragmentPage getFragmentPageAdvanced() {return fragmentPageAdvanced;}
public FragmentPage getFragmentPageSettings() {return fragmentPageSettings;}
}
Instead of having redundant FragmentPage1, Fragment2, FragmentPage3 classes, of course now there is only FragmentPage and FragmentSettingsPage (extends FragmentPage to override OnCreateView method), which results in a much cleaner and more understandable code.
Class FragmentPage
public class FragmentPage extends Fragment {
protected MainActivity mainActivity;
// layout resource
protected int layoutResource;
// view
protected View rootView;
//Admob
protected AdView adBanner;
protected int adBannerResource;
protected int adBannerLayoutResource;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
onCreate(inflater, container);
return rootView;
}
// manage common onCreate things
protected void onCreate(LayoutInflater inflater, ViewGroup container)
{
rootView = inflater.inflate(layoutResource, container, false);
// admob banner
adBanner = (AdView) rootView.findViewById(adBannerResource);
adBanner.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdClosed() {
newAdBannerRequest();
}
#Override
public void onAdFailedToLoad(int errorCode) {
newAdBannerRequest();
}
#Override
public void onAdLeftApplication() {
}
});
if(mainActivity.showAdBanners())
{
newAdBannerRequest();
showAdBanner();
}
else
hideAdBanner();
}
// ADMOB
public void newAdBannerRequest()
{
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("XXXXXXXXXXXXXXXXXXXXXXXXXX") // My Galaxy Nexus test phone
.build();
adBanner.loadAd(request);
}
public void showAdBanner()
{
GridLayout adBannerLayout = (GridLayout) rootView.findViewById(adBannerLayoutResource);
if(adBannerLayout.getVisibility() == GridLayout.GONE)
adBannerLayout.setVisibility(GridLayout.VISIBLE);
}
public void hideAdBanner()
{
GridLayout adBannerLayout = (GridLayout) rootView.findViewById(adBannerLayoutResource);
if(adBannerLayout.getVisibility() == GridLayout.VISIBLE)
adBannerLayout.setVisibility(GridLayout.GONE);
}
// GETTERS
public AdView getAdBanner() { return adBanner;}
public View getRootView() { return rootView;}
// SETTERS
public void setMainActivity(MainActivity mainActivity) {this.mainActivity = mainActivity;}
public void setLayoutResource(int layoutResource){this.layoutResource = layoutResource;}
public void setAdBannerResource(int adBannerResource){this.adBannerResource = adBannerResource;}
public void setAdBannerLayoutResource(int adBannerLayoutResource){this.adBannerLayoutResource = adBannerLayoutResource;}
}
Class FragmentSettingsPage
public class FragmentSettingsPage extends FragmentPage {
// Preferences
public static final String PREFS_NAME = "Preferences";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(inflater, container);
SharedPreferences preferences = mainActivity.getSharedPreferences(PREFS_NAME, 0);
// do some other top secret stuff here ;)
return rootView;
}
}
Any ideas how to improve this further ?
Use import android.support.v4.app.Fragment instead import android.app.Fragment
Please add this in your gradle dependencies
compile 'com.android.support:support-v4:22.1.1'
Edit : please use findFragmentById(R.id.fragment_page1) instead R.layout
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.id.fragment_page1);
The problem arise when I use code for Button , I am referring to The new Boston tutorials.
I am doing exactly what is told but getting error in logcat.
package com.example.myfirstapp;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
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.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int counter=0;
TextView display;
Button add;
Button sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add=(Button) findViewById(R.id.bAdd);
sub=(Button) findViewById(R.id.bSub);
display=(TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter++;
display.setText("Your Total is " +counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter--;
display.setText("Your Total is " +counter);
}
});
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;
}
}
}
This is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat file shows these errors
: FATAL EXCEPTION: main
Process: com.example.myfirstapp, PID: 1873
E/AndroidRuntime(1873): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime(1873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
E/AndroidRuntime(1873):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime(1873):at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime(1873): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime(1873): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(1873): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1873): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1873): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1873): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1873): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1873): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1873): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1873): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1873): at android.view.ViewConfiguration.get(ViewConfiguration.java:325)
E/AndroidRuntime(1873): at android.view.View.<init>(View.java:3448)
E/AndroidRuntime(1873): at android.view.View.<init>(View.java:3505)
E/AndroidRuntime(1873): at android.widget.TextView.<init>(TextView.java:623)
E/AndroidRuntime(1873): at android.widget.Button.<init>(Button.java:107)
E/AndroidRuntime(1873): at android.widget.Button.<init>(Button.java:103)
E/AndroidRuntime(1873): at android.widget.Button.<init>(Button.java:99)
E/AndroidRuntime(1873): at com.example.myfirstapp.MainActivity.<init>(MainActivity.java:18)
E/AndroidRuntime(1873): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(1873): at java.lang.Class.newInstance(Class.java:1208)
E/AndroidRuntime(1873): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
E/AndroidRuntime(1873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
E/AndroidRuntime(1873): ... 11 more
: I/Process(1873): Sending signal. PID: 1873 SIG: 9
This is layout xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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.example.myfirstapp.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textSize="45sp"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/tvDisplay"
/>
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="#string/add_button"
android:gravity="center"
android:layout_gravity="center"
android:id="#+id/bAdd"
/>
<Button
android:id="#+id/bSub"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/sub_button" />
</LinearLayout>
Please help me and please do not downvote me as I am very new and learning.
The fragment is holding the layout. You have to get the reference of buttons and textview from inflated view in onCreateView()
public static class PlaceholderFragment extends Fragment {
int counter=0;
TextView display;
Button add;
Button sub;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
add = (Button) rootView.findViewById(R.id.bAdd);
sub = (Button) rootView.findViewById(R.id.bSub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter++;
display.setText("Your Total is " +counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter--;
display.setText("Your Total is " +counter);
}
});
return rootView;
}
}
You are initializing Button and TextView before fragment's view is created.
Move Button, TextView initialization and callback register code before return rootView statement or override onViewCreated(View view, Bundle savedInstanceState) function of PlaceholderFragment and put code inside that method.
I have been tried to build my first Android Application. Every time I open the application in the emulator, I just get a message that says test has stopped working. It must be something simple. Hope you can help me.
04-06 15:43:47.806: W/dalvikvm(4275): threadid=1: thread exiting with
uncaught exception (group=0xa614d908)
04-06 15:43:47.826: E/AndroidRuntime(4275): FATAL EXCEPTION: main
04-06 15:43:47.826: E/AndroidRuntime(4275):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.test/com.test.MainActivity}:
java.lang.NullPointerException
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.access$600(ActivityThread.java:141)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.os.Handler.dispatchMessage(Handler.java:99)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.os.Looper.loop(Looper.java:137)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.main(ActivityThread.java:5041)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
java.lang.reflect.Method.invokeNative(Native Method)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
java.lang.reflect.Method.invoke(Method.java:511)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
dalvik.system.NativeStart.main(Native Method)
04-06 15:43:47.826: E/AndroidRuntime(4275): Caused by:
java.lang.NullPointerException
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.test.MainActivity.onCreate(MainActivity.java:30)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.Activity.performCreate(Activity.java:5104)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-06 15:43:47.826: E/AndroidRuntime(4275): ... 11 more
Above is the log file
public class Main extends ActionBarActivity {
int counter ;
Button add, sub ;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
sub = (Button) findViewById (R.id.bsub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
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;
}
}
}
Above is the Main class
<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.test.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignLeft="#+id/bsub"
android:layout_alignParentBottom="true"
android:layout_below="#+id/bsub"
android:gravity="center"
android:text="Your total is 0"
android:textSize="45dp" />
<Button
android:id="#+id/badd"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="78dp"
android:gravity="center"
android:text="Add one"
android:textSize="20dp" />
<Button
android:id="#+id/bsub"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/badd"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Subtract one"
android:textSize="20dp" />
</RelativeLayout>
Above is the fragment_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.Hello.firstapp.Main"
tools:ignore="MergeRootFrame" />
ABove is the activity_main.xml
Instead of onCreate() move all ur initialization into onCreateView() as those buttons and textview is in ur fragment_main.xml thats why u got NPE as those buttons and textview is not the part of activity_main.xml.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
add = (Button) rootView.findViewById (R.id.bAdd);
sub = (Button) rootView.findViewById (R.id.bsub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
return rootView;
}
I see your issue. activity_main.xml contains a frame layout, in which your fragment_main.xml is inflated. The thing is that, both add and sub are null, as you're looking for them in the wrong layout. Thus, call the FragmentTransaction first and move all your button code to the onCreateView of the PlaceHolderFragment and your issue should be fixed. I have provided the fixed code, all you have to do is copy it and remove the button code from onCreate (...)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
add = (Button) rootView.findViewById (R.id.bAdd);
sub = (Button) rootView.findViewById (R.id.bsub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
return rootView;
}
Most likely
add = (Button) findViewById (R.id.bAdd);
returns null, because the element is not defined on your activity_main view.
i keep getting a null pointer exception
I have a problem about starting a new activity via using button.
I already checked the previous questions related to mine problem, one of them is almost same but solutions didn't work out for me. So here is my problem.
whenever i start the app it crashes.
i have a main class called MainActivity and new Activity called login
Main class
public class MainActivity extends Activity {
Intent myIntent = new Intent(MainActivity.this, login.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button loginButton = (Button) findViewById(R.id.button_login);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(myIntent);
}
});
}
#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;
}
}
}
logcat
02-18 10:27:42.520 1098-1098/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.app, PID: 1098
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
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.NullPointerException
at com.example.app.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
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)
thanks in advance!!!
EDIT---> MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.app.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.app.login"
android:label="#string/title_activity_login" >
<intent-filter>
<action android:name="android.intent.action.LOGIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.app.MainActivity">
//login Button
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/button_login"
android:layout_marginBottom="160dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="23dp" />
//high score button
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="high score"
android:id="#+id/highScore"
android:layout_alignTop="#+id/button_login"
android:layout_toRightOf="#+id/button_login"
android:layout_marginLeft="45dp" />
//play Button
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Play"
android:id="#+id/Play"
android:layout_above="#+id/button_login"
android:layout_centerHorizontal="true"
android:layout_marginBottom="55dp" />
</RelativeLayout>
Edited corrections with imports
package com.example.app;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
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.Button;
import android.widget.ImageButton;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button loginButton = (Button) findViewById(R.id.button_login);
// if (savedInstanceState == null) {
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, new PlaceholderFragment())
// .commit();
// }
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, login.class);
startActivity(myIntent);
}
});
}
#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;
}
}
}
Move this inside the onCreate method :
Intent myIntent = new Intent(MainActivity.this, login.class);
By using that line outside the method, you are referring to the instance of MainActivity before it is fully created.
Since it looks like you are only using that intent once, you could even move that line inside the onClick method of the loginButton's OnClickListener, as suggested by InnocentKiller.
Remove this line from top of your screen
Intent myIntent = new Intent(MainActivity.this, login.class);
and put under the button click event. So basically your code will something like this for MainActivity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button loginButton = (Button) findViewById(R.id.button_login);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, login.class);
startActivity(myIntent);
}
});
............
...........
}
Do you have the Login activity declared on your manifest as an activity
<activity
android:name="com.examlpe.app.loginActivity"/>
You need an Intent!
try:
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, Login.class);
startActivity(myIntent);
}
});
Your login class should also be named "Login" to serve the name convention
And you need to add the new Login.class to your Manifest like
<activity
android:name="com.example.yourapp.Login"
android:label="#string/app_name"
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity