Android从SQLite数据库填充字符串数组

时间:2012-02-14 14:09:30

标签: java android arrays sqlite

我尝试调整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);


    }

}

1 个答案:

答案 0 :(得分:1)

*

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();
            }


        }

*