Application crashes upon opening

Go To StackoverFlow.com

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>
2012-04-04 00:54
by Erik
menuItem1 id is in your about layout?? mind posting your about layout? because as I posted you on my answer, if your id isnt in that layout then it will always throw you a nullpointer exceptio - Raykud 2012-04-04 01:50
See my edit :) I maybe just have forgot to change something. I hope so but I'm not getting any errors at all expect for that error I'm getting when I start the application - Erik 2012-04-04 01:51
can you post main.xml? That seems to be the xml file that is supposed to contain menuItem1 right - ByteMe 2012-04-04 02:30


2

Do you see the line that says Caused by: java.lang.NullPointerException in your log? Right below that is the line at weather.right.nowActivity.onCreate(nowActivity.java:37)

This means there is a NullPointerException being thrown at line 37 of your nowActivity. If you double click on that line, it will open the Activity and take you directly to where the error is being thrown. So, keep all that in mind.

One thing I notice is that you're using setContentView twice in your onCreate method. It looks like you'll want to use your about.xml in your About.class. Also, if you think the Exception that's being thrown is caused by your Menu, then you should post that code, as it's relevant to your OP.

It looks like line 37 has to do with starting your About.class. Make sure you have it tagged in your Manifest and that your Button is a part of the Layout you're using for your 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>

Whichever Activity you want to start first, or the one that will appear inside your app drawer, should include the Intent-Filter tags I posted, but other Activities don't need to include those specific tags, some may need an Intent-Filter though. Also, everything in your AndroidManifest should go inside ONE <manifest></manifest> tag and ONE <application></application>.

2012-04-04 01:04
by adneal
Thanks for the heads-up! :) I'll remember that next time I'm getting some errors. When I double clicked on the error message for row 37, it thrown me back to this line: b.setOnClickListener(new View.OnClickListener() {. I want to make a new window when the user is clicking on the "About" link in the menu that appears when you pressing the menu button on your phone. See my edit too se my nowActivity.java file and About.java file - Erik 2012-04-04 01:11
Try the things I mentioned in my answer. You need to remove the second time your call setContentView, make sure you reference your About.class in your Manifest, and make sure your Button, menuItem1 is a part of your main.xml - adneal 2012-04-04 01:18
menuItem1 is a part of my main.xml file and I have now removed setContentView(R.layout.about); from notActivity.java. I don't understand what you mean with "Manifest". Where is that - Erik 2012-04-04 01:31
I updated my answer again. Look for a file called AndroidManifest.xml in your project. It's automatically generated and will be towards to bottom. Inside the Application tags, add the line I posted. Every time you create a new Activity, you'll need to add it into your Manifest - adneal 2012-04-04 01:37
Aha! You meant that file :) See my edit in my first post too see how my AndroidManifest.xml file looks like after I tried to add the About.java file - Erik 2012-04-04 01:42
I updated my answer once more - adneal 2012-04-04 01:52
Thanks but I'm getting crash upon opening of the application :/ I have searched for any misspelling or something like that in the source codes and I haven't found anything wrong - according to m - Erik 2012-04-04 02:02
let us continue this discussion in chatadneal 2012-04-04 02:07
The solution for this error has now been fixed :) Thanks, aneal - Erik 2012-04-04 02:32
@adneal Thanks a lot, you are a life saver : - Lily 2013-11-24 06:23


0

try changing this line:

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

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

and if you are in a fragment use:

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

ok you are using View.onOnclickListerner.. try removing the word View. :) so it looks something like this:

b.setOnClickListener(new OnClickListener() {

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

            }
        });

and make sure you have the button id in your layout. Note: since the last setContentView you are using is: setContentView(R.layout.about);, the id of your button MUST be in that layout.

2012-04-04 01:06
by Raykud
Thanks but changing the line to Intent i = new Intent(getApplicationContext(), About.class); didn't make any changes to the sudden crash of my application : - Erik 2012-04-04 01:16
ok i just edited my answer so you can try it out - Raykud 2012-04-04 01:29
Thanks but that didn't fix the problem : - Erik 2012-04-04 01:36


0

Looking at your code here. You have 2 calls to setContentView which is pretty weird. I'm guessing that the about box is trying to be displayed but I'd only have call, assuming you really wanted just setContentView(R.layout.main);

Now also I'm going to guess your NullPointerException is because Button b = (Button) findViewById(R.id.menuItem1); is null. I think you created a menu by creating a menu XML file in the menu/ folder. What you're really looking for is a button in the layout/main.xml that has android:id="menuItem1". If that exists it'll find it, otherwise it'll return null. This code implies that it was created from a menu xml which if that's the case this is how you'd handle that.

// 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-04 01:24
by Jeremy Edwards
Thanks but see my previous topic :) http://stackoverflow.com/questions/10003123/pressing-the-go-back-button-closes-the-applicatio - Erik 2012-04-04 01:28
Ads