존경하는 회원, 나는 기본적인 Google지도 응용 프로그램을 작성하고 있습니다. GPS 체크, 인터넷 체크, 인터넷 체크 등이 기능을 구현했습니다. 방금 하나의 단일 위성 유형 맵을 사용하여 상단에 옵션 메뉴를 추가했습니다. 필자는 정확한 코드를 기록했지만지도보기를 변경하려면 위성 옵션을 클릭 할 때마다 앱이 닫힙니다. 터미널에 오류가 표시되지 않습니다. 앱이 다른 모든 작업에 적합합니다. 특정지도 유형을로드하는 대신 내 앱을 닫는 것이 잘못되어 있는지 파악할 수 없습니다.위성지도 유형이 작동하지 않습니다.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/SatelliteType"
android:title="@string/satellite"/>
</menu>
다음은 자바 코드 : 다음 내 main_menu XML 리소스 파일입니다. 나는이 코딩 실제로 내 실수/단점을 이해하는 것이 더 명확하게 일을 자세히 설명 할 필요가 있으면 알려 주시기 바랍니다 :
는package com.example.Test;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.maps.CameraUpdateFactory;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.net.InetAddress;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
GoogleMap googleMap;
private static final int ERROR_DIALOG_REQUEST = 9901;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//****************************Checking the GPS at start*******************
final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
} else {
showGPSDisabledAlertToUser();
}
//********Checking the Google Play Services at start*********
if (ServicesOK()) {
Toast.makeText(this, "CONNECTED to Google Play Services", Toast.LENGTH_SHORT).show();
}
//****************************Checking the NETWORKING DEVICE at start*******************
if (isConnected()) {
Toast.makeText(this, "CONNECTED to NETWORKING DEVICE", Toast.LENGTH_SHORT).show();
}
//****************************Checking the INTERNET SERVICE at Start*******************
if (isInternetAvailable()) {
Toast.makeText(this, "CONNECTED to INTERNET", Toast.LENGTH_SHORT).show();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//****************************When MAP is perfectly LOADED*******************
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in CIITLAHORE and move the camera
LatLng ciitlahore = new LatLng(31.400693, 74.210941);
googleMap.addMarker(new MarkerOptions().position(ciitlahore).title("Marker in CIIT LAHORE"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(ciitlahore));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//****************************Making MENU Option******************
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//Add menu handling code
switch (id) {
case R.id.SatelliteType:
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return (true);
default :
return super.onOptionsItemSelected(item);
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//****************************METHOD for checking GOOGLE PLAY SERVICES*************************
public boolean ServicesOK() {
int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if (resultCode == ConnectionResult.SUCCESS) {
return true;
} else {
GoogleApiAvailability.getInstance().getErrorDialog(this, resultCode, ERROR_DIALOG_REQUEST).show();
Toast.makeText(this, "Can't connect to mapping services", Toast.LENGTH_SHORT).show();
}
return false;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//****************************METHOD for checking INTERNET AVAILABLE*************************
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
return !ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
//****************************METHOD for checking INTERNET CONNECTIVITY*************************
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
Toast.makeText(this, "WIFI CONNECTION AVAILABLE", Toast.LENGTH_SHORT).show();
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
Toast.makeText(this, "CELLULAR CONNECTION AVAILABLE", Toast.LENGTH_SHORT).show();
}
} else {
// not connected to the internet
Toast.makeText(this, "NOT CONNECTED to any working INTERNET service", Toast.LENGTH_SHORT).show();
}
return false;
}
//****************************GPS DIALOGUE BOX*************************
private void showGPSDisabledAlertToUser() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finishAffinity();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++ END +++++++++++++++++++++++++++++++++++++++++++++++
}
이것이 문제 였지만 이제는 정상적으로 작동합니다. 답변을 많이 주셔서 감사합니다 :) 그렇다면이 실수를 이용하여 프로그래밍에서 NULL이 아니거나 중요한 시나리오에서만 객체가 있는지 항상 확인해야합니까? –
주제에 관해서는 매우 흥미로운 토론이 있습니다. 다음을 확인하십시오. http://stackoverflow.com/questions/271526/avoiding-null-statements – antonio