应用FC启动时自己。附加了LogCat和其他文件

时间:2012-08-01 12:35:21

标签: android geolocation nullpointerexception android-manifest android-activity

这是一个基于位置的应用程序.MainActivity.java是第一个被执行的文件,但应用程序Force一打开就关闭。包含LogCat。
请帮忙。希望能在这里得到答案 MainActivity.java

package com.location.sensor;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
     LocationListener locationlistener;
     Location loc;
     PendingIntent pendint;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager lm=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
     locationlistener=new MyLocationListener();
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationlistener);
            Button btn=(Button) findViewById(R.id.btn_OK);
            //Animation anim= AnimationUtils.loadAnimation(getApplicationContext(), R.anim.jump);
            //btn.startAnimation(anim);
            TextView n= (TextView)findViewById(R.id.tv);
                btn.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Animation anim= AnimationUtils.loadAnimation(getApplicationContext(), R.anim.jump);
                        anim.setDuration(3000);
                        //v.startAnimation(anim);
                        TextView n= (TextView)findViewById(R.id.tv);
                        EditText txt=(EditText) findViewById(R.id.txt_username);
                        //Animation anim= AnimationUtils.loadAnimation(getApplicationContext(), R.anim.jump);
                        n.startAnimation(anim);
                        String s=txt.getText().toString();
                        n.setText(s);
                        n.setBackgroundResource(R.drawable.icn);                    
                    }
                });

                EditText txt=(EditText) findViewById(R.id.txt_username);
                //Animation anim= AnimationUtils.loadAnimation(getApplicationContext(), R.anim.jump);
                String s=txt.getText().toString();
                    //LocationManager lm=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    //LocationListener locationlistener=new MyLocationListener();
                    //lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 10, locationlistener);
                    Intent intent=new Intent(this,NotificationClass.class);
                    Bundle extras=new Bundle();
                    extras.putString("alarm", s);
                    intent.putExtras(extras);
                    PendingIntent.getActivity(this, 0, intent, 0);
                    lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 8, -1, pendint);


    }

 private class MyLocationListener implements LocationListener{

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
                loc.set(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            Toast.makeText(getBaseContext(), "Please enable GPS in Settings!", Toast.LENGTH_LONG).show();
            Message msg = handler.obtainMessage();
             msg.arg1 = 1;
             handler.sendMessage(msg);
        }



        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub


        }

 }
private final Handler handler = new Handler() {
         @Override
        public void handleMessage(Message msg) {
              if(msg.arg1 == 1){
                   if (!isFinishing()) { // Without this in certain cases application will show ANR
                        AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
                        builder.setMessage("Your GPS is disabled! Would you like to enable it?").setCancelable(false).setPositiveButton("Enable GPS", new DialogInterface.OnClickListener() {
                             @Override
                            public void onClick(DialogInterface dialog, int id) {
                                  Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                  startActivity(gpsOptionsIntent);
                              }
                         });
                         builder.setNegativeButton("Do nothing", new DialogInterface.OnClickListener() {
                              @Override
                            public void onClick(DialogInterface dialog, int id) {
                                   dialog.cancel();
                              }
                         });
                         AlertDialog alert = builder.create();
                         alert.show();
                   }
               }

           }
    };
 }

NotificationClass.java

package com.location.sensor;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class NotificationClass extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        TextView txtview=new TextView(this);
        txtview.setText("Hey,Im Sorry");
        setContentView(txtview);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        String data=getIntent().getExtras().getString("alarm").toString();
        Bundle enter= getIntent().getExtras();
        if(enter.getBoolean("KEY_PROXIMITY_ENTERING"))
        {
            setContentView(R.layout.notif);
        TextView tv=(TextView) findViewById(R.id.txt_pendint);
        Button btn=(Button) findViewById(R.id.btn_cancel);
        tv.setText(data);
        btn.setOnClickListener(new View.OnClickListener() {

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

            }
        });
        }
    }
@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case 0:

        return new AlertDialog.Builder(this)
                .setIcon(R.drawable.excl_mark)
                .setTitle("Do you want to Cancel?")
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        finish();
                    }
                })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        Toast.makeText(getBaseContext(), "Cancel Clicked!", Toast.LENGTH_LONG).show();
                    }
                })
                .create();
    }
    return null;

}
}

AndroidManifest.xml

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

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

    <application
        android:icon="@drawable/gps1"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity 
            android:name=".NotificationClass"
            android:label="YOU ARE IN PROXIMITY AREA!!!"
            android:exported="false">
            <intent-filter>
                <action android:name="com.locationsensor.notif"/>
                <category android:name="android.intent.category.DEFAULT"/> 
            </intent-filter>
        </activity>
    </application>

</manifest>

logcat的

    08-01 17:51:17.546: D/AndroidRuntime(483): Shutting down VM
08-01 17:51:17.546: W/dalvikvm(483): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-01 17:51:17.566: E/AndroidRuntime(483): FATAL EXCEPTION: main
08-01 17:51:17.566: E/AndroidRuntime(483): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.location.sensor/com.location.sensor.MainActivity}: java.lang.NullPointerException
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.os.Looper.loop(Looper.java:123)
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 17:51:17.566: E/AndroidRuntime(483):  at java.lang.reflect.Method.invokeNative(Native Method)
08-01 17:51:17.566: E/AndroidRuntime(483):  at java.lang.reflect.Method.invoke(Method.java:507)
08-01 17:51:17.566: E/AndroidRuntime(483):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 17:51:17.566: E/AndroidRuntime(483):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 17:51:17.566: E/AndroidRuntime(483):  at dalvik.system.NativeStart.main(Native Method)
08-01 17:51:17.566: E/AndroidRuntime(483): Caused by: java.lang.NullPointerException
08-01 17:51:17.566: E/AndroidRuntime(483):  at com.location.sensor.MainActivity.onCreate(MainActivity.java:68)
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-01 17:51:17.566: E/AndroidRuntime(483):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-01 17:51:17.566: E/AndroidRuntime(483):  ... 11 more
08-01 17:56:17.656: I/Process(483): Sending signal. PID: 483 SIG: 9

4 个答案:

答案 0 :(得分:1)

看起来你的'loc'变量没有被实例化,这就是为什么你得到一个'空指针'异常(这将导致你的应用程序的FC)。

堆栈跟踪中的这两行指向我:

引起:java.lang.NullPointerException 08-01 17:51:17.566:E / AndroidRuntime(483):at com.location.sensor.MainActivity.onCreate(MainActivity.java:68)

答案 1 :(得分:0)

您无法在findViewById()中致电btn.setOnClickListener()。您正在调用findViewById()类的匿名内部类中的OnClickListener。因此,Android会在findViewById()

中寻找方法OnClickListener

只需初始化Views中的onCreate()

或者你可以创建一个名为private Context context的变量,然后在你的onCreate()中创建this

protected void onCreate(Bundle savedInstanceState) {
     context = this;
     //... your code
}

并在context.findViewById()

中致电btn.setOnClickListener()

答案 2 :(得分:0)

MainActivity.onCreate()结尾处有一些问题:

intent.putExtras(extras);
PendingIntent.getActivity(this, 0, intent, 0);
lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 8, -1, pendint);

我假设您要将PendingIntent传递给addProximityAlert()。但是,您不会对从PendingIntent.getActivity()返回的PendingIntent执行任何操作。然后,您将pendint传递给addProximityAlert(),肯定是 null 。你可能想做类似的事情:

pendint = PendingIntent.getActivity(this, 0, intent, 0);
lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 8, -1, pendint);

此外,您在变量getLatitude()上调用getLongitude()loc,但该变量也从未设置为任何内容,因此肯定是 null

修复这些事情,看看你能走多远。

答案 3 :(得分:0)

我正在做一些与此非常相似的事情。当我只使用onLocationChanged时,我的代码工作正常。当我使用onLocationChanged和addProximityAlert时,问题就出现了。

添加Proximity Alert后,onLocationChanged从未被调用,并且onLocationChanged方法中的初始化对象开始给我一个空指针。

我对此不太确定,但我也想在桌面上提出这样的问题:onLocationChanged是否与addProximityAlert一起被调用?或者也许我们需要做一些额外的工作来让两者一起工作?