保存地图标记

时间:2015-11-30 17:00:11

标签: android sqlite google-maps

我有一个任务是创建一个地图应用程序,在长按下放置标记并在标记点击时显示标记信息。我还必须将它保存到SQLite中。问题是我被卡住了,似乎有些不对劲。离开app后,SQLite显得空洞。我不知道如何保存它们。欢迎任何帮助。 目标在app上退出要保存在DB中的标记,并在再次启动时重新加载并显示在地图上。 到目前为止,这是我的代码: MainActivity:

private GoogleMap mMap;
private JSONObject httpResponse;
private String markerCountry;
private String markerStreetAddress;
private JSONArray addressArray;
private ArrayList<Markers> markerOptionsList;
private Markers markerForDb;
private LatLng markerPosition;
private int counter=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);



}

@Override
protected void onDestroy() {
    if (counter==0){
        DatabaseHandler db = new DatabaseHandler(getApplicationContext(),null,null,1);
        try{

            for (Markers marker : markerOptionsList) {
                db.addMarker(marker);
            }
        }catch (NullPointerException e){
            e.printStackTrace();
        }finally {
            db.close();
        }

    }
    super.onDestroy();
}

@Override
protected void onPause() {
    if (counter==0){
        DatabaseHandler db = new DatabaseHandler(getApplicationContext(),null,null,1);
        try{

            for (Markers marker : markerOptionsList) {
                db.addMarker(marker);
            }
        }catch (NullPointerException e){
            e.printStackTrace();
        }finally {
            db.close();
        }
    }
    super.onPause();
}


@Override
protected void onStop() {
        if (counter==0){
            DatabaseHandler db = new DatabaseHandler(getApplicationContext(),null,null,1);
            try{

                for (Markers marker : markerOptionsList) {
                    db.addMarker(marker);
                }
            }catch (NullPointerException e){
                e.printStackTrace();
            }finally {
                db.close();
            }
        }
    super.onStop();
}



@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMyLocationEnabled(true);
    mMap.setOnMapLongClickListener(this);
    mMap.setOnMarkerClickListener(this);
    markerOptionsList = new ArrayList<>();
}


@Override
public void onMapLongClick(LatLng latLng) {
    markerPosition = latLng;
    mMap.addMarker(new MarkerOptions().position(markerPosition));
    getAddress(latLng);
    AsyncSaveToDb async2 = new AsyncSaveToDb();
    async2.execute(latLng);

}

private void getAddress(LatLng latLng) {
    URL url = null;
    try {
        url = new URL("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latLng.latitude + "," + latLng.longitude + "&key=AIzaSyBWH6gioY47pZjtCy-lz3rmyYNKVBOZnaA");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    Async async = new Async();
    async.execute(url);
}

@Override
public boolean onMarkerClick(Marker marker) {
    for (Markers markers :markerOptionsList) {
        double lat = markers.get_lat();
        double lng = markers.get_lng();
        LatLng latlng = new LatLng(lat,lng);
        if (latlng.equals(marker.getPosition())){
            Intent intent = new Intent(getApplicationContext(),com.example.fixxxer.mapclicker.MarkerInfoPage.class);
            String addressForText = markers.get_address();
            String countryForText = markers.get_country();
            String locationForText = markers.get_lat() + ", " + markers.get_lng();
            intent.putExtra("address", addressForText);
            intent.putExtra("country", countryForText);
            intent.putExtra("location", locationForText);
            startActivity(intent);
        }
    }
    return true;
}

public class Async extends AsyncTask<URL, Void, JSONArray> {


    @Override
    protected JSONArray doInBackground(URL... params) {
        BufferedReader reader;
        InputStream inputStream;
        JSONArray results = null;
        try {

            StringBuilder responseBuilder = new StringBuilder();
            HttpURLConnection conn = (HttpURLConnection) params[0].openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            inputStream = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            for (String line; (line = reader.readLine()) != null; ) {
                responseBuilder.append(line).append("\n");
            }
            httpResponse = new JSONObject(responseBuilder.toString());
            results = httpResponse.getJSONArray("results");
            inputStream.close();
            reader.close();

        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }


        return results;
    }

    @Override
    protected void onPostExecute(JSONArray resultList) {
        addressArray = resultList;
        JSONArray responseComponents;
        try {
            if (addressArray != null) {
                JSONObject firstResult = addressArray.getJSONObject(0);
                if (firstResult != null) {
                    responseComponents = firstResult.getJSONArray("address_components");
                    if (responseComponents != null) {
                        for (int i = 0; i < responseComponents.length(); i++) {
                            JSONObject currentComponent = responseComponents.getJSONObject(i);
                            if (currentComponent.getString("types").contains("country")) {
                                markerCountry = currentComponent.getString("long_name");
                                markerStreetAddress = firstResult.getString("formatted_address");
                                if (markerStreetAddress==null||markerStreetAddress.isEmpty()){
                                    markerStreetAddress="No address available for this location";
                                }else{
                                    String[] split = markerStreetAddress.split(",");
                                    markerStreetAddress="";
                                    for (int j =0;j<split.length-1;j++){
                                        markerStreetAddress+=split[j];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (markerStreetAddress==null||markerStreetAddress.isEmpty()) {
            markerStreetAddress = "No address available for this location";
        }
        Toast.makeText(getApplicationContext(), "Marker added", Toast.LENGTH_SHORT).show();
    }
}
public class AsyncSaveToDb extends AsyncTask<LatLng, Void, Markers>{

    @Override
    protected Markers doInBackground(LatLng... params) {
        markerForDb = new Markers();
        markerForDb.set_address(markerStreetAddress);
        markerForDb.set_country(markerCountry);
        markerForDb.set_lat(params[0].latitude);
        markerForDb.set_lng(params[0].longitude);
        markerForDb.set_image("image");

        return markerForDb;
    }

    @Override
    protected void onPostExecute(Markers markers) {
        markers = markerForDb;
        markerOptionsList.add(markerForDb);
        super.onPostExecute(markers);
    }
}

DatabaseHelper类:

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "locations.db";
public static final String TABLE_LOCATIONS = "locations";

public static final String COLUMN_ID = "_id";
public static final String COLUMN_ADDRESS = "_address";
public static final String COLUMN_COUNTRY = "_country";
public static final String COLUMN_LAT = "_lat";
public static final String COLUMN_LNG = "_lng";
public static final String COLUMN_IMAGE = "_image";


public DatabaseHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " +
            TABLE_LOCATIONS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_ADDRESS + " TEXT, " +
            COLUMN_COUNTRY + " TEXT, " +
            COLUMN_LAT + " REAL, " +
            COLUMN_LNG + " REAL, " +
            COLUMN_IMAGE + " TEXT " +
            ");";

    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
    onCreate(db);
}

public void addMarker(Markers marker) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_ADDRESS, marker.get_address());
    values.put(COLUMN_COUNTRY, marker.get_country());
    values.put(COLUMN_LAT, marker.get_lat());
    values.put(COLUMN_LNG, marker.get_lng());
    values.put(COLUMN_IMAGE, marker.get_image());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_LOCATIONS, null, values);
    db.close();
}

public void deleteMarker(int id) {
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM " + TABLE_LOCATIONS + " WHERE " + COLUMN_ID + "=\"" + id + "\";");
}

public ArrayList<Markers> getExistingMarkers() {
    ArrayList<Markers> list = new ArrayList<>();
    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_LOCATIONS;
    Cursor curs = db.rawQuery(query, null);
    curs.moveToFirst();
    while (!curs.isAfterLast()) {

        Markers marker = new Markers(
                curs.getString(1),
                curs.getString(2),
                Double.parseDouble(curs.getString(3)),
                Double.parseDouble(curs.getString(4)),
                curs.getString(5));
        list.add(marker);
    }
    curs.close();
    return list;
}

public Markers getOneMarker(double lat, double lng) {
    SQLiteDatabase db = this.getReadableDatabase();
    String query = "SELECT * FROM " + TABLE_LOCATIONS + " WHERE " + COLUMN_LAT + "=?" + " AND " + COLUMN_LNG + "=?";
    Cursor curs = db.rawQuery(query, new String[]{String.valueOf(lat), String.valueOf(lng)});
    if (curs != null)
        curs.moveToFirst();

    Markers marker = null;
    if (curs != null) {
        try{
            marker = new Markers(curs.getString(1), curs.getString(2), Double.parseDouble(curs.getString(3)), Double.parseDouble(curs.getString(4)), curs.getString(5));
        }catch (CursorIndexOutOfBoundsException e){
            e.printStackTrace();
        }

    }
    if (curs != null) {
        curs.close();
    }
    return marker;
}
public Markers getfirstMarker() {
    SQLiteDatabase db = this.getReadableDatabase();
    Markers marker=null;
    String query = "SELECT * FROM " + TABLE_LOCATIONS + " LIMIT 1";
    Cursor curs = db.rawQuery(query, null);
    if (curs != null) {
        curs.moveToFirst();
        try {
            marker = new Markers(curs.getString(1), curs.getString(2), Double.parseDouble(curs.getString(3)), Double.parseDouble(curs.getString(4)), curs.getString(5));
        } catch (CursorIndexOutOfBoundsException e) {
            e.printStackTrace();
        }

    }
    return marker;
}

数据库实体是标准的:

private int _id;
private String _address;
private String _country;
private double _lat;
private double _lng;
private String _image;

public Markers(int _id, String _address, String _country, double _lat, double _lng, String _image) {
    this._id = _id;
    this._address = _address;
    this._country = _country;
    this._lat = _lat;
    this._lng = _lng;
    this._image = _image;
}

public Markers(String _address, String _country, double _lat, double _lng, String _image) {
    this._address = _address;
    this._country = _country;
    this._lat = _lat;
    this._lng = _lng;
    this._image = _image;
}

public Markers() {

}

public int get_id() {
    return _id;
}

public void set_id(int _id) {
    this._id = _id;
}

public String get_address() {
    return _address;
}

public void set_address(String _address) {
    this._address = _address;
}

public String get_country() {
    return _country;
}

public void set_country(String _country) {
    this._country = _country;
}

public double get_lat() {
    return _lat;
}

public void set_lat(double _lat) {
    this._lat = _lat;
}

public double get_lng() {
    return _lng;
}

public void set_lng(double _lng) {
    this._lng = _lng;
}

public String get_image() {
    return _image;
}

public void set_image(String _image) {
    this._image = _image;
}

最后是MarkersInfoPage:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_marker_info_page);
    TextView addressText = (TextView) findViewById(R.id.addressView);
    TextView countryText = (TextView) findViewById(R.id.countryView);
    TextView position = (TextView) findViewById(R.id.latlngText);
    String address = getIntent().getStringExtra("address");
    String country =getIntent().getStringExtra("country");
    String location =getIntent().getStringExtra("location");
    addressText.setText(address);
    countryText.setText(country);
    position.setText(location);
    Button backButton = (Button) findViewById(R.id.backButton);
    backButton.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    super.finish();
}

我被困在这里很久了。任何帮助都是无价的。

0 个答案:

没有答案