简体   繁体   中英

Android populate string array from SQLite database

I have tried to adapt the Google notepad tutorial ( http://developer.android.com/resources/tutorials/notepad/index.html ) for using SQLite databases to store GPS co-ords when the user tags current location. I've had no trouble getting the location added to the database but currently having trouble populating an array from the database in order to draw the locations on the map

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

I'm using a separate class called LocationsDbAdapter for handling database management as demonstrated in the notepad tutorial. The COL_LATITUDE and COL_LONGITUDE variables point to the column titles.

I've used a for loop to determine that nothing seems to be going into the strarrlatitude array but using the SQLite CLI I've checked that the database is being determined

Any help would be most gratefully received - if any more information is required I'll upload it as quick as possible

Many thanks

EDIT: Added the main two classes below for extra reference. I was trying not to overload with too much information but that was an error in judgement.

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
    }

}

}

/** * Following class has been adapted from Google's Android Notepad tutorial: 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();
            }


        }

*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM