简体   繁体   English

应用程序可在模拟器中运行,但在真实设备中崩溃

[英]App works in emulator but crashes in real device

I have an app that shows user's current location on google map, the app runs in emulator (though it doesn't show location) however it crashes in real device. 我有一个可以在google map上显示用户当前位置的应用程序,该应用程序在模拟器中运行(尽管它不显示位置),但是在真实设备中崩溃。 Here is the error I'm getting 这是我遇到的错误

01-04 15:00:59.509 26494-26494/io.xgear.geotag E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{io.xgear.geotag/io.xgear.geotag.MainActivity}: java.lang.NullPointerException 01-04 15:00:59.509 26494-26494 / io.xgear.geotag E / AndroidRuntime:致命例外:main java.lang.RuntimeException:无法启动活动ComponentInfo {io.xgear.geotag / io.xgear.geotag.MainActivity }:java.lang.NullPointerException

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659) 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)

at android.app.ActivityThread.access$1500(ActivityThread.java:121) 在android.app.ActivityThread.access $ 1500(ActivityThread.java:121)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:943)

at android.os.Handler.dispatchMessage(Handler.java:99) 在android.os.Handler.dispatchMessage(Handler.java:99)

at android.os.Looper.loop(Looper.java:130) 在android.os.Looper.loop(Looper.java:130)

at android.app.ActivityThread.main(ActivityThread.java:3701) 在android.app.ActivityThread.main(ActivityThread.java:3701)

at java.lang.reflect.Method.invokeNative(Native Method) 在java.lang.reflect.Method.invokeNative(本机方法)

at java.lang.reflect.Method.invoke(Method.java:507) 在java.lang.reflect.Method.invoke(Method.java:507)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:866)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)

at dalvik.system.NativeStart.main(Native Method) 在dalvik.system.NativeStart.main(本机方法)

Caused by: java.lang.NullPointerException 造成原因:java.lang.NullPointerException

at io.xgear.geotag.MainActivity.onCreate(MainActivity.java:72) 在io.xgear.geotag.MainActivity.onCreate(MainActivity.java:72)

at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623) 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)

at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)

at android.app.ActivityThread.access$1500(ActivityThread.java:121) 在android.app.ActivityThread.access $ 1500(ActivityThread.java:121)

at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:943)

at android.os.Handler.dispatchMessage(Handler.java:99) 在android.os.Handler.dispatchMessage(Handler.java:99)

at android.os.Looper.loop(Looper.java:130) 在android.os.Looper.loop(Looper.java:130)

at android.app.ActivityThread.main(ActivityThread.java:3701) 在android.app.ActivityThread.main(ActivityThread.java:3701)

at java.lang.reflect.Method.invokeNative(Native Method) 在java.lang.reflect.Method.invokeNative(本机方法)

at java.lang.reflect.Method.invoke(Method.java:507) 在java.lang.reflect.Method.invoke(Method.java:507)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:866)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)

at dalvik.system.NativeStart.main(Native Method) 在dalvik.system.NativeStart.main(本机方法)

and here's my code for main activity 这是我主要活动的代码

package io.xgear.geotag;


import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import android.support.v4.app.Fragment;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import io.xgear.geotag.helper.Post;

public class MainActivity extends FragmentActivity implements LocationListener {
    GoogleMap googleMap;
    private GeoTagTask mAuthTask = null;
    //GPSTracker gps;
    private JSONObject jsonObj;

    // UI references.
    private EditText txtShopCode;
    private EditText lblAddress;
    private View mProgressView;
    private View mGeoTagForm;
    private Button btnGeoTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_main);

        txtShopCode = (EditText) findViewById(R.id.txtShopCode);
        btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
        mGeoTagForm = (View) findViewById(R.id.geoTagForm);
        mProgressView = findViewById(R.id.geoTagProgress);
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        setContentView(R.layout.activity_main);
        SupportMapFragment supportMapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
        googleMap = supportMapFragment.getMap();
        googleMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
        }
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

       // gps = new GPSTracker(MainActivity.this);
        btnGeoTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String shopid = txtShopCode.getText().toString();
                boolean cancel = false;
                View focusView = null;

               //txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);

                if (TextUtils.isEmpty(shopid)) {
                    txtShopCode.setError(getString(R.string.error_field_required));
                    focusView = txtShopCode;
                    cancel = true;

                }
                else {


                    showProgress(true);
                    mAuthTask = new GeoTagTask(shopid);
                    mAuthTask.execute((Void) null);
                }
            }

        });

    }


//
//    public void btnGeoTag_Click(View v){
//
//    }
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
            mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
        private final String shopCode;
       // private String lat= Double.toString( gps.getLatitude());
      //  private String lng = Double.toString( gps.getLongitude());
       Location location;
        private String lat = Double.toString(location.getLatitude());
        private String lng = Double.toString(location.getLongitude());
       // double longitude = location.getLongitude();
        private boolean isConnect;
        GeoTagTask(String shopId) {
            shopCode = shopId;
            isConnect = false;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean res = false;
     try {
                ContentValues nameValuePairs = new ContentValues();
                nameValuePairs.put("Id", shopCode);
                nameValuePairs.put("lat", lat);
                nameValuePairs.put("lng", lng);
         //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
               Log.i("Latitude", lat+"");

                Post post = new Post(getApplicationContext());
                String result = "";
//                isConnect = post.isConnected();
  //              if(isConnect) {
                    result = post.doPost(nameValuePairs);
                    jsonObj = new JSONObject(result);
                    Log.i("Result", result+"");
                    if(jsonObj.getInt("success") == 1)
                        res = true;
    //            }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return res;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
//                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//                intent.putExtra("jsonObj", jsonObj.toString());
//                startActivity(intent);
                txtShopCode.getText().clear();
                txtShopCode.requestFocus();
                Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();

            } else {
//                if(isConnect){
//                    mPasswordView.setError(getString(R.string.error_incorrect_password));
//                    mPasswordView.requestFocus();

//                }
//                else
                    Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        googleMap.addMarker(new MarkerOptions().position(latLng));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

}

why is google map null? 为什么Google Map为null? I'm using API in my meta deta 我在元数据中使用API

在此处输入图片说明

Change you or on create to start with 更改您或在创建时以

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

Remove additional setContentView calls. 删除其他setContentView调用。

Use getMapAsyc to handle asynchronous map initialization: 使用getMapAsyc处理异步地图初始化:

SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
supportMapFragment.getMapAsync(new OnMapReadyCallback(){
    @Override
    public void onMapReady(final GoogleMap map) {
        map.setMyLocationEnabled(true);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 应用在模拟器上崩溃,但可以在真实设备上运行 - App crashes on emulator but it works on real device 应用程序在模拟器中运行但在真实设备上崩溃 - App works in emulator but crashes on a real device Android Studio 应用程序在真实设备上崩溃,但可在模拟器上运行 - Android Studio app crashes on real device, but works on emulator Android应用程式可在模拟器上正常运作,但在真实装置中当机 - Android app works fine in emulator but crashes in real device 应用程序可在模拟器上运行,在设备上崩溃 - App works on emulator, crashes on device 应用程序可在模拟器上运行,但不能在真实设备上运行 - App works on emulator but not real device 应用程序可在模拟器中运行,但不能在真实设备上运行 - App works in Emulator, but not on a real device 应用程序可以在模拟器上运行,但不能在真实设备上运行 - App works on emulator but not on real device Android 应用程序在少数真实设备上崩溃,但在与真实设备具有相同 API 的模拟器上运行良好 - Android app crashes on few real devices but works fine on an emulator which has the same API as that of the real device 应用程序在模拟器上运行正常,但在真实设备上崩溃 - App runs fine on emulator, but crashes on real device
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM