0

这是一个基于位置的应用程序。MainActivity.java 是第一个执行的文件,但应用程序一打开就会强制关闭。包括 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>

日志猫

    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

4 回答 4

1

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

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

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

于 2012-08-01T12:44:32.890 回答
0

我正在研究与此非常相似的东西。当我只使用 onLocationChanged 时,我的代码运行良好。当我使用 onLocationChanged 和 addProximityAlert 时,问题就开始了。

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

我对此不太确定,但我可能还想提出这个问题,即 onLocationChanged 与 addProximityAlert 一起调用是否存在问题?或者也许我们需要做一些额外的事情才能让他们两个一起工作?

于 2012-08-18T15:26:51.197 回答
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(). 然后你传递pendintaddProximityAlert()它肯定是null。您可能想做类似的事情:

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

此外,您调用getLatitude()getLongitude()变量loc,但该变量也从未设置为任何东西,所以它肯定是null

解决这些问题,看看你能走多远。

于 2012-08-01T16:38:51.263 回答
0

你不能调用findViewById()你的btn.setOnClickListener(). 您正在为您的班级调用findViewById()匿名内部OnClickListener班级。所以 Android 会findViewById()在你的OnClickListener.

只需Views在您的onCreate().

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

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

并打电话给context.findViewById()btn.setOnClickListener()

于 2012-08-01T12:49:22.333 回答