“不幸的是,点击登录按钮后app已经停止”

时间:2014-07-25 12:07:21

标签: java android eclipse onclicklistener buttonclick

我是这个机器人的新手。每当我点击登录按钮时,它都会显示“不幸的是,您的应用已停止”。 没有编译时错误.. 我正在上传我的MainActivity.java,LoginActivity.java和manifest.xml文件。 请告诉我这个问题是什么,或者我做错了什么?

// 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)

2 个答案:

答案 0 :(得分:1)

我猜你的onClick中有一个空指针用于你的登录活动。你应该能够通过查看你的logcat来解决这个问题,它应该告诉你造成这次崩溃的确切代码行。可能引用一个未初始化的对象/ null

修改

如上所述,您在LoginActivity的第50行上有一个空引用:

java.lang.NullPointerException
07-25 17:53:19.014: E/AndroidRuntime(1627):     at com.satty002.swag.LoginActivity$2.onClick(LoginActivity.java:50

你拼错了密码字段引用:

 mPassword = (EditText) findViewById(R.id.passwordFiled);

应该是

 mPassword = (EditText) findViewById(R.id.passwordField);

答案 1 :(得分:0)

LoginActivity中的第50行抛出NullPointerException, 第50行将在某处:

String username = mUsername.getText().toString();
String password = mPassword.getText().toString();

表示mUsernamemPasswordnull 检查是否将正确的布局绑定到活动,并且您使用的是正确的ID