dpdbu24262 2017-09-16 17:52
浏览 82
已采纳

AsyncTask在执行时执行崩溃应用程序

The user must add a marker by tapping the map. My goal is to send the Name, Category, Latitude and Longitude to a SQL database. I followed this issue: How can you pass multiple primitive parameters to AsyncTask?, but the app crashes when I hit the button which calls the shopReg. Also, maybe there is something wrong with the communication between my app and the WampServer. I wonder if the connection URL is correct. I found on the Internet that the default WAMP localhost IP is 10.0.2.2. See the code:

AddShopActivity.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;
Double 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 = latLng.latitude;
            Longitude = latLng.longitude;
        }
    });

}

public void shopReg(View view)
{
    String method = "save";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    new BackgroundTask(method,Name,Category,Latitude,Longitude).execute();
    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> {

String Name, Category;
Double Latitude, Longitude;

 BackgroundTask(String method, String Name, String Category, Double Latitude, Double Longitude) {
    this.Name = Name;
    this.Category = Category;
    this.Latitude = Latitude;
    this.Longitude = Longitude;
}

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];
        Double Latitude = Double.parseDouble(params[3]);
        Double Longitude = Double.parseDouble(params[4]);
        try {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(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(String.valueOf(Latitude),"UTF-8")+"&"+
            URLEncoder.encode("Longitude", "UTF-8") +"="+URLEncoder.encode(String.valueOf(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();
}
}

register.php

<?php
require"init.php";

$Name=$_POST["Name"];
$Category=$_POST["Category"];
$Latitude=$_POST["Latitude"];
$Longitude=$_POST["Longitude "];

$sql_query="insert into shop_info 
values('$Name','$Category','$Latitude','$Longidude');";

?>

init.php

<?php
$db_name="shops";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";

?>
  • 写回答

2条回答 默认 最新

  • dsfdgdsfd23212 2017-09-23 17:02
    关注

    Actually it was very obvious, but I didn't see it. The String method = "save";accepts only String type and I was trying to pass double with Latitude and Longitude. So I just turned doubles to Strings using;

     Latitude = String.valueOf(latLng.latitude);
     Longitude = String.valueOf(latLng.longitude);
    

    Thanks for help!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制