사용자는지도를 탭하여 마커를 추가해야합니다. 내 목표는 SQL 데이터베이스에 이름, 카테고리, 위도 및 경도를 보내는 것입니다. 나는이 튜토리얼을 따라 갔다 : https://www.youtube.com/watch?v=cOsZHuu8Qog. 앱이 작동하면 이 "등록 성공!"이라는 toast
을 얻습니다.이지만 데이터베이스 은 여전히 비어 있습니다.입니다.Android 앱에서 WAMP 데이터베이스에 데이터 저장 안 함
또한 내 앱과 WampServer 간의 통신에 문제가있을 수 있습니다. 연결 URL이 정확한지 궁금합니다. 나는 인터넷에서 기본 WAMP localhost IP이 10.0.2.2이거나 내 PC의 로컬 IP에서 작동 할 수 있음을 확인했습니다. 둘 다 작동하지 않았다.
init.phpAddShopActivity.java
public class AddShopActivity extends MainScreen implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
GoogleMap mGoogleMap;
GoogleApiClient mGoogleApiClient;
String Name, Category, Latitude, Longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_shop);
initMap();
spinner = (Spinner) findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.eidoskatastimatos, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
private void initMap() {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
LocationRequest mLocationsRequest;
@Override
public void onConnected(Bundle bundle) {
mLocationsRequest = LocationRequest.create();
mLocationsRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationsRequest.setInterval(5000);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationsRequest, this);
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
EditText shop_name = (EditText)findViewById(R.id.editName);
Spinner shop_category = (Spinner)findViewById(R.id.spinner);
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(latLng.latitude, latLng.longitude))
.draggable(true)
.title(shop_name.getText().toString())
.snippet(shop_category.getSelectedItem().toString());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 16);
mGoogleMap.animateCamera(update);
mGoogleMap.clear();
mGoogleMap.addMarker(marker);
Name = shop_name.getText().toString();
Category = shop_category.getSelectedItem().toString();
Latitude = String.valueOf(latLng.latitude);
Longitude = String.valueOf(latLng.longitude);
}
});
}
public void shopReg(View view)
{
String method = "save";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method, Name, Category, Latitude, Longitude);
finish();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
if (location == null){
Toast.makeText(this, "Can't get current location", Toast.LENGTH_LONG).show();
} else {
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 16);
mGoogleMap.animateCamera(update);
}
}
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String,Void,String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2/shop/register.php";
String method = params[0];
if(method.equals("save"))
{
String Name = params[1];
String Category = params[2];
String Latitude = params[3];
String Longitude = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("Name", "UTF-8") +"="+URLEncoder.encode(Name,"UTF-8")+"&"+
URLEncoder.encode("Category", "UTF-8") +"="+URLEncoder.encode(Category,"UTF-8")+"&"+
URLEncoder.encode("Latitude", "UTF-8") +"="+URLEncoder.encode(Latitude,"UTF-8")+"&"+
URLEncoder.encode("Longitude", "UTF-8") +"="+URLEncoder.encode(Longitude,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Το κατάστημα προστέθηκε!";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}
:
코드를 참조하십시오 백엔드 (PHP) 코드를 가정
<?php
$db_name="shops";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name);
?>
는 register.php
<?php
require"init.php";
$shop_name=$_POST["Name"];
$shop_category=$_POST["Category"];
$shop_latitude=$_POST["Latitude"];
$shop_longitude=$_POST["Longitude"];
$sql_query="insert into shop_info values('$shop_name','$shop_category','$shop_latitude','$shop_longidude');";
?>
안녕하세요, 여기에 여러 가지 문제가있는 것 같습니다. 먼저 모바일 앱과 호스트 된 WampServer가 동일한 네트워크에 있는지 확인하십시오. 그런 다음 Postman과 유사한 도구를 사용하여 등록 엔드 포인트가 작동하는지 확인하십시오. 두 가지 모두를 명확히 한 다음 모바일 앱 문제를 해결하려고합니다. –
@Ruchira Randana 나는 안드로이드 스튜디오의 기본 에뮬레이터를 사용한다. "우편 배달부"도구에 대해, 그것은 무엇입니까? 나는 그것을 사용한 적이 없다. 어디에서 찾을 수 있습니까? –
Postman은 Chrome 용이며 애드온입니다. 이를 사용하여 웹 서비스를 테스트 할 수 있습니다. CURL과 같은 다른 많은 유사한 도구가 있습니다. https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=ko –