Unfortunately MyFirstApp has stopped - java

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.

Related

loginButton.setFragment(this); crashes app

I'm trying to make an app that simply logs into facebook and then logs out. My app would compile and load however adding the line: loginButton.setFragment(this) causes a compilation which I have fixed by using the package android.support.v4.app.Fragment rather than android.app.Fragment. The issue is that now my app crashes whenever I try to run it.
This is my MainFragment.java
//MainFragment.java
//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
/**
* A placeholder fragment containing a simple view.
*/
public class MainFragment extends Fragment {
private CallbackManager mCallBackManager;
private TextView mTextDetails;
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome" + profile.getName());
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallBackManager=CallbackManager.Factory.create();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends", "user_photos");
loginButton.setFragment(this);
loginButton.registerCallback(mCallBackManager, mCallBack);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
mCallBackManager.onActivityResult(requestCode, resultCode, data);
}
}
This is my MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stan.facebooktestexactexample" >
<uses-permission
android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:name=".MyApplication"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id"/>
<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="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
</application>
</manifest>
And here is my MainFragment layout file
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
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=".MainActivityFragment">
<TextView
android:text="#+id/text_details"
android:layout_width="match_parent"
android:gravity="center"
android:layout_above="#+id/login_button"
android:layout_height="wrap_content" />
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
</RelativeLayout>
and here is the logcat
--------- beginning of crash
07-25 05:12:55.211 2473-2473/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.stan.facebooktestexactexample, PID: 2473
java.lang.RuntimeException: Unable to instantiate application com.example.stan.facebooktestexactexample.MyApplication: java.lang.ClassNotFoundException: Didn't find class "com.example.stan.facebooktestexactexample.MyApplication" on path: DexPathList[[zip file "/data/app/com.example.stan.facebooktestexactexample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at android.app.LoadedApk.makeApplication(LoadedApk.java:563)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4529)
at android.app.ActivityThread.access$1500(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.stan.facebooktestexactexample.MyApplication" on path: DexPathList[[zip file "/data/app/com.example.stan.facebooktestexactexample-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newApplication(Instrumentation.java:980)
at android.app.LoadedApk.makeApplication(LoadedApk.java:558)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4529)
            at android.app.ActivityThread.access$1500(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Suppressed: java.lang.ClassNotFoundException: com.example.stan.facebooktestexactexample.MyApplication
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
Please Help!!
if you set android:name=".MyApplication" on manifest you have to create MyApplication class.If you dont want that remove it or create class as
public class MyAppilcation extends Application{
...
}
it is used to declare global variables.
see this link How to declare global variables in Android?

Crash when open activity contain fragment

• 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");
}
}

"unfortunately, app has stopped" on clicking login button [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
I am new to this android. Whenever I click the login button, it says "unfortunately, your app has stopped".
There is no compile time error..
I am uploading my MainActivity.java, LoginActivity.java and manifest.xml files..
Please tell me whats the problem or am i doing something wrong?
//MainActivity.java
package com.satty002.swag;
import java.util.Locale;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.parse.ParseAnalytics;
import com.parse.ParseUser;
public class MainActivity extends Activity implements ActionBar.TabListener {
public static final String TAG = MainActivity.class.getSimpleName();
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpened(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
} else {
Log.i(TAG, currentUser.getUsername());
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#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_logout) {
ParseUser.logOut();
navigateToLogin();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
//LoginActivity.java
package com.satty002.swag;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;
public class LoginActivity extends Activity {
protected EditText mUsername;
protected EditText mPassword;
protected Button mLoginButton;
protected TextView mSignUpTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSignUpTextView = (TextView) findViewById(R.id.SignupText);
mSignUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
}
});
mUsername = (EditText) findViewById(R.id.usernameField);
mPassword = (EditText) findViewById(R.id.passwordFiled);
mLoginButton = (Button) findViewById(R.id.loginButton);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
username.trim();
password.trim();
if(username.isEmpty() || password.isEmpty() )
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(R.string.login_error_message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else
{
ParseUser.logInInBackground(username, password, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if(e == null)
{
//success
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(R.string.login_error_message)
.setTitle(R.string.login_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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);
}
}
//manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.satty002.swag"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:name="SwagApplication">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name=".SignupActivity"
android:label="#string/app_name"
android:parentActivityName=".LoginActivity">
</activity>
</application>
//Activity_login.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.satty002.swag.LoginActivity" >
<TextView
android:id="#+id/SignupText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/signup_text" />
<EditText
android:id="#+id/usernameField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="#string/username_hint" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/PasswordField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/usernameField"
android:layout_below="#+id/usernameField"
android:ems="10"
android:hint="#string/password_hint"
android:inputType="textPassword" />
<Button
android:id="#+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/PasswordField"
android:layout_below="#+id/PasswordField"
android:text="#string/login_button_label" />
//logcat
07-25 17:52:52.332: E/Trace(1627): error opening trace file: No such file or directory (2)
07-25 17:52:54.393: D/dalvikvm(1627): GC_CONCURRENT freed 274K, 7% free 6132K/6535K, paused 14ms+110ms, total 330ms
07-25 17:52:55.083: D/libEGL(1627): loaded /system/lib/egl/libEGL_emulation.so
07-25 17:52:55.093: D/(1627): HostConnection::get() New Host Connection established 0xb8462cf0, tid 1627
07-25 17:52:55.123: D/libEGL(1627): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-25 17:52:55.153: D/libEGL(1627): loaded /system/lib/egl/libGLESv2_emulation.so
07-25 17:52:55.363: W/EGL_emulation(1627): eglSurfaceAttrib not implemented
07-25 17:52:55.423: D/OpenGLRenderer(1627): Enabling debug mode 0
07-25 17:52:56.833: W/EGL_emulation(1627): eglSurfaceAttrib not implemented
07-25 17:52:56.833: I/Choreographer(1627): Skipped 37 frames! The application may be doing too much work on its main thread.
07-25 17:52:57.283: D/dalvikvm(1627): GC_CONCURRENT freed 189K, 5% free 6342K/6663K, paused 18ms+101ms, total 151ms
07-25 17:53:19.003: D/AndroidRuntime(1627): Shutting down VM
07-25 17:53:19.003: W/dalvikvm(1627): threadid=1: thread exiting with uncaught exception (group=0xb5f03288)
07-25 17:53:19.014: E/AndroidRuntime(1627): FATAL EXCEPTION: main
07-25 17:53:19.014: E/AndroidRuntime(1627): java.lang.NullPointerException
07-25 17:53:19.014: E/AndroidRuntime(1627): at com.satty002.swag.LoginActivity$2.onClick(LoginActivity.java:50)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.view.View.performClick(View.java:4084)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.view.View$PerformClick.run(View.java:16966)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.os.Handler.handleCallback(Handler.java:615)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.os.Handler.dispatchMessage(Handler.java:92)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.os.Looper.loop(Looper.java:137)
07-25 17:53:19.014: E/AndroidRuntime(1627): at android.app.ActivityThread.main(ActivityThread.java:4745)
07-25 17:53:19.014: E/AndroidRuntime(1627): at java.lang.reflect.Method.invokeNative(Native Method)
07-25 17:53:19.014: E/AndroidRuntime(1627): at java.lang.reflect.Method.invoke(Method.java:511)
07-25 17:53:19.014: E/AndroidRuntime(1627): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-25 17:53:19.014: E/AndroidRuntime(1627): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-25 17:53:19.014: E/AndroidRuntime(1627): at dalvik.system.NativeStart.main(Native Method)
I am going to guess that there is a null pointer somewhere in your onClick for your login activity. you should be able to figure this out by looking at your logcat which should tell you the exact line of code that is causing this crash. probably referencing an object that is not initialized / null
Edit
As stated you have a null reference on line 50 of LoginActivity:
java.lang.NullPointerException
07-25 17:53:19.014: E/AndroidRuntime(1627): at com.satty002.swag.LoginActivity$2.onClick(LoginActivity.java:50
you misspelled the password field reference:
mPassword = (EditText) findViewById(R.id.passwordFiled);
should be
mPassword = (EditText) findViewById(R.id.passwordField);
Line 50 in your LoginActivity throws NullPointerException,
line 50 will be somewhere around:
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
which means mUsername or mPassword is null
Check are you binding right layout to activity, and are you using correct ids

I can't move from current activity to another activity

when try to click on New Activity Button in my MainActivity , my app crash and closed . whit this error on screen " unfortunately[ App Name ] has stopped "
I google this problem and i can't find any Definitive solution.
here is logCat Log , First Java Source ( MainActivity.java ) and seccond java source ( Seccond.java ) .
Logcat Log :
05-03 00:05:17.750: E/AndroidRuntime(1091): FATAL EXCEPTION: main
05-03 00:05:17.750: E/AndroidRuntime(1091): Process: com.example.helloworld, PID: 1091
05-03 00:05:17.750: E/AndroidRuntime(1091): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld/com.example.helloworld.Seccond}: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.helloworld:id/container) for fragment PlaceholderFragment{b2d2faf8 #0 id=0x7f05003c}
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.os.Handler.dispatchMessage(Handler.java:102)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.os.Looper.loop(Looper.java:136)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-03 00:05:17.750: E/AndroidRuntime(1091): at java.lang.reflect.Method.invokeNative(Native Method)
05-03 00:05:17.750: E/AndroidRuntime(1091): at java.lang.reflect.Method.invoke(Method.java:515)
05-03 00:05:17.750: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-03 00:05:17.750: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-03 00:05:17.750: E/AndroidRuntime(1091): at dalvik.system.NativeStart.main(Native Method)
05-03 00:05:17.750: E/AndroidRuntime(1091): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.helloworld:id/container) for fragment PlaceholderFragment{b2d2faf8 #0 id=0x7f05003c}
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.Activity.performStart(Activity.java:5241)
05-03 00:05:17.750: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start
Button btn_img = (Button) findViewById(R.id.btn_image);
Button btn = (Button) findViewById(R.id.btn_Click);
final TextView txt = (TextView) findViewById(R.id.txt_view);
Button btn_avtivity = ( Button) findViewById(R.id.btn_activity);
// For button click
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
txt.setText(" Amin Bassam ");
}
});
// Image show
btn_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ImageView img=(ImageView)findViewById(R.id.img_view);
img.setImageResource(R.drawable.amin);
}
});
btn_avtivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(),Seccond.class);
startActivity(intent);
}
});
// Open Activities
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new Fragment()).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.
*/
}
Seccond.java
package com.example.helloworld;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class Seccond extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seccond);
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.seccond, 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.activity_seccond,
container, false);
return rootView;
}
}
}
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.helloworld.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/txt_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btn_Click"
android:layout_alignParentTop="true"
android:layout_marginTop="98dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/btn_Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="66dp"
android:text="Click"
tools:ignore="HardcodedText" />
"res/layout/activity_main.xml"
<Button
android:id="#+id/btn_image"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btn_Click"
android:layout_alignBottom="#+id/btn_Click"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/btn_Click"
android:text="Image"
tools:ignore="HardcodedText" />
<ImageView
android:id="#+id/img_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btn_image"
android:layout_centerVertical="true"
android:scaleType="center"
android:src="#drawable/abc_ab_solid_light_holo"
tools:ignore="ContentDescription" />
<Button
android:id="#+id/btn_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/btn_image"
android:text="New Activities"
tools:ignore="HardcodedText" />
</RelativeLayout>
Seccond_activity.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:background="#A8B007"
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.helloworld.Seccond$PlaceholderFragment" >
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
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="com.example.helloworld.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.helloworld.Seccond"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
No view found for id 0x7f05003c (com.example.helloworld:id/container) for fragment PlaceholderFragment
The error is saying it cannot find the view with an id of container for the fragment placeholder to go into.
setContentView(R.layout.activity_seccond);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
This part of the code is the main problem. In the add() for the getSupportFragmentManager, it is saying to create the fragment and put it in a view with the id container. But the layout specified in setContentView does not have a view with an id of container. So there needs to be a layout file with a View (like a frame) with an id of container, so that when the fragment layout loads, it can go into that view.
Try adding a file to layouts called activity_frame_seccond.xml with:
<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" />
Which is a frame with the id 'container'.
Change this line in Seccond.java:
setContentView(R.layout.activity_seccond);
for
setContentView(R.layout.activity_frame_seccond);
and see if that works.
With this code you are using the new file activity_frame_seccond.xml as the layout for the activity, and the first file activity_seccond.xml as the fragment that will put in the frame element (because it has the id container).
If this doesn't work let me know and I will have another look.
Check this line in your Fragment class :
View rootView = inflater.inflate(R.layout.activity_seccond,
container, false);
i think the Returned View is Null
Remove this line from your manifest
<activity
android:name="com.example.helloworld.Second"
android:label="#string/app_name" >
>
</activity>
and try
try in this way
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this,Seccond.class);
startActivity(intent);
}

Android start activity with button?

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

Categories