簡體   English   中英

Android從SQLite數據庫填充字符串數組

[英]Android populate string array from SQLite database

我試圖改編Google記事本教程( http://developer.android.com/resources/tutorials/notepad/index.html ),以便在用戶標記當前位置時使用SQLite數據庫存儲GPS坐標。 我毫不費力地將位置添加到數據庫中,但是目前無法從數據庫填充數組以在地圖上繪制位置

private void fillData() {
    /**
     *  Get all of the geotags from the database and populate the strarrlatitude and strarrlongitude arrays
     *  Also calls 'drawpins' to draw the geotags on the map
     */

    Cursor c = mDbHelper.fetchAllNotes();
    startManagingCursor(c);

    strarrlatitude = new String[] { LocationsDbAdapter.COL_LATITUDE};
    System.out.println(strarrlatitude);
    strarrlongitude = new String[] { LocationsDbAdapter.COL_LONGITUDE };

    drawpins();
}

我正在使用一個名為LocationsDbAdapter的單獨類來處理數據庫管理,如記事本教程中所示。 COL_LATITUDE和COL_LONGITUDE變量指向列標題。

我使用了for循環來確定strarrlatitude數組中似乎沒有任何內容,但是使用SQLite CLI,我已經檢查了數據庫是否已確定

非常感謝您的任何幫助-如果需要更多信息,我會盡快上傳

非常感謝

編輯:添加了下面的主要兩個類,以供參考。 我試圖不讓過多的信息超載,但這是判斷上的錯誤。

package com.nick.locationapp;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.AlteredCharSequence;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.nick.androidsoar.R;

public class AndroidSoarActivity extends MapActivity {
/** Called when the activity is first created. */


LinearLayout linearLayout;
MapView mapView;
TextView LocationText;
double dbllatitude;
double dbllongitude;
double dblaltitude;
String debugstring; 
String strlatitude = "0";
String strlongitude = "0";
String[] strarrlatitude;
String[] strarrlongitude;
String[] strarrlatitude1 = {"50.0","40.0","43.0","100.0"};
String[] strarrlongitude1 = {"12.4","123.4","60.2","72.0"};
Double[] debuglat = {50.0,40.0,43.0,100.0};
Double[] debuglong = {12.4,123.4,60.2,72.0};
Double dbllat;
Double dbllong;
int intlatitude;
int intlongitude;

private LocationsDbAdapter mDbHelper;
public static final int INSERT_ID = Menu.FIRST;

List<Overlay> mapOverlays;
Drawable drawable;
HelloItemizedOverlay itemizedOverlay; 


@Override
protected boolean isRouteDisplayed() {
        return false;
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Identifies the textview as variable 'LocationText'
    LocationText = (TextView)findViewById(R.id.locationtext);
    //mDbHelper points to the LocationsDbAdapter class used for handling the database
    mDbHelper = new LocationsDbAdapter (this);
    mDbHelper.open();


    //defines the mapview as variable 'mapView' and enables zoom controls
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);

    mapOverlays = mapView.getOverlays();

    //points variable 'drawable' to the icon resource of a pushpin, used for marking tags on the map
    drawable = this.getResources().getDrawable(R.drawable.pushpin);

    //Adds a current location overlay to the map 'mapView' and turns on the map's compass
    MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocationOverlay);
    myLocationOverlay.enableMyLocation();
    myLocationOverlay.enableCompass();
    mapView.postInvalidate();

    /**
     * Code required to receive gps location. Activates GPS provider, and is set to update only after
     * at least 10 seconds and a position change of at least 10 metres
     */
    LocationListener locationListener = new MyLocationListener();

    //setting up the location manager
    LocationManager locman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, locationListener); 
    //fillData();
}


/**
 * Generates the menu from the resource 'mainmenu.xml'
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
}
/**
 * Code to run depending on the menu button pressed
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.new_tag:
        createTag();
        fillData();
        //Toast.makeText(getApplicationContext(), "geotag added to db", Toast.LENGTH_SHORT).show();

        return true;
    case R.id.draw_pins:
        //fillData();
        drawpins();

        return true;
    case R.id.create_tag:
        Intent intent = new Intent(AndroidSoarActivity.this, TagCreate.class);
        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
}

/**
 * Create a new geotag pin from the current location
 */
private void createTag() {


    //String titleName = "title " + titleNumber++;
    mDbHelper.createNote(strlatitude, strlongitude);
    Toast.makeText(getApplicationContext(), "geotag of lat: "+dbllatitude+" long: "+dbllongitude+" added to db ", Toast.LENGTH_SHORT).show();
    fillData();
}



private void fillData() {
    /**
     *  Get all of the geotags from the database and populate the strarrlatitude and strarrlongitude arrays
     *  Also calls 'drawpins' to draw the geotags on the map
     */
    System.out.println("Fetching data");
    Cursor c = mDbHelper.fetchAllNotes();
    System.out.println(c.toString());
    startManagingCursor(c);

    strarrlatitude = new String[] { LocationsDbAdapter.COL_LATITUDE };
    //System.out.println(strarrlatitude);
    strarrlongitude = new String[] { LocationsDbAdapter.COL_LONGITUDE };



}
/**
 * Creates an array of geopoints, pulling the locations from strarrlatitude and strarrlongitude
 * and creates a mapview overlay using the geopoints
 */
private void drawpins() {


    itemizedOverlay = new HelloItemizedOverlay(drawable);
    GeoPoint[] mapPoints = new GeoPoint[strarrlatitude.length];
    OverlayItem[] mapItems = new OverlayItem[strarrlatitude.length];

    for(int i=1; i<strarrlatitude.length;i++){

        dbllat = Double.parseDouble(strarrlatitude[i]);
        dbllong = Double.parseDouble(strarrlongitude[i]);
        System.out.println(i);   
            mapPoints[i] = new GeoPoint((int) (dbllat * 1E6), (int) (dbllong * 1E6));
            mapItems[i] = new OverlayItem(mapPoints[i], "", "");                                       
            itemizedOverlay.addOverlay(mapItems[i]);

            mapOverlays.add(itemizedOverlay);
    }

}



private final class MyLocationListener implements LocationListener {

    /**
     * Code to run when the listener receives a new location
     */
    @Override
    public void onLocationChanged(Location locFromGps) {



        Toast.makeText(getApplicationContext(), "Location changed, Lat: "+locFromGps.getLatitude()+" Long: "+ locFromGps.getLongitude(), Toast.LENGTH_SHORT).show();

        //LocationText.setText("Your Location: Latitude " +locFromGps.getLatitude() + " Longitude: " +locFromGps.getLongitude());

        dbllatitude = locFromGps.getLatitude();
        dbllongitude = locFromGps.getLongitude();
        dblaltitude = locFromGps.getAltitude();

        strlatitude = Double.toString(dbllatitude);
        strlongitude = Double.toString(dbllongitude);
        dblaltitude = (dblaltitude / 0.3048); 

        LocationText.setText("Your Location: Latitude " + dbllatitude + " Longitude: " +dbllongitude + " Altitude " + dblaltitude);

    }

    @Override
    public void onProviderDisabled(String provider) {
       // called when the GPS provider is turned off (user turning off the GPS on the phone)
    }

    @Override
    public void onProviderEnabled(String provider) {
       // called when the GPS provider is turned on (user turning on the GPS on the phone)
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
       // called when the status of the GPS provider changes
    }

}

}

/ ** *以下課程已從Google的Android記事本教程改編而成: http : //developer.android.com/resources/tutorials/notepad/index.html * * /

package com.nick.locationapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class LocationsDbAdapter {

public static final String COL_LATITUDE = "latitude";
public static final String COL_LONGITUDE = "longitude";
//public static final String KEY_NOTE = "note";
public static final String COL_TITLE = "title";
public static final String COL_ROWID = "_id";
//public static final String TABLE_LOC = "locations";

private static final String TAG = "LocationsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

/**
 * Database creation sql statement
 */
private static final String DATABASE_CREATE =
    "CREATE TABLE locations (_id integer primary key autoincrement, "
    + "latitude text not null, longitude text not null);";

private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "locations";
private static final int DATABASE_VERSION = 1;

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    /**
     * SQL for creating the table. Table and column names are declared as variables
     */
    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE "+DATABASE_TABLE+" ("+COL_ROWID+ " INTEGER PRIMARY KEY AUTOINCREMENT, "+COL_LATITUDE+ " TEXT, "+COL_LONGITUDE+" TEXT "+COL_TITLE+" TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS location");
        onCreate(db);
    }
}


public LocationsDbAdapter(Context ctx) {
    this.mCtx = ctx;
}

public LocationsDbAdapter open() throws SQLException {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    mDbHelper.close();
}

/**
 * Code for adding latitude and longitude into the database
 * @param latitude
 * @param longitude
 * @return
 */
public long createNote(String latitude, String longitude) {
    ContentValues geotagValues = new ContentValues();
    geotagValues.put(COL_LATITUDE, latitude);
    geotagValues.put(COL_LONGITUDE, longitude);
    //geotagValues.put(COL_TITLE, title);


    return mDb.insert(DATABASE_TABLE, null, geotagValues);
}

/**
 * Query to return all data
 * @return
 */
public Cursor fetchAllNotes() {

    return mDb.query(DATABASE_TABLE, new String[] {COL_ROWID, COL_LATITUDE, COL_LONGITUDE}, null, null, null, null, null);


    }

}
*

public void getData()
        {
            List<String> labels = new ArrayList<String>();
            placeData = new PlaceDataSQL(MainActivity.this);
            String selectQuery = "SELECT * FROM xmlTable;";
            SQLiteDatabase db = placeData.getWritableDatabase();

            Cursor cursor = db.rawQuery(selectQuery, null);
            {
                // looping through all rows and adding to list
                if (cursor.moveToFirst()) {
                    do {

                        labels.add(cursor.getString(1));

                        Log.i("imagespath",arr[i]);
                        i++;
                    } while (cursor.moveToNext());
                }
                cursor.close();enter code here
                db.close();
            }


        }

*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM