无法通过某些函数调用恢复活动

时间:2013-12-11 01:21:55

标签: java android nfc onresume

我遇到onResume()的问题,我的应用程序在对intent处理程序的函数调用期间崩溃。当我的app优先使用enableForegroundDispath()方法读取NFC标签时,它也会崩溃。我已将所有NFC意图过滤器和权限添加到清单中。如果我在onResume()中注释掉最后两个方法,应用程序运行完美......不确定是什么问题,但是真的很感激任何帮助! MainActivity如下。

package com.example.final_project;

import java.util.Locale;

import android.app.Activity;
import android.app.ActivityOptions;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
    Button B1,B2,foodButton;
    static EditText Text1;
    static Context context;
    String Text;
    String Preference;
    String NearMe= "+near+me";
    Double Latitude, Longitude;
    ImageView TV;
    Button FavoriteButton;
    View FavoriteView;
    TextToSpeech tts;
    Intent Gpsintent;
    ProgressBar progress;

    //NFC Stuff
    private static final String TAG = "NFCTag";
    private static final String APP_MIME_TYPE = "application/edu.villanova.ece5480.nfctag";
    private static final String APP_LAUNCH_MIME_TYPE = APP_MIME_TYPE + ".launch";

    NfcAdapter nfc = null;
    Tag tag = null;

    PendingIntent intentPending = null;
    IntentFilter[] readFilters = null;
    IntentFilter[] writeFilters = null;


    public static String MY_PREFS = "edu.villanova.ece5480.my_prefs";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context=MainActivity.this;

        tts = new TextToSpeech(this, this);
        Text1=(EditText)findViewById(R.id.editText1);
        TV=(ImageView)findViewById(R.id.imageView2);
        progress = (ProgressBar)findViewById(R.id.progressBar1);


        //NFC

        // get an instance of the device NfcAdapter
        nfc = NfcAdapter.getDefaultAdapter(this);

        if (nfc == null) {
            // let user know that their device does not support NFC then exit
            Toast.makeText(this, "Device does not support NFC.", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        // handle foreground NFC scanning in this activity by creating a pending intent 
        //      with FLAG_ACTIVITY_SINGLE_TOP flag so each new scan is not added to the Back Stack
        intentPending = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // intents for reading NDEF tags action
        IntentFilter appRead = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try { appRead.addDataType(APP_MIME_TYPE); }
        catch (MalformedMimeTypeException e) { Log.e(TAG, "MalforedMimeTypeException:" + e.toString());  }

        IntentFilter launchRead = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try { launchRead.addDataType(APP_LAUNCH_MIME_TYPE); }
        catch (MalformedMimeTypeException e) { Log.e(TAG, "MalforedMimeTypeException:" + e.toString());  }

        readFilters = new IntentFilter[] { appRead, launchRead };

        // intent for writing NDEF tag action - read any tag (could check for formatable)
        IntentFilter appWrite = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        writeFilters = new IntentFilter[] { appWrite };
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        return true;
    }

    @Override
    public void onInit(int status) {

        if (status == TextToSpeech.SUCCESS) {
            int result = tts.setLanguage(Locale.US);    
        }

        else {
            Log.e("TTS", "Initilization Failed!");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!nfc.isEnabled()){
            // NFC is not enabled, launch wireless settings intent for user to enable
            startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
            Toast.makeText(this, "Enable NFC", Toast.LENGTH_LONG).show();

        }

        // tag received when app is not running and/or foreground dispatch is not enabled
        handleIntent(this.getIntent());
        /*
        // enable priority for activity to detect scanned tags
        nfc.enableForegroundDispatch(this, intentPending, readFilters, null); */

    } 


    @Override
    protected void onPause() {
        super.onPause();

        // disable priority for activity to detect scanned tags
        nfc.disableForegroundDispatch(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.d(TAG, "onNewIntent() triggered");
        // tag received when app set launchMode to “singleTask� and/or foreground dispatch is enabled
        handleIntent(intent);
    }


    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }


    public void GpsClick(View view) throws InterruptedException{

        progress.setVisibility(0);

        LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        if(!mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }

        LocationListener mlocListener = new MyLocationListener();
        mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 10000, mlocListener);

    }

    public void FindPartyClick(View view){


        Preference=Text1.getText().toString();
        SharedPreferences prefs = getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(Preference, Preference);
        editor.commit();



        Intent intent = new Intent(MainActivity.this, SearchClass.class); 
        String Address=Text1.getText().toString().replace(' ', '+');
        if((Address.length()!=5 && Address.matches("\\d+")) || Address.length()<2) 
            Toast.makeText( getApplicationContext(),"Zip Code must be 5 digits" , Toast.LENGTH_SHORT ).show();
        else{

            String text = MainActivity.Text1.getText().toString();
            int i;
            for(i=0;i<10;i++){
                text=text.replace(String.valueOf(i),String.valueOf(i) + ' ');
            }
            //tts.speak(text,TextToSpeech.QUEUE_FLUSH,null);
            tts.speak("What's The Move",TextToSpeech.QUEUE_FLUSH,null);

        intent.putExtra("message", Address);
        Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation,R.anim.animation2).toBundle();
        startActivity(intent, bndlanimation); 
        }               
}


/* Class My Location Listener */

    public class MyLocationListener implements LocationListener{

    @Override

        public void onLocationChanged(Location loc){
            Latitude=loc.getLatitude();
            Longitude=loc.getLongitude();
            //setGPS(loc.getLatitude(),loc.getLongitude());
            Intent Gpsintent = new Intent(MainActivity.this, SearchClass.class); 
            Gpsintent.putExtra("latitude", Latitude);
            Gpsintent.putExtra("longitude",Longitude);
            Gpsintent.putExtra("message", NearMe);
            //tts.speak("Finding Current Location",TextToSpeech.QUEUE_FLUSH,null);
            progress.setVisibility(2);
            tts.speak("What's The Move",TextToSpeech.QUEUE_FLUSH,null);
            Bundle bndlanimation = ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation,R.anim.animation2).toBundle();
            startActivity(Gpsintent, bndlanimation);
        }

        public String setGPS(double Lat, double Long){
            Latitude=Lat;
            Longitude=Long;
            Text = "My current location is: " + "Latitude = " + Lat + "Longitude = " + Long;
            return Text;
        }

        @Override
        public void onProviderDisabled(String provider)
        {
        Toast.makeText( getApplicationContext(),"Gps Disabled" , Toast.LENGTH_SHORT ).show();

        }

        @Override
        public void onProviderEnabled(String provider)
        {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }


    }/* End of Class MyLocationListener */

    protected void handleIntent(Intent intent){
        String action = intent.getAction();

        if(action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)){
            intent = new Intent(MainActivity.this, NFCClass.class);
            startActivity(intent);
        }

    }


}/* End of Main Activity */

logcat的

12-10 20:52:07.871: E/AndroidRuntime(11113): FATAL EXCEPTION: main
12-10 20:52:07.871: E/AndroidRuntime(11113): java.lang.RuntimeException: Unable to       resume activity {com.example.final_project/com.example.final_project.MainActivity}: java.lang.NullPointerException
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2639)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2667)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2140)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.ActivityThread.access$700(ActivityThread.java:143)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.os.Looper.loop(Looper.java:137)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.ActivityThread.main(ActivityThread.java:4950)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at java.lang.reflect.Method.invoke(Method.java:511)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at dalvik.system.NativeStart.main(Native Method)
12-10 20:52:07.871: E/AndroidRuntime(11113): Caused by: java.lang.NullPointerException
12-10 20:52:07.871: E/AndroidRuntime(11113):    at com.example.final_project.MainActivity.handleIntent(MainActivity.java:152)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at com.example.final_project.MainActivity.onResume(MainActivity.java:143)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1199)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.Activity.performResume(Activity.java:5253)
12-10 20:52:07.871: E/AndroidRuntime(11113):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2629)
12-10 20:52:07.871: E/AndroidRuntime(11113):    ... 12 more

0 个答案:

没有答案