如何从SQLite获取所有标记?

时间:2018-06-08 13:17:56

标签: android sqlite android-sqlite

我想将SQLite数据库中的标记添加到地图中 我希望标记在地图开始时显示(在onMapReady()中) 我有一个SQLite数据库inilizetion的代码,并从Asset文件夹

加载db

SQLHelper.java

public class SQLHelper extends SQLiteOpenHelper{

    private static final String DATABASE_NAME = "atm-terdekat.db";
    private static final int DATABASE_VERSION = 1;
    private static String DB_PATH = "/data/data/com.mm.atmterdekat/databases/";
    private Context myContext;

    public SQLHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
        myContext=context;
    }

    public void createDataBase() throws IOException{
        if(DataBaseisExist()){
            //do nothing - database already exist
            Toast.makeText(myContext, "Database Sudah Ada", Toast.LENGTH_LONG).show();
        }
        else{
            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {
                copyDataBase();
                Toast.makeText(myContext, "Database Berhasil Diimport Dari Assets", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }

    }

    private boolean DataBaseisExist(){
        SQLiteDatabase checkDB = null;
        try{
            String myPath = DB_PATH + DATABASE_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){
            //database does't exist yet.
        }
        if(checkDB != null){
            checkDB.close();
        }
        if(checkDB != null )return true ;else return false;
    }

    private void copyDataBase() throws IOException{
        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
        // Path to the just created empty db
        String outFileName = DB_PATH + DATABASE_NAME;
        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);
        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }
        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }
}

这是我的地图片段。这就是我希望我的标记从onMapReady()开始的地方。

BNIFragment.java

public class BNIMapsFragment extends Fragment  implements OnMapReadyCallback{

    // DB
    SQLHelper dbHelper;
    Cursor cursor;

    //    vars
    private GoogleMap mMap;



    public BNIMapsFragment() {

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootVIew = inflater.inflate(R.layout.fragment_bnimaps, container, false);

        // membuat DB
        dbHelper = new SQLHelper(this.getActivity());
        try {
            dbHelper.createDataBase();
        }catch (Exception e){
            Toast.makeText(getActivity(), "Gagal", Toast.LENGTH_SHORT).show();
        }

        // Query untuk menampilkan semua Mall
        final SQLiteDatabase db = dbHelper.getReadableDatabase();
        cursor = db.rawQuery("SELECT * FROM atm_bni", null);
        cursor.moveToFirst();


        // what's next ?

        return rootVIew;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.bnimaps);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
//        mMap = googleMap;
//
//        LatLng ll = new LatLng(-7.76303354, 110.39192754);
//
//        MarkerOptions options = new MarkerOptions();
//        options.position(ll).title("Universitas Mercu Buana Yogyakarta");
//        mMap.addMarker(options);
//        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 15f));


    }

}

更新:

atm_bni表:

enter image description here

1 个答案:

答案 0 :(得分:1)

像这样的东西,只是通过查询数据库结果自定义部件:

@Override
public void onMapReady(GoogleMap googleMap) {
    // membuat DB
    dbHelper = new SQLHelper(this.getActivity());
    try {
        dbHelper.createDataBase();
    }catch (Exception e){
        Toast.makeText(getActivity(), "Gagal", Toast.LENGTH_SHORT).show();
    }

    // Query untuk menampilkan semua Mall
    final SQLiteDatabase db = dbHelper.getReadableDatabase();
    cursor = db.rawQuery("SELECT * FROM atm_bni", null);
    final LatLngBounds.Builder mapBuilder = new LatLngBounds.Builder();
    boolean addedMarker = false;
    if (cursor != null) {
        while (cw.moveToNext()) {
            double latitude = cursor.getDouble("latitude");
            double longitude = cursor.getDouble("longitude");

            MarkerOptions options = new MarkerOptions()
                .position(latitude, longitude)
                .anchor(0.5F, 1.0F)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
            Marker marker = googleMap.addMarker(options);
            mapBuilder.include(marker.getPosition());
            addedMarker = true;
        }
        if (!cursor.isClosed()) {
            cursor.close();
            cursor = null;
        }
    }

    if (addedMarker) {
        final LatLngBounds mapBounds = mapBuilder.build();
        final CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(mapBounds, 0);
        googleMap.moveCamera(cameraUpdate);
    }
}