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

标签 java android arrays sqlite

我尝试改编 Google 记事本教程 (http://developer.android.com/resources/tutorials/notepad/index.html),以便在用户标记当前位置时使用 SQLite 数据库来存储 GPS 坐标。我在将位置添加到数据库时没有遇到任何问题,但目前在从数据库填充数组以在 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();
}

我正在使用一个名为 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
    }

}

}

/** * 以下类(class)改编自 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();
            }


        }

*

关于java - Android 从 SQLite 数据库填充字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9278324/

相关文章:

java - Spring Query By Example 使用 "OR"

java - Java 中的 Ubuntu : Redirection from a . txt 文件

一年中的 Java 毫秒数

java - 使用 Visa Checkout 解密支付数据

javascript - 无法从我的 API 访问数据(异步问题)

android - 如何在 Flutter 中使 Expanded 中的文本可滚动

android - ScrollView 内的 Google Maps API v2 SupportMapFragment - 用户无法垂直滚动 map

android - 当 ViewPager 的父 Fragment 隐藏然后显示时,ViewPager 的 Fragment 的 View 丢失

java - 如何使用流将 String 数组转换为 int 数组

java - 如何在 FileOutputStream 中使用数组列表