我尝试使用json从数据库设置纬度和经度值来解析从php返回的Response 在函数setmMap我解析json和woking会!我被单独测试并且工作了! 并在mapReady上我调用setmMap()并使用日志来测试日志打印map1和map2而不是打印map3这意味着没有输入forloop如何让它进入 谢谢
{package com.example.lef.firstapplication;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
private static final LatLng PERTH = new LatLng(-31.952854, 115.857342);
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private static final LatLng BRISBANE = new LatLng(-27.47093, 153.0235);
private Marker mPerth;
private Marker mSydney;
private Marker mBrisbane;
RequestQueue requestQueue;
String allFriend = "http://192.168.0.103/PlaneEye/v1/allFriend";
int friend_id;
String friend_Fname;
String friend_Lname;
double latitude;
double longitude;
LinearLayout info ;
TextView title ;
Button button;
TextView snippet;
public List <User> userInf=new ArrayList<>();
public List <User> friendList=new ArrayList<>();
public List<User> getUserInf() {
return userInf;
}
public void setUserInf(List<User> userInf) {
this.userInf = userInf;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
info = new LinearLayout(this);
title = new TextView(this);
snippet = new TextView(this);
button = new Button(this);
// prepareFriendsLocation();
info.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
button.setBackgroundColor(Color.WHITE);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
prepareFriendsList();
}
public void setmMap()
{
Log.w("test","map1");
friendList=prepareFriendsList();
Log.w("test","map2");
for (int i=0;i<friendList.size();i++)
{ Log.w("test","map3");
mMap.addMarker(new MarkerOptions()
.position(new LatLng(friendList.get(i).getLatitude(),friendList.get(i).getLongitude()))
.title(friendList.get(i).getfName()+friendList.get(i).getlName())
.snippet("(-27.47093,153.0235)")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.friends_on_map))).setTag(0);
Log.w("jk",friendList.get(i).getfName()+friendList.get(i).getlName()+"yarb b2a");
}
mMap.setOnMarkerClickListener(this);
//getCompleteAddressString(-27.47093,153.0235);
//change markerInfoWindow style
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker arg0) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
info.setOrientation(LinearLayout.VERTICAL);
title.setTextColor(Color.BLACK);
title.setGravity(Gravity.CENTER);
title.setTypeface(null, Typeface.BOLD);
title.setText(marker.getTitle());
button.setText("Send Message");
snippet.setTextColor(Color.GRAY);
snippet.setText(marker.getSnippet());
info.removeView(title);
info.addView(title);
info.removeView(snippet);
info.addView(snippet);
info.removeView(button);
info.addView(button);
return info;
}
});
}
private List prepareFriendsList() {
requestQueue = Volley.newRequestQueue(this);
StringRequest request=new StringRequest(Request.Method.POST, "http://192.168.0.103/PlaneEye/v1/allFriend", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject user = new JSONObject(response);
JSONArray friends=user.getJSONArray("users");
for (int i = 0; i <friends.length() ; i++) {
final JSONObject friend = friends.getJSONObject(i);
friend_id = friend.getInt("user_id");
friend_Fname = friend.getString("fName");
friend_Lname = friend.getString("lName");
latitude = friend.getDouble("latitude");
longitude = friend.getDouble("longitude");
int online = friend.getInt("online");
userInf.add(new User(friend_id,friend_Fname,friend_Lname,latitude,longitude,online));
setUserInf(userInf);
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("userData", "Error");
}
});
requestQueue.add(request);
return getUserInf();
}
@Override
public void onMapReady(GoogleMap map) {
mMap = map;
// Add markers to the map
setmMap();
}
@Override
//CLick setOnMarkerClickListener
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
Integer clickCount = (Integer) marker.getTag();
// Check if a click count was set, then display the click count.
if (clickCount != null) {
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" has been clicked " + clickCount + " times.",
Toast.LENGTH_SHORT).show();
}
return false;
}
//get the location from lattude logtude
private String getCompleteAddressString(double LATITUDE, double LONGITUDE)
{
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<android.location.Address> addresses =
geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(Geocoder.isPresent()) {
if (addresses != null) {
android.location.Address returnedAddress =addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
} else {
//strAdd = "unfortunately, we can't display address Now";
}
}
else
{
Log.w("error","false");
}
}
catch (Exception e) {
e.printStackTrace();
//strAdd = "Please check your internet connection";
}
return strAdd;
}
答案 0 :(得分:0)
这可以更好地构建,但是从你的代码开始就是一个例子。
private void prepareFriendsList() {
requestQueue = Volley.newRequestQueue(this);
StringRequest request=new StringRequest(Request.Method.POST,
"http://192.168.0.103/PlaneEye/v1/allFriend",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
List<User> users = new ArrayList<>();
JSONObject user = new JSONObject(response);
JSONArray friends=user.getJSONArray("users");
for (int i = 0; i <friends.length() ; i++) {
final JSONObject friend = friends.getJSONObject(i);
friend_id = friend.getInt("user_id");
friend_Fname = friend.getString("fName");
friend_Lname = friend.getString("lName");
latitude = friend.getDouble("latitude");
longitude = friend.getDouble("longitude");
int online = friend.getInt("online");
users.add(new User(friend_id,friend_Fname,friend_Lname,latitude,longitude,online));
//setUserInf(userInf); // Dont update the entire list every iteration.
}
Log.d("Users parsed, call back to set Users!");
setUserInf(users);
} catch (JSONException e) {
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("userData", "Error");
}
});
requestQueue.add(request);
Log.d("Request Sent!");
//return getUserInf(); // empty list since users not parsed yet
}
然后更改setUserInf这是异步响应准备就绪时的回调。使用此函数构建地图对象。
public void setUserInf(List<User> users) {
this.userInf = users;
Log.d("Response callback!!");
for (int i=0;i<friendList.size();i++){
mMap.addMarker(new MarkerOptions() ...
}
...
}
这将为您提供您期望的流程。
> Request Sent!
> //... other logs while waiting for response.
> Users parsed, call back to set Users!
> Response callback!!