只需从 JSON 接收一个数据对象
Posted
技术标签:
【中文标题】只需从 JSON 接收一个数据对象【英文标题】:Just recieve one Dataobject from JSON 【发布时间】:2017-08-26 19:07:41 【问题描述】:我尝试将地图标记从 JSON 获取到 MapActivity。 我只是从 JSON 中得到第一个,其他的没有显示在我的地图中。 我该如何解决我的问题。 这是我的地图活动:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
private ProgressDialog pDialog;
private GoogleMap mMap;
private static String url="http://partypeople.bplaced.net/markers.json";
ArrayList<HashMap<String, String>> contactList;
private String TAG = MainActivity.class.getSimpleName();
double latitude;
double longitude;
String namec;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState)
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
contactList = new ArrayList<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map3);
mapFragment.getMapAsync(this);
private class GetContacts extends AsyncTask<Void, Void, Void>
@Override
protected void onPreExecute()
super.onPreExecute();
@Override
protected Void doInBackground(Void... arg0)
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null)
try
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray("markers");
for (int i = 0; i < contacts.length(); i++)
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String address = c.getString("address");
String lat = c.getString("lat");
String lng = c.getString("lng");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("address",address);
contact.put("lat", lat);
contact.put("lng", lng);
latitude = Double.parseDouble(lat); longitude = Double.parseDouble(lng);
contactList.add(contact);
namec = name;
catch (final JSONException e)
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
);
else
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
);
return null;
@Override
protected void onPostExecute(Void result)
super.onPostExecute(result);
LatLng P1 = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(P1).title(namec));
mMap.moveCamera(CameraUpdateFactory.newLatLng(P1));
@Override
public void onMapReady(GoogleMap googleMap)
mMap = googleMap;
new GetContacts().execute();
mMap.setMyLocationEnabled(true);
这是我的 JSON:
"markers": [
"id": "c201",
"name": "Munic",
"address": "try",
"lat": "48.142281",
"lng" : "11.550613"
,
"id": "c205",
"name": "Berlin",
"address": "test",
"lat": "43.142281",
"lng" : "11.550613"
]
这是我的 httpHandler:
公共类 HttpHandler
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler()
public String makeServiceCall(String reqUrl)
String response = null;
try
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
catch (MalformedURLException e)
Log.e(TAG, "MalformedURLException: " + e.getMessage());
catch (ProtocolException e)
Log.e(TAG, "ProtocolException: " + e.getMessage());
catch (IOException e)
Log.e(TAG, "IOException: " + e.getMessage());
catch (Exception e)
Log.e(TAG, "Exception: " + e.getMessage());
return response;
private String convertStreamToString(InputStream is)
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try
while ((line = reader.readLine()) != null)
sb.append(line).append('\n');
catch (IOException e)
e.printStackTrace();
finally
try
is.close();
catch (IOException e)
e.printStackTrace();
return sb.toString();
【问题讨论】:
【参考方案1】:您的问题出在 onPostExecute 中,您只在地图上添加了一个标记。 你应该在那里使用你的联系人列表:
for (HashMap<String, String> contact: contactList)
LatLng P1 = new LatLng(
Double.parseDouble(contact.get("lat")),
Double.parseDouble(contact.get("lng")));
mMap.addMarker(new MarkerOptions().position(P1).title(contact.get("name")));
mMap.moveCamera(CameraUpdateFactory.newLatLng(P1));
【讨论】:
我试过了,但它没有运行,只显示了一个标记 对不起,现在它工作正常我有一个错误:)以上是关于只需从 JSON 接收一个数据对象的主要内容,如果未能解决你的问题,请参考以下文章