0

When I'm testing my new update to my application for Android, the application crashes upon start when it trying to start the "optionsmenu" (what I know). Here's the code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
         Toast.makeText(this, "GPS'n är aktiverad på din mobilenhet", Toast.LENGTH_SHORT).show();
    }else{
        showGPSDisabledAlertToUser();
    }

    setContentView(R.layout.about);
    Button b = (Button) findViewById(R.id.menuItem1);
    b.setOnClickListener(new View.OnClickListener() {
       public void onClick(View arg0) {
       Intent i = new Intent(nowActivity.this, About.class);
       startActivity(i);
       } 
    });
}

And the LogCat:

04-04 00:50:27.324: D/LocationManager(870): Constructor: service = android.location.ILocationManager$Stub$Proxy@44e95640
04-04 00:50:27.374: D/AndroidRuntime(870): Shutting down VM
04-04 00:50:27.374: W/dalvikvm(870): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-04 00:50:27.374: E/AndroidRuntime(870): Uncaught handler: thread main exiting due to uncaught exception
04-04 00:50:27.384: E/AndroidRuntime(870): java.lang.RuntimeException: Unable to start activity ComponentInfo{weather.right.now/weather.right.nowActivity}: java.lang.NullPointerException
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.os.Looper.loop(Looper.java:123)
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.app.ActivityThread.main(ActivityThread.java:4363)
04-04 00:50:27.384: E/AndroidRuntime(870):  at java.lang.reflect.Method.invokeNative(Native Method)
04-04 00:50:27.384: E/AndroidRuntime(870):  at java.lang.reflect.Method.invoke(Method.java:521)
04-04 00:50:27.384: E/AndroidRuntime(870):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-04 00:50:27.384: E/AndroidRuntime(870):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-04 00:50:27.384: E/AndroidRuntime(870):  at dalvik.system.NativeStart.main(Native Method)
04-04 00:50:27.384: E/AndroidRuntime(870): Caused by: java.lang.NullPointerException
04-04 00:50:27.384: E/AndroidRuntime(870):  at weather.right.nowActivity.onCreate(nowActivity.java:37)
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-04 00:50:27.384: E/AndroidRuntime(870):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-04 00:50:27.384: E/AndroidRuntime(870):  ... 11 more
04-04 00:50:27.404: I/dalvikvm(870): threadid=7: reacting to signal 3
04-04 00:50:27.424: E/dalvikvm(870): Unable to open stack trace file '/data/anr/traces.txt': Permission denied

I'm currently learning to build a proper Android application so I don't know what's wrong here. Do you know what's wrong?

Thanks in advance!

EDIT: About.java

package weather.right;

import weather.right.now.R;
import android.app.Activity;
import android.os.Bundle;

public class About extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about);
    }

}

EDIT: nowActivity.java

package weather.right;

// import java.util.Calendar;

import weather.right.now.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
// import android.view.Menu;
// import android.view.MenuInflater;
// import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class nowActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
             Toast.makeText(this, "GPS'n är aktiverad på din mobilenhet", Toast.LENGTH_SHORT).show();
        }else{
            showGPSDisabledAlertToUser();
        }

        setContentView(R.layout.about);
        Button b = (Button) findViewById(R.id.menuItem1);
        b.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
           Intent i = new Intent(nowActivity.this, About.class);
           startActivity(i);
           } 
        });
    }

    @Override
    public void onBackPressed() {
        System.exit(0);
        return;
    }
 /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Calendar c = Calendar.getInstance();
        // int year = c.get(Calendar.YEAR);

        // Handle item selection
        switch (item.getItemId())
        {
        case R.id.menuItem1:
            // Toast.makeText(nowActivity.this, "Copyright " + year + " Erik Edgren", 3000).show();
            setContentView(R.layout.about);
            return true;
        case R.id.menuItem2:
            System.exit(0);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    */



    public void goToSo(View view) {
        goToUrl("http://erik-edgren.nu/weather");
        System.exit(0);
    }

    private void goToUrl(String url) {
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        startActivity(launchBrowser);
        System.exit(0);
    }



    private void showGPSDisabledAlertToUser(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setMessage("GPS-mottagaren är inte aktiverad på din mobil. För att tjänsten ska kunna hitta dig, måste den vara aktiverad.")
         .setCancelable(false)
         .setPositiveButton("Gå till inställningarna",
              new DialogInterface.OnClickListener(){
              public void onClick(DialogInterface dialog, int id){
                      Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                      startActivity(callGPSSettingIntent);
                      System.exit(0);
              }
         });
         alertDialogBuilder.setNegativeButton("Stäng",
              new DialogInterface.OnClickListener(){
              public void onClick(DialogInterface dialog, int id){
                   dialog.cancel();
                   System.exit(0);
              }
         });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
    }
}

EDIT: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="weather.right.now"
    android:versionCode="1"
    android:versionName="1.1" >

    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:icon="@drawable/sun_icon"
        android:label="@string/app_name" >
        <activity
            android:name="weather.right.nowActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <application
        android:icon="@drawable/sun_icon"
        android:label="@string/app_name" >
        <activity
            android:name="weather.right.About"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

EDIT: about.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="252dp"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:text="@string/about" />

</LinearLayout>
4

3 回答 3

2

您看到Caused by: java.lang.NullPointerException日志中显示的那一行了吗?正下方是那条线at weather.right.nowActivity.onCreate(nowActivity.java:37)

这意味着您NullPointerException的. 如果您双击该行,它将打开并直接将您带到引发错误的位置。所以,请记住所有这些。37nowActivityActivity

我注意到的一件事是您在方法中使用setContentView了两次onCreate。看起来你会想about.xml在你的About.class. 此外,如果您认为Exception抛出的问题是由您的. 引起的Menu,那么您应该发布该代码,因为它与您的 OP 相关。

看起来 line37与启动你的About.class. 确保您已将其标记在您的文件中Manifest,并且您的Button文件是Layout您用于nowActivity.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="weather.right.now"
android:versionCode="1"
android:versionName="1.1" >

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:icon="@drawable/sun_icon"
    android:label="@string/app_name" >
    <activity
        android:name="weather.right.nowActivity"
        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="weather.right.About"
        android:label="@string/app_name" />
</application>

</manifest>

无论Activity您想先开始,还是将出现在应用程序抽屉中的那个,都应该包括Intent-Filter我发布的标签,但其他Activities不需要包括那些特定的标签,有些可能需要Intent-Filter。此外,您的所有内容都AndroidManifest应该放在ONE <manifest></manifest>标签和ONE <application></application>中。

于 2012-04-04T01:04:59.060 回答
0

在这里查看您的代码。你有 2 次调用 setContentView 这很奇怪。我猜关于框正在尝试显示,但我只会打电话,假设你真的想要setContentView(R.layout.main);

现在我也猜你NullPointerException是因为Button b = (Button) findViewById(R.id.menuItem1);是空的。我认为您通过在 menu/ 文件夹中创建菜单 XML 文件来创建菜单。您真正要寻找的是layout/main.xmlthat has中的一个按钮android:id="menuItem1"。如果存在,它将找到它,否则它将返回 null。这段代码暗示它是从一个菜单 xml 创建的,如果是这种情况,这就是你处理它的方式。

// Load the menu into the activity. Add this code to the activity class.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.example_menu, menu);
    return true;
}

// Handler for menu selections.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {

  case R.id.menuItem1: {
    // do work.
  } break;
  default:
    return super.onOptionsItemSelected(item);
  }

  return true;
}
于 2012-04-04T01:24:25.197 回答
0

尝试更改此行:

Intent i = new Intent(nowActivity.this, About.class);

为了Intent i = new Intent(getApplicationContext(), About.class);

如果您在片段中,请使用:

Intent i = new Intent(getActivity().getApplicationContext(), About.class);

好的,您正在使用 View.onOnclickListerner.. 尝试删除单词 View。:) 所以它看起来像这样:

b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });

并确保您的布局中有按钮 ID。注意:由于setContentView您使用的最后一个是:setContentView(R.layout.about);,因此您的按钮的 id必须在该布局中。

于 2012-04-04T01:06:15.800 回答