Android sndroid使用json hashmap映射v2
单击带有json和集群的标记时如何启动活动 我的地图已经群集,但当单击没有标题的标记时,我无法开始新的活动 这是我的密码Android sndroid使用json hashmap映射v2,android,Android,单击带有json和集群的标记时如何启动活动 我的地图已经群集,但当单击没有标题的标记时,我无法开始新的活动 这是我的密码 package tmg.tower; /** * Created by DIMAS on 25/06/2015. */ import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.app.FragmentMa
package tmg.tower;
/**
* Created by DIMAS on 25/06/2015.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
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 com.google.maps.android.clustering.ClusterManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity implements GoogleMap.OnMarkerClickListener, View.OnClickListener {
private JSONParser json;
private LatLng myLocation;
ArrayList<HashMap<String, String>> dataMap = new ArrayList<HashMap<String, String>>();
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
Server serv = new Server();
String conn = serv.connection();
String url = conn + "********";
JSONArray str_json = null;
static final int showerror = 1;
public static final String SP = "shareAt";
SharedPreferences shareAt;
public static final String KEY_LAT_TUJUAN = "lat_tujuan";
public static final String KEY_LNG_TUJUAN = "lng_tujuan";
static final LatLng AWAL = new LatLng(3.584695, 98.675079);
Button mBtnFind;
EditText etPlace;
Button searchlist;
private ClusterManager<MyItem> mClusterManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LatLng myPosition;
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS Disabled, Buka Setting dan Aktifkan GPS?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
Toast.makeText(getApplicationContext(), "GPS Enabled", Toast.LENGTH_LONG).show();
}
if (cek_status(this)) {
Server serv = new Server();
conn = serv.connection();
new getListInfo().execute();
} else {
showDialog(showerror);
}
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment) myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.getUiSettings().setAllGesturesEnabled(true);
myMap.setTrafficEnabled(true);
myMap.setOnMarkerClickListener(this);
myMap.moveCamera(CameraUpdateFactory.newLatLngZoom(AWAL, 15));
myMap.setBuildingsEnabled(true);
myMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
mBtnFind = (Button) findViewById(R.id.btn_show);
etPlace = (EditText) findViewById(R.id.et_place);
searchlist = (Button) findViewById(R.id.searchlist);
searchlist.setOnClickListener(this);
mBtnFind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Getting the place entered
String location = etPlace.getText().toString();
if(location==null || location.equals("")){
Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}
String url = "https://**********";
try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(location, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String siteid = "Site_ID=" + location;
String sensor = "sensor=false";
// url , from where the geocoding data is fetched
url = url + siteid + "&" + sensor;
// Instantiating DownloadTask to get places from Google Geocoding service
// in a non-ui thread
DownloadTask downloadTask = new DownloadTask();
// Start downloading the geocoding places
downloadTask.execute(url);
}
});
}
public void onClick (View v){
Intent i = new Intent(MainActivity.this,Search.class);
startActivity(i);
}
public boolean cek_status(Context cek) {
ConnectivityManager cm = (ConnectivityManager) cek.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case showerror:
AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
errorDialog.setTitle("Error Connection");
errorDialog.setMessage("Please check your internet connection");
errorDialog.setNeutralButton("exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.this.finish();
startActivity(exit);
}
});
AlertDialog errorAlert = errorDialog.create();
return errorAlert;
default:
break;
}
return dialog;
}
@Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
@SuppressLint("LongLogTag")
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(String result){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
class getListInfo extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Loading server...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONObject json = jParser.AmbilJson(url);
try {
str_json = json.getJSONArray("tower");
for (int i = 0; i < str_json.length(); i++) {
JSONObject ar = str_json.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Site ID", ar.getString("Site ID"));
map.put("Site Name", ar.getString("Site Name"));
map.put("Address", ar.getString("Address"));
map.put("Lattitude", ar.getString("Lattitude"));
map.put("Longitude", ar.getString("Longitude"));
dataMap.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
mClusterManager = new ClusterManager<MyItem>(getApplicationContext(), myMap);
myMap.setOnCameraChangeListener(mClusterManager);
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
for (int i = 0; i < dataMap.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
List<MyItem> items = new ArrayList<MyItem>();
map = dataMap.get(i);
mClusterManager.addItem(new MyItem(Double.parseDouble(map.get("Lattitude")), Double.parseDouble(map.get("Longitude"))));
}
}
});
}
}
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
@Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.parse(jObject);
}catch(Exception e){
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(List<HashMap<String,String>> list){
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("Lattitude"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("Longitude"));
// Getting name
String name = hmPlace.get("Site ID");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Locate the first location
if(i==0)
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
@Override
public boolean onMarkerClick(Marker marker) {
myLocation = new LatLng(myMap.getMyLocation().getLatitude(), myMap.getMyLocation().getLongitude());
if (myLocation != null) {
Bundle bundle = new Bundle();
bundle.putDouble(KEY_LAT_TUJUAN, marker.getPosition().latitude);
bundle.putDouble(KEY_LNG_TUJUAN, marker.getPosition().longitude);
shareAt = getBaseContext().getSharedPreferences(SP, 0);
SharedPreferences.Editor editor = shareAt.edit();
String replace_string_first = marker.getTitle().replace(" ", "_");
editor.putString("Site ID", replace_string_first);
editor.putString("Lattitude", replace_string_first);
editor.putString("Longitude", replace_string_first);
editor.commit();
Intent intent = new Intent(MainActivity.this, Main.class);
intent.putExtras(bundle);
intent.putExtra("Site ID", replace_string_first);
intent.putExtra("Lattitude", replace_string_first);
intent.putExtra("Longitude", replace_string_first);
startActivity(intent);
}
return false;
}
}
包装tmg.tower;
/**
*由DIMAS于2015年6月25日创建。
*/
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.app.Dialog;
导入android.app.FragmentManager;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.location.LocationManager;
导入android.net.ConnectivityManager;
导入android.net.NetworkInfo;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.provider.Settings;
导入android.support.v7.app.AlertDialog;
导入android.util.Log;
导入android.view.Menu;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.GooglePlayServicesUtil;
导入com.google.android.gms.maps.CameraUpdateFactory;
导入com.google.android.gms.maps.GoogleMap;
导入com.google.android.gms.maps.MapFragment;
导入com.google.android.gms.maps.model.LatLng;
导入com.google.android.gms.maps.model.Marker;
导入com.google.android.gms.maps.model.MarkerOptions;
导入com.google.maps.android.clustering.ClusterManager;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.urlcoder;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
公共类MainActivity扩展活动实现GoogleMap.OnMarkerClickListener、View.OnClickListener{
私有JSONParser json;
私人车床定位;
ArrayList dataMap=新的ArrayList();
私人对话;
JSONParser jParser=新的JSONParser();
服务器服务=新服务器();
字符串conn=serv.connection();
字符串url=conn+“*******”;
JSONArray str_json=null;
静态最终积分ROR=1;
公共静态最终字符串SP=“shareAt”;
SharedReferences shareAt;
公共静态最终字符串键\u LAT\u TUJUAN=“LAT\u TUJUAN”;
公共静态最终字符串键\u LNG\u TUJUAN=“LNG\u TUJUAN”;
静态最终车床警报=新车床警报(3.584695,98.675079);
按钮mBtnFind;
编辑文本位置;
按钮搜索列表;
私人群集管理器McClusterManager;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
车床位置;
最终LocationManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
如果(!manager.isProviderEnabled(LocationManager.GPS\U提供程序)){
final AlertDialog.Builder=新建AlertDialog.Builder(此);
builder.setMessage(“GPS禁用,Buka设置和Aktifkan GPS?”)
.setCancelable(错误)
.setPositiveButton(“Ya”,新的DialogInterface.OnClickListener(){
public void onClick(@SuppressWarnings(“未使用”)最终对话框接口对话框,@SuppressWarnings(“未使用”)最终int-id){
startActivity(新意图(设置、动作、位置、来源、设置));
完成();
}
})
.setNegativeButton(“Tidak”,新的DialogInterface.OnClickListener(){
public void onClick(final DialogInterface dialog,@SuppressWarnings(“未使用”)final int-id){
完成();
}
});
final AlertDialog alert=builder.create();
alert.show();
}否则{
Toast.makeText(getApplicationContext(),“启用GPS”,Toast.LENGTH_LONG.show();
}
if(cek_状态(本)){
服务器服务=新服务器();
conn=serv.connection();
新建getListInfo().execute();
}否则{
showDialog(淋浴器);
}
FragmentManager myFragmentManager=getFragmentManager();
MapFragment myMapFragment
=(MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap=myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP\u TYPE\u地形);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.getUiSettings().setAllGesturesEnabled(true);
myMap.setTrafficEnabled(true);
setOnMarkerClickListener(这个);
myMap.moveCamera(CameraUpdateFactory.newLatLngZoom(AWAL,15));
myMap.SetBuildingEnabled(true);
myMap.animateCamera(CameraUpdateFactory.zoomTo(10),2000,空);
mBtnFind=(按钮)findviewbyd(R.id.btn_show);
etPlace=(EditText)findViewById(R.id.et_place);
searchlist=(按钮)findviewbyd(R.id.searchlist);
searchlist.setOnClickListener(此);
mBtnFind.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//进入这个地方
字符串位置=etPlace.getText().toString();
if(location==null | | location.equals(“”){
Toast.makeText(getBaseContext(),“未输入任何位置”,Toast.LENGTH_SHORT.show();
返回;
}
String url=“https:/