我需要使用onClick标记创建一个地图。标记保存在db中,单击标记时,必须在另一个活动中显示信息。没有任何理由我得到空指针异常......这是我到目前为止: 这是我的主要活动:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,OnMapClickListener,OnMarkerClickListener {
private GoogleMap mMap;
public LatLng markerLatLng;
public JSONArray js;
public LatLng latLng;
public Location location;
public DbActions DbActions;
public List<Markers> markersList;
public Markers readyMarker;
@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
public void onMapReady(GoogleMap googleMap)throws SecurityException {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lon = location.getLongitude();
latLng = new LatLng(lat, lon);
mMap = googleMap;
mMap.setOnMapClickListener(this);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
mMap.setOnMarkerClickListener(this);
markersList = new ArrayList<>();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onMapClick(LatLng latLng) {
js = null;
markerLatLng = latLng;
mMap.addMarker(new MarkerOptions().position(markerLatLng).title("Click me").draggable(true));
getAddress(latLng);
}
public 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=AIzaSyDE3_JFqocq7yObLvLayj0xMs3YRiVhiJI");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Async async =new Async();
async.execute(url);
}
@Override
public boolean onMarkerClick(Marker marker) {
DbActions = new DbActions(getApplicationContext(), null, null, 1);
Markers markerFromDB = DbActions.getOneMarker(readyMarker.get_lat(),readyMarker.get_lng());
MarkerInfo markerInfo =new MarkerInfo();
String address = markerFromDB.get_address();
String locat = markerFromDB.get_lat()+","+markerFromDB.get_lng();
markerInfo.addressView.setText(address);
markerInfo.addressView.setText(locat);
Intent intent = new Intent(MapsActivity.this, com.example.fixxxer.mapapplication.MarkerInfo.class);
startActivity(intent);
return false;
}
public class Async extends AsyncTask<URL, Void, JSONArray> {
public JSONArray jsonArray;
String country;
public JSONObject jsFirstAddress;
@Override
protected JSONArray doInBackground(URL... params) {
BufferedReader reader;
InputStream is;
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();
is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
for (String line; (line = reader.readLine()) != null; ) {
responseBuilder.append(line).append("\n");
}
JSONObject jObj= new JSONObject(responseBuilder.toString());
jsonArray = jObj.getJSONArray("results");
reader.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return jsonArray;
}
@Override
protected void onPostExecute(JSONArray jsonArrayResponse) {
js = jsonArrayResponse;
jsFirstAddress = null;
JSONArray jsCountry;
country = "";
try {
if (js != null) {
jsFirstAddress = js.getJSONObject(0);
if (jsFirstAddress != null) {
jsCountry = jsFirstAddress.getJSONArray("address_components");
JSONObject jsComponents;
for (int i = 0; i < jsCountry.length(); i++) {
jsComponents = jsCountry.getJSONObject(i);
if (jsComponents.getString("types").contains("country")) {
country = jsComponents.getString("long_name");
}
}
readyMarker = new Markers(jsFirstAddress.getString("formatted_address"), country, markerLatLng.latitude, markerLatLng.longitude, "image");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
DbActions = new DbActions(getApplicationContext(), null, null, 1);
DbActions.addMarker(readyMarker);
}
}
这是DBHelper类:
public class DbActions extends SQLiteOpenHelper {
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 DbActions(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 List<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 = new Markers(Integer.parseInt(curs.getString(0)),
curs.getString(1), curs.getString(2),Double.parseDouble(curs.getString(3)),Double.parseDouble(curs.getString(4)),curs.getString(5));
return marker;
}
以及必须从DB显示标记信息的其他活动:
public class MarkerInfo extends AppCompatActivity {
public TextView addressView;
public TextView latLngView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_marker_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addressView = (TextView) findViewById(R.id.addressText);
latLngView = (TextView) findViewById(R.id.latlngText);
}
我在这里得到空指针:
String address = markerFromDB.get_address();//<----HERE!
String locat = markerFromDB.get_lat()+","+markerFromDB.get_lng();
markerInfo.addressView.setText(address);
markerInfo.addressView.setText(locat);
奇怪的是,当我敬酒地址时,它完美地出现了。但我无法干预身份证。我对SQLite非常不好,所以我认为我的错误就在那里。有任何想法吗? logcat的:
java.lang.NullPointerException
11-14 16:27:28.703 16895-16895/com.example.fixxxer.mapapplication E/AndroidRuntime: at com.example.fixxxer.mapapplication.MapsActivity.onMarkerClick(MapsActivity.java:123)
这是第123行:
markerInfo.addressView.setText(address);