错误:(99,45)错误:无法找到符号变量btnfinger / btnmeasure

时间:2016-04-04 08:00:38

标签: android sqlite

我试图通过触摸2个不同的按钮显示我的sqlite数据库中的所有数据。但是当我运行应用程序时,它给出了错误消息:(99,45)错误:无法找到符号变量btnfinger。我当然宣布了必要的按钮。

MapViewActivity.java

package com.inte.indoorpositiontracker;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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 android.view.View;
import android.widget.Button;
import android.app.AlertDialog;


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 {
    FingerprintDatabaseHandler myDb;
    Button btnfinger,btnmeasure;

    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);
        myDb = new FingerprintDatabaseHandler(this);
        btnmeasure=(Button)findViewById(R.id.btnfinger);
        btnfinger=(Button)findViewById(R.id.btnmeasure);
        ViewAllFinger();
        ViewAllMeasure();
    }


    @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;
    }


    public  void ViewAllFinger(){
        btnfinger.setOnClickListener(
                new View.OnClickListener() {

                    public void onClick(View v) {
                        Cursor res= myDb.getAllDataFinger();
                        if(res.getCount()==0){
                            showMessage("Error","nothing found");
                            return;
                        }
                        StringBuffer buffer= new StringBuffer();
                        while(res.moveToNext()){
                            buffer.append("fingerID :"+res.getString(0)+"\n");
                            buffer.append("mapName :"+res.getString(1)+"\n");
                            buffer.append("positionx :"+res.getString(2)+"\n");
                            buffer.append("positiony :"+res.getString(3)+"\n\n");
                        }
                        showMessage("Data", buffer.toString());
                    }

                }
        );
    }

    public  void ViewAllMeasure(){
        btnmeasure.setOnClickListener(
                new View.OnClickListener() {

                    public void onClick(View v) {
                        Cursor res= myDb.getAllDataMeasure();
                        if(res.getCount()==0){
                            showMessage("Error","nothing found");
                            return;
                        }
                        StringBuffer buffer= new StringBuffer();
                        while(res.moveToNext()){
                            buffer.append("measureID :"+res.getString(0)+"\n");
                            buffer.append("fingerprint :"+res.getString(1)+"\n");
                            buffer.append("bssid :"+res.getString(2)+"\n");
                            buffer.append("level :"+res.getString(3)+"\n\n");
                        }
                        showMessage("Data", buffer.toString());
                    }

                }
        );
    }

    public void showMessage(String title, String Message){
        AlertDialog.Builder builder= new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();

    }


}

FingerprintDatabaseHelper.java

package com.inte.indoorpositiontracker;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.PointF;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class FingerprintDatabaseHandler extends SQLiteOpenHelper{
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "fingerprints";
    private static final String TABLE_MEASUREMENTS = "measurements";
    private static final String TABLE_FINGERPRINTS = "fingerprints";


    // measurements table columns names
    private static final String KEY_MEASUREMENT_ID = "id";
    private static final String KEY_FINGERPRINT = "fingerprint_id";
    private static final String KEY_BSSID = "bssid";
    private static final String KEY_LEVEL = "value";

    // fingerprintss table column names
    private static final String KEY_FINGERPRINT_ID = "id";
    private static final String KEY_MAP_NAME = "map_name";
    private static final String KEY_POSITION_X = "position_x";
    private static final String KEY_POSITION_Y = "position_y";



    /** CONSTRUCTORS */
    public FingerprintDatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }



    /** INSTANCE METHODS */

    @Override
    public void onCreate(SQLiteDatabase db) {
        // create tables

        String CREATE_MEASUREMENTS_TABLE = "CREATE TABLE " + TABLE_MEASUREMENTS + "("
                + KEY_MEASUREMENT_ID + " INTEGER PRIMARY KEY,"
                + KEY_FINGERPRINT + " INTEGER,"
                + KEY_BSSID + " TEXT,"
                + KEY_LEVEL + " INTEGER" + ")";
        db.execSQL(CREATE_MEASUREMENTS_TABLE);  

        String CREATE_FINGERPRINT_TABLE = "CREATE TABLE " + TABLE_FINGERPRINTS + "("
                + KEY_FINGERPRINT_ID + " INTEGER PRIMARY KEY,"
                + KEY_MAP_NAME + " TEXT,"
                + KEY_POSITION_X + " FLOAT,"
                + KEY_POSITION_Y + " FLOAT" + ")";

        db.execSQL(CREATE_FINGERPRINT_TABLE);  
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEASUREMENTS);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FINGERPRINTS);

        // Create tables again
        onCreate(db);
    }

    public Cursor getAllDataFinger() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor resfinger = db.rawQuery("select * from " + TABLE_FINGERPRINTS, null);
        return resfinger;
    }

    public Cursor getAllDataMeasure() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor resmeasure = db.rawQuery("select * from " + TABLE_MEASUREMENTS, null);
        return resmeasure;

    }

    public void addFingerprint(Fingerprint fingerprint) {
        SQLiteDatabase db = this.getWritableDatabase();
        PointF location = fingerprint.getLocation();

        ContentValues fingerprintValues = new ContentValues();
        fingerprintValues.put(KEY_MAP_NAME, fingerprint.getMap());
        fingerprintValues.put(KEY_POSITION_X, location.x);
        fingerprintValues.put(KEY_POSITION_Y, location.y);

        // insert fingerprint into fingerprints table
        long fingerprintId = db.insert(TABLE_FINGERPRINTS, null, fingerprintValues);


        // insert measurements into measurements table
        if(fingerprintId != -1) {
            Map<String, Integer> measurements = fingerprint.getMeasurements();
            for(String key : measurements.keySet()) {
                int value = measurements.get(key);

                ContentValues measurementValues = new ContentValues();
                measurementValues.put(KEY_FINGERPRINT, fingerprintId);
                measurementValues.put(KEY_BSSID, key);
                measurementValues.put(KEY_LEVEL, value);
                db.insert(TABLE_MEASUREMENTS, null, measurementValues);
            }
        }

        db.close();
    }

    public Fingerprint getFingerprint(int id) {
        Fingerprint fingerprint = null;

        SQLiteDatabase db = this.getReadableDatabase();

        // SQL query
        Cursor cursor = db.query(TABLE_FINGERPRINTS,
                new String[] {KEY_FINGERPRINT_ID, KEY_MAP_NAME, KEY_POSITION_X, KEY_POSITION_Y},
                KEY_FINGERPRINT_ID + " = ?", new String[] { String.valueOf(id) },
                null, null, null, null);

        if (cursor.moveToFirst()) {
            // parse fingerprint data
            String map = cursor.getString(1);
            PointF location = new PointF(cursor.getFloat(2), cursor.getFloat(3));
            HashMap<String, Integer> measurements = getMeasurements(id);

            // create fingerprint
            fingerprint = new Fingerprint(id, map, location, measurements);
        }

        cursor.close();
        db.close();
        return fingerprint;
    }

    public ArrayList<Fingerprint> getAllFingerprints() {
        ArrayList<Fingerprint> fingerprints = new ArrayList<Fingerprint>();

        String SELECT_QUERY = "SELECT * FROM " + TABLE_FINGERPRINTS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(SELECT_QUERY, null); // SQL query

        // loop through all fingerprint rows and add to list
        if (cursor.moveToFirst()) {
            do {
                // parse fingerprint data
                int id = cursor.getInt(0);
                String map = cursor.getString(1);
                PointF location = new PointF(cursor.getFloat(2), cursor.getFloat(3));

                HashMap<String, Integer> measurements = getMeasurements(id); // query measurements

                Fingerprint fingerprint = new Fingerprint(id, map, location, measurements); // create fingerprint

                fingerprints.add(fingerprint); // add to list returned fingerprints
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return fingerprints;
    }

    public HashMap<String, Integer> getMeasurements(int fingerprintId) {
        SQLiteDatabase db = this.getReadableDatabase();

        // SQL query
        Cursor cursor = db.query(TABLE_MEASUREMENTS,
                new String[] {KEY_BSSID, KEY_LEVEL},
                KEY_FINGERPRINT + " = ?", new String[] { String.valueOf(fingerprintId) },
                null, null, null, null);

        HashMap<String, Integer> measurements = new HashMap<String, Integer>();

        // loop through all measurement rows and add to list
        if(cursor.moveToFirst()) {
            do {
                // parse measurement data
                String BSSID = cursor.getString(0);
                int level = cursor.getInt(1);

                measurements.put(BSSID, level); // add to list
            } while(cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return measurements;
    }

    public int getFingerprintCount() {
        String COUNT_QUERY = "SELECT  * FROM " + TABLE_FINGERPRINTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(COUNT_QUERY, null); // SQL query
        int count = cursor.getCount();

        cursor.close();
        db.close();
        return count;
    }

    public void deleteFingerprint(Fingerprint fingerprint) {
        SQLiteDatabase db = this.getWritableDatabase();

        // SQL query for deleting fingerprint
        db.delete(TABLE_FINGERPRINTS, KEY_FINGERPRINT_ID + " = ?",
                new String[] { String.valueOf(fingerprint.getId()) });

        // SQL query for deleting measurements linked to given fingerprint
        db.delete(TABLE_MEASUREMENTS, KEY_FINGERPRINT + " = ?",
                new String[] { String.valueOf(fingerprint.getId()) });

        db.close();
    }

    public void deleteAllFingerprints() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_FINGERPRINTS, null, null); // delete all fingerprints
        db.delete(TABLE_MEASUREMENTS, null, null); // delete all measurements
        db.close();
    }
}
你能帮我解决一下吗?感谢

0 个答案:

没有答案