java.lang.NullPointerException in MainAcitivity setOnClickListener - java

When I run my application, I keep getting a NullPointerException on line 56 as shown in the debug log below. I am relatively new to programming android applications, so I can't figure out what's going on here. Can someone please help me out with this?
My MainActivity.java:
package com.termite.pockettube;
import java.util.Locale;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements View.OnClickListener{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this); //this is line 56
}
public void countryOnClick() {
startActivity(new Intent("com.termite.pockettube.COUNTRY"));
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
countryOnClick();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position) {
case 0:
Fragment1 fragment1 = new Fragment1();
return fragment1;
case 1:
Fragment2 fragment2 = new Fragment2();
return fragment2;
case 2:
Fragment3 fragment3 = new Fragment3();
return fragment3;
case 3:
Fragment4 fragment4 = new Fragment4();
return fragment4;
case 4:
Fragment5 fragment5 = new Fragment5();
return fragment5;
}
return null;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
case 4:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
}
This is my debug log when attempting to run the application:
12-20 01:13:26.898: D/AndroidRuntime(6539): Shutting down VM
12-20 01:13:26.906: W/dalvikvm(6539): threadid=1: thread exiting with uncaught exception (group=0x40af21f8)
12-20 01:13:26.906: E/AndroidRuntime(6539): FATAL EXCEPTION: main
12-20 01:13:26.906: E/AndroidRuntime(6539): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.termite.pockettube/com.termite.pockettube.MainActivity}: java.lang.NullPointerException
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2035)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2060)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.app.ActivityThread.access$600(ActivityThread.java:127)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1181)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.os.Handler.dispatchMessage(Handler.java:99)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.os.Looper.loop(Looper.java:137)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.app.ActivityThread.main(ActivityThread.java:4558)
12-20 01:13:26.906: E/AndroidRuntime(6539): at java.lang.reflect.Method.invokeNative(Native Method)
12-20 01:13:26.906: E/AndroidRuntime(6539): at java.lang.reflect.Method.invoke(Method.java:511)
12-20 01:13:26.906: E/AndroidRuntime(6539): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-20 01:13:26.906: E/AndroidRuntime(6539): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-20 01:13:26.906: E/AndroidRuntime(6539): at dalvik.system.NativeStart.main(Native Method)
12-20 01:13:26.906: E/AndroidRuntime(6539): Caused by: java.lang.NullPointerException
12-20 01:13:26.906: E/AndroidRuntime(6539): at com.termite.pockettube.MainActivity.onCreate(MainActivity.java:56)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.app.Activity.performCreate(Activity.java:4635)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-20 01:13:26.906: E/AndroidRuntime(6539): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1999)
12-20 01:13:26.906: E/AndroidRuntime(6539): ... 11 more
Manifest xml code:
<uses-sdk
android:minSdkVersion="11"
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.termite.pockettube.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.termite.pockettube.CountryActivity"
android:label="#string/title_activity_country" >
<intent-filter>
<action android:name="com.termite.pockettube.COUNTRY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff"
>
</android.support.v4.view.PagerTabStrip>
</android.support.v4.view.ViewPager>
fragment1.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=".MainActivity$DummySectionFragment" >
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:text="#string/button" />
</RelativeLayout>

You need to button in activity_main.xml as you had added that button in fragment_1.xml this is is the cause of NPE.
add button in activity_main.xml will solve your problem
**activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/padding_Small"
android:shrinkColumns="*"
android:stretchColumns="*" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="ButtonText" />
</RelativeLayout>

button = (Button) findViewById(R.id.button);
button.setOnClickListener(this); //this is line 56
button is null. Initialization fails
Need button in activity_main.xml and also id should be button
findViewById looks for a view with the id in the current inflated layout. So if you have button in activity_main.xml then your initialization works else you get NPE`
There is no button in activity_main.xml. S0 button = (Button) findViewById(R.id.button); fails
Button is in fragment1. So you will need to inflate the layout fragment1.xml and then initialize the button in onCreateView not initialize button in Activity.

Thank you all for your input, and it all worked to end the NPE, yet it didn't perform the task I wanted it to complete. I added the button to ,y Fragment1.java file and then it worked.
package com.termite.pockettube;
import com.termite.pockettube.MainActivity.SectionsPagerAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class Fragment1 extends Fragment implements View.OnClickListener {
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragment1, container, false);
button = (Button)view.findViewById(R.id.button);
button.setOnClickListener(this);
return view;
}
/* #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}*/
public void countryOnClick() {
startActivity(new Intent("com.termite.pockettube.COUNTRY"));
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
countryOnClick();
break;
}
}
}

Try
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(buttonListener);
in onCreate
Then try
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
//Do Work Here
}
};

Check R.id.button, button is it in R.layout.activity_main layout..
Post your activity_main.xml layout.
Do below thing.
Add your Button in activity_main.xml or change code
button = (Button) mViewPager.findViewById(R.id.button);
button.setOnClickListener(this);

Your error is in the getItem(poistion) method. even your adapter size is 5, it give you positions grater than 5. at such moments you return null from there.
you can check this by adding a Log statement to print the position value at the beginning of the getItem method

Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { Toast.makeText(MainActivity.this,"RunAPP",Toast.LENGTH_LONG).show();
}
});

Related

MediaPlayer onClick crashes when start() is called

I have an app that simply displays 1 picture, implemented through Picasso. The onClick works fine if I replace the contents with a simple toast, so it must be the MediaPlayer calls. I don't know why it keeps crashing though.
package com.example.andrew.crossfade;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends ActionBarActivity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setClickable(true);
Picasso.with(this)
.load("http://i.imgur.com/vpeH7S2.jpg")
.into(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.later);
mp.start();
}
});
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
The 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=".MainActivity" tools:ignore="MergeRootFrame" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
/>
And finally, the log cat:
10-29 12:12:07.343 18409-18409/com.example.andrew.crossfade W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41f38da0)
10-29 12:12:07.343 18409-18409/com.example.andrew.crossfade E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.andrew.crossfade, PID: 18409
java.lang.NullPointerException
at com.example.andrew.crossfade.MainActivity$1.onClick(MainActivity.java:47)
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 dalvik.system.NativeStart.main(Native Method)
something is null in your code
java.lang.NullPointerException
call mp.prepare() before start
and make sure R.raw.later is playable audio for media player

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

Unfortunately MyFirstApp has stopped

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 just written my first android app, and after 3 hours it still doesn't work

I have just started writing my first piece of code in an android app, however when I run it with the following section uncommented it crashes (anything else I tell you would be a useless guess):
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
With the following error log:
04-07 17:45:30.897: E/AndroidRuntime(15210): FATAL EXCEPTION: main
04-07 17:45:30.897: E/AndroidRuntime(15210): Process: com.ollieapps.helloworld, PID: 15210
04-07 17:45:30.897: E/AndroidRuntime(15210): java.lang.IllegalStateException: Could not execute method of the activity
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3823)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View.performClick(View.java:4438)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$PerformClick.run(View.java:18422)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.handleCallback(Handler.java:733)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.dispatchMessage(Handler.java:95)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Looper.loop(Looper.java:136)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.reflect.InvocationTargetException
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3818)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 9 more
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.ollieapps.helloworld.MainActivity.onButton1Click(MainActivity.java:59)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 11 more
I'm sorry if I have included to much or too little, this is my first question, also I have already searched for 3 hours.
Full Code:
package com.ollieapps.helloworld;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView; CheckBox pepBox, cheeseBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
xml:
fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.ollieapps.helloworld.MainActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pepperoni" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ExtraCheese" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButton1Click"
android:text="Show" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Plain" />
</LinearLayout>
</RelativeLayout>
Main:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ollieapps.helloworld.MainActivity"
tools:ignore="MergeRootFrame" />
It seems you built your views inside fragment_main.xml and not activity_main.xml.
When you first create a new android project, you have these files which are automatically created and opened:
Then, when you begin, you add views (e.g: a TextView) inside fragment_main.xml file. Finally, you tried to do a basically event with this view inside your Activity, something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Using layout activity_main.xml
// You try to set a simple text on the view (TextView) previously added
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("Simple Text"); // And you get an error here!
/*
* You do an fragment transaction to add PlaceholderFragment Fragment
* on screen - this below snippnet is automatically created.
*/
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
You cannot run your app or sometimes you have only a white screen, because the views that you tried to call/display are into the wrong layout..
Solution: Move all your stuff inside onCreateView method into the Fragment class.
As DoctororDrive said in his comment
Call views and do something in the related fragment and not the parent activity.
For example, in your case, these following lines:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
might be inside your fragment because you created it in fragment_main.xml layout. Then:
// start fragment
public static class PlaceholderFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Use the layout which is displayed it's fragment_main.xml
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Find your views here!
// Don't forget to findViewById attached to the inflated view "rootView.findView..."
pepBox = (CheckBox) rootView.findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) rootView.findViewById(R.id.checkBox2);
textView = (TextView) rootView.findViewById(R.id.textView1);
/*
* Do something here: click listener, set a text, check a box..
*/
return rootView;
}
/*
* Perform other methods still inside the fragment
*/
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
}
// end fragment
if (pepBox.isChecked()) {
This line of code is failing with a NullPointerException because pepBox was declared but it's not being initialized as it should (and is therefore null at this point in the code).
Here is its declaration line:
TextView textView; CheckBox pepBox, cheeseBox;
And here is its initialization:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
The problem is that (a) this line is not be called, or (b) findViewById(R.id.checkBox1) is returning null.
If findViewByID is returning null then you probably want to refer to this question, which addresses exactly this issue. Its "related questions", down the right-hand side, should also be helpful.

Categories