无法启动活动ComponentInfo NullPointer

时间:2016-04-01 23:21:22

标签: android

主要活动

package com.project.mobileshoppingassistant.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;

import com.project.mobileshoppingassistant.Environment.Constants;
import com.project.mobileshoppingassistant.MapViewActivity;
import com.project.mobileshoppingassistant.R;
import com.project.mobileshoppingassistant.model.SharedPrefs;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        ImageButton bScanProduct = (ImageButton) findViewById(R.id.bScanProduct);
        ImageButton blocateuser = (ImageButton) findViewById(R.id.bLocateUser);
        ImageButton bAllProducts = (ImageButton) findViewById(R.id.bAllProducts);
        ImageButton bSaleProducts = (ImageButton) findViewById(R.id.bSaleProducts);
        ImageButton bYourCart = (ImageButton) findViewById(R.id.bYourCart);
        ImageButton bYourList = (ImageButton) findViewById(R.id.bYourList);
        ImageButton bLogout = (ImageButton) findViewById(R.id.bLogout);
        ImageButton bTransactionHistory = (ImageButton) findViewById(R.id.bTransactionHistory);

        bScanProduct.setOnClickListener(this);
        bAllProducts.setOnClickListener(this);
        blocateuser.setOnClickListener(this);
        bSaleProducts.setOnClickListener(this);
        bYourCart.setOnClickListener(this);
        bYourList.setOnClickListener(this);
        bLogout.setOnClickListener(this);
        bTransactionHistory.setOnClickListener(this);

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Intent i = new Intent(this, PrefsActivity.class);
            startActivity(i);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bAllProducts:
                Intent i1 = new Intent(this, ProductCategoryActivity.class);
                startActivity(i1);
                break;

            case R.id.bLocateUser:
                Intent i8 = new Intent(this, MapViewActivity.class);
                startActivity(i8);
                break;

            case R.id.bSaleProducts:
                Intent i2 = new Intent(this, SaleProductsActivity.class);
                startActivity(i2);
                break;

            case R.id.bScanProduct:
                Intent i3 = new Intent(this, ProductScanActivity.class);
                startActivity(i3);
                break;

            case R.id.bYourCart:
                Intent i4 = new Intent(this, CartActivity.class);
                startActivity(i4);
                break;

            case R.id.bYourList:
                Intent i5 = new Intent(this, YourListActivity.class);
                startActivity(i5);
                break;

            case R.id.bTransactionHistory:
                Intent i6 = new Intent(this, TransactionHistoryActivity.class);
                startActivity(i6);
                break;

            case R.id.bLogout:
                SharedPrefs.setUserEmailId(getApplicationContext(), null);
                Intent i7 = new Intent(this, LoginActivity.class);
                startActivity(i7);
                finish();
                break;
        }
    }
}

MapViewActivity

package com.project.mobileshoppingassistant;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PointF;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;

public class MapViewActivity extends MapActivity {
    public final static String EXTRA_MESSAGE_FLOOR = "com.inte.indoorpositiontracker.FLOOR";

    private static final int MENU_ITEM_EDIT_MAP = 21;

    public static final int SCAN_DELAY = 1000; // delay for the first scan (milliseconds)
    public static final int SCAN_INTERVAL = 1000; // interval between scans (milliseconds)
    public static final int MAX_SCAN_THREADS = 2; // max amount of simultaneus scans

    private int mScanThreadCount = 0;

    //keys to save fingerPrint to sharedPereferences--start
    public static final String KEY_ID="fingerprint_id";
    public static final String KEY_MAP="fingerprint_map";
    public static final String KEY_POSITON_X="fingerprintX";
    public static final String KEY_POSITON_Y="fingerprintY";
    //end

    public static final String KEY_FINGERPRINT_MADE="hasFIngerPrintBeenMade";//used to check if
    // an average point has been calculated

    // UI pointer to visualize user where he is on the map
    private WifiPointView mLocationPointer;

    // handler for callbacks to the UI thread
    private static Handler sUpdateHandler = new Handler();

    // runnable to refresh map (called by the handler)
    private Runnable mRefreshMap = new Runnable() {
        public void run() {
            refreshMap();
        }
    };

    private boolean mPaused = false; // used to detect if the application is on map edit mode

    private HashMap<String, Integer> mMeasurements; // used to calculate weighted averages of signal strengths



    /** INSTANCE METHODS*/

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMeasurements = new HashMap<String, Integer>();

        mLocationPointer = mMap.createNewWifiPointOnMap(new PointF(-1000, -1000));
        mLocationPointer.activate();

        if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(KEY_FINGERPRINT_MADE,false))
        {
            mLocationPointer.setFingerprint(getSavedFingerprint());
        }

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                if(mPaused == false) { // start scan only when this activity is active
                    mWifi.startScan();
                }
            }

        }, SCAN_DELAY, SCAN_INTERVAL);
    }


    @Override
    public void onReceiveWifiScanResults(final List<ScanResult> results) {
        IndoorPositionTracker application = (IndoorPositionTracker) getApplication();
        final ArrayList<Fingerprint> fingerprints = application.getFingerprintData(mSelectedMap);

        // calculating the location might take some time in case there are a lot of fingerprints (>10000),
        // so it's reasonable to limit scan thread count to make sure there are not too many of these threads
        // going on at the same time
        if(results.size() > 0 && fingerprints.size() > 0 && mScanThreadCount <= MAX_SCAN_THREADS) {
            Thread t = new Thread() {
                public void run() {
                    mScanThreadCount++;

                    HashMap<String, Integer> measurements = new HashMap<String, Integer>();
                    for (ScanResult result : results) {
                        measurements.put(result.BSSID, result.level);
                    }

                    TreeSet<String> keys = new TreeSet<String>();
                    keys.addAll(mMeasurements.keySet());
                    keys.addAll(measurements.keySet());

                    // calculate access point signal strengths with weighted averages
                    // (adjust to suddent big changes in received signal strengths)
                    for (String key : keys) {
                        Integer value = measurements.get(key);
                        Integer oldValue = mMeasurements.get(key);
                        if(oldValue == null) {
                            mMeasurements.put(key, value);
                        } else if(value == null) {
                            mMeasurements.remove(key);
                        } else {
                            value = (int) (oldValue * 0.4f + value * 0.6f);
                            mMeasurements.put(key, value);
                        }
                    }


                    Fingerprint f = new Fingerprint(mMeasurements);

                    // find fingerprint closest to our location (one with the smallest euclidean distance to us)
                    Fingerprint closestMatch = f.getClosestMatch(fingerprints);

                    runOnUiThread(new Runnable() {
                        public void run() {
                            PreferenceManager.getDefaultSharedPreferences(MapViewActivity.this).edit()
                                    .putBoolean(KEY_FINGERPRINT_MADE,true).commit();
                        }
                    });
                    mLocationPointer.setFingerprint(closestMatch); // translate UI pointer to new location on screen
                    saveFingerPrint(closestMatch);
                    // need to refresh map through updateHandler since only UI thread is allowed to touch its views
                    sUpdateHandler.post(mRefreshMap);

                    mScanThreadCount--;
                }
            };
            t.start(); // start new scan thread
        }
    }

    public void startMapEditActivity() {
        Intent intent = new Intent(MapViewActivity.this, MapEditActivity.class);
        intent.putExtra(EXTRA_MESSAGE_FLOOR, mSelectedMap);
        startActivity(intent); // start map edit mode
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // add menu items
        super.onCreateOptionsMenu(menu); // items for changing map
        menu.add(Menu.NONE, MENU_ITEM_EDIT_MAP, Menu.NONE, "Edit map");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case MENU_ITEM_EDIT_MAP: // start map edit mode
                startMapEditActivity();
                return true;
            default: // change map
                return super.onOptionsItemSelected(item);
        }
    }

    private void saveMap(HashMap<String,Integer> inputMap){
        SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences
                ("MyVariables", Context.MODE_PRIVATE);
        if (pSharedPref != null){
            JSONObject jsonObject = new JSONObject(inputMap);
            String jsonString = jsonObject.toString();
            SharedPreferences.Editor editor = pSharedPref.edit();
            editor.remove("My_map").commit();
            editor.putString("My_map", jsonString);
            editor.commit();
        }
    }

    private HashMap<String,Integer> loadMap(){
        HashMap<String,Integer> outputMap = new HashMap<String,Integer>();
        SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
        try{
            if (pSharedPref != null){
                String jsonString = pSharedPref.getString("My_map", (new JSONObject()).toString());
                JSONObject jsonObject = new JSONObject(jsonString);
                Iterator<String> keysItr = jsonObject.keys();
                while(keysItr.hasNext()) {
                    String key = keysItr.next();
                    Integer value = (Integer) jsonObject.get(key);
                    outputMap.put(key, value);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return outputMap;
    }

    private void saveFingerPrint(Fingerprint fingerprint)
    {
        PreferenceManager.getDefaultSharedPreferences(this).edit()
                .putInt(KEY_ID,fingerprint.getId())
                .putString(KEY_MAP,fingerprint.getMap())
                .putFloat(KEY_POSITON_X,fingerprint.getLocation().x)
                .putFloat(KEY_POSITON_Y,fingerprint.getLocation().y)
                .commit();
        saveMap(fingerprint.getMeasurements());

    }

    private Fingerprint getSavedFingerprint()
    {
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(this);
        int id=preferences.getInt(KEY_ID, -1);
        String map=preferences.getString(KEY_MAP, null);
        Float positionX=preferences.getFloat(KEY_POSITON_X, -1);
        Float positionY=preferences.getFloat(KEY_POSITON_Y,-1);
        PointF pointF=new PointF(positionX,positionY);
        Fingerprint fingerprint=new Fingerprint(id,map,pointF,loadMap());

        return fingerprint;
    }


}

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.project.mobileshoppingassistant">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activity.SplashScreenActivity"
            android:label="@string/title_activity_splash_screen"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.ProductScanActivity"
            android:label="@string/title_activity_barcode_scanner"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.MainActivity"
            android:label="@string/title_activity_main"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.UserRegisterActivity"
            android:label="@string/title_activity_user_register"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.DisplayProductActivity"
            android:label="@string/title_activity_display_product"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.TransactionActivity"
            android:label="@string/title_activity_transaction"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.AllProductsActivity"
            android:label="@string/title_activity_all_products"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.LoginActivity"
            android:label="@string/title_activity_login"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.CartActivity"
            android:label="@string/title_activity_cart"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.OrderActivity"
            android:label="@string/title_activity_order"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.RegisterActivity"
            android:label="@string/title_activity_register"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.TransactionHistoryActivity"
            android:label="@string/title_activity_transaction_history"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.PrefsActivity"
            android:label="@string/title_activity_transaction_history"
            android:screenOrientation="portrait" />
        PrefsActivity
        <activity
            android:name=".activity.SaleProductsActivity"
            android:label="@string/title_activity_sale_products"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.YourListActivity"
            android:label="@string/title_activity_your_list"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.ProductCategoryActivity"
            android:label="@string/title_activity_product_category"
            android:screenOrientation="portrait" />

        <activity android:name=".MapEditActivity"
            android:label="Localisation">
        </activity>

        <activity android:name=".MapViewActivity"
            android:label="Localisation"></activity>

        <activity android:name=".MapActivity"
            android:label="Localisation"></activity>
    </application>

</manifest>

当我点击按钮定位用户(从主要到mapeditactivity)我得到一个无法启动活动组件NullException.Can有人帮忙吗?

1 个答案:

答案 0 :(得分:0)

您尚未初始化mMap并在此处使用

 mLocationPointer = mMap.createNewWifiPointOnMap(new PointF(-1000, -1000)); 

在使用之前初始化它。