尝试使用Android Studio检索用户位置时出错

时间:2018-05-26 00:27:48

标签: android google-maps nullpointerexception location locationmanager

我想创建一个应用程序,使用Locaion manager获取坐标中的用户位置信息。问题是我的应用程序在运行时总是停止并且总是得到java.lang.NullPointerException

这是我的主要活动

package com.ionlab.project.volley; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.ionlab.project.volley.app.AppController; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.DateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity implements LocationListener { //location private TextView textView; private LocationManager locationManager; //waktu TextView textviewDate; Button buttonChoose; FloatingActionButton buttonUpload; Toolbar toolbar; ImageView imageView; EditText txt_name; EditText txt_item; Bitmap bitmap, decoded; int success; int PICK_IMAGE_REQUEST = 1; int bitmap_size = 60; // range 1 - 100 private static final String TAG = MainActivity.class.getSimpleName(); /* 10.0.2.2 adalah IP Address localhost Emulator Android Studio. Ganti IP Address tersebut dengan IP Address Laptop jika di RUN di HP/Genymotion. HP/Genymotion dan Laptop harus 1 jaringan! */ private String UPLOAD_URL = "http://192.168.1.4/android/upload_image/upload.php"; private static final String TAG_SUCCESS = "success"; private static final String TAG_MESSAGE = "message"; private String KEY_IMAGE = "image"; private String KEY_NAME = "name"; private String KEY_ITEM = "item"; private String KEY_LOKASI = "lokasi"; private String KEY_WAKTU = "waktu"; String tag_json_obj = "json_obj_req"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonChoose = (Button) findViewById(R.id.buttonChoose); buttonUpload = (FloatingActionButton) findViewById(R.id.buttonUpload); txt_name = (EditText) findViewById(R.id.editText); txt_item = (EditText) findViewById(R.id.editItem); imageView = (ImageView) findViewById(R.id.imageView); buttonChoose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showFileChooser(); } }); buttonUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uploadImage(); } }); //Calendar Calendar calendar = Calendar.getInstance(); String currenDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime()); textviewDate = findViewById(R.id.text_view_date); textviewDate.setText(currenDate); //textloc textView = (TextView) findViewById(R.id.id_textview); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 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(locationManager.NETWORK_PROVIDER); onLocationChanged(location); } public String getStringImage(Bitmap bmp) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, baos); byte[] imageBytes = baos.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); return encodedImage; } private void uploadImage() { //menampilkan progress dialog final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false); StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e(TAG, "Response: " + response.toString()); try { JSONObject jObj = new JSONObject(response); success = jObj.getInt(TAG_SUCCESS); if (success == 1) { Log.e("v Add", jObj.toString()); Toast.makeText(MainActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); kosong(); } else { Toast.makeText(MainActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } //menghilangkan progress dialog loading.dismiss(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //menghilangkan progress dialog loading.dismiss(); //menampilkan toast Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show(); Log.e(TAG, error.getMessage().toString()); } }) { @Override protected Map<String, String> getParams() { //membuat parameters Map<String, String> params = new HashMap<String, String>(); //menambah parameter yang di kirim ke web servis params.put(KEY_IMAGE, getStringImage(decoded)); params.put(KEY_NAME, txt_name.getText().toString().trim()); params.put(KEY_ITEM, txt_item.getText().toString().trim()); params.put(KEY_WAKTU, textviewDate.getText().toString().trim()); params.put(KEY_LOKASI, textView.getText().toString().trim()); //kembali ke parameters Log.e(TAG, "" + params); return params; } }; AppController.getInstance().addToRequestQueue(stringRequest, tag_json_obj); } private void showFileChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri filePath = data.getData(); try { //mengambil fambar dari Gallery bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); // 512 adalah resolusi tertinggi setelah image di resize, bisa di ganti. setToImageView(getResizedBitmap(bitmap, 512)); } catch (IOException e) { e.printStackTrace(); } } } private void kosong() { imageView.setImageResource(0); txt_name.setText(null); txt_item.setText(null); } private void setToImageView(Bitmap bmp) { //compress image ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes); decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray())); //menampilkan gambar yang dipilih dari camera/gallery ke ImageView imageView.setImageBitmap(decoded); } // fungsi resize image public Bitmap getResizedBitmap(Bitmap image, int maxSize) { int width = image.getWidth(); int height = image.getHeight(); float bitmapRatio = (float) width / (float) height; if (bitmapRatio > 1) { width = maxSize; height = (int) (width / bitmapRatio); } else { height = maxSize; width = (int) (height * bitmapRatio); } return Bitmap.createScaledBitmap(image, width, height, true); } @Override public void onLocationChanged(Location location) { double longitude = location.getLongitude(); double latitude = location.getLatitude(); textView.setText("Longitude:" + longitude + "\n" + "Latitude:" + latitude); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }

我还确保我的Android清单正确

我花了很多时间试图解决这个问题,浏览了很多关于这个主题的网页,尝试了我自己的不同代码。 它仍然会发生。我是Android的初学者。拜托,请帮助我。有没有办法解决我的问题?

这是我的logcat LogCat

1 个答案:

答案 0 :(得分:1)

首先,您应该将logcat以文本形式包含在您的问题中!

但是,从我从屏幕截图中可以看到的问题是onLocationChanged()方法。检查&#34; location&#34;在尝试阅读之前查看它是否为null

@Override
 public void onLocationChanged(Location location) {
    if(location != null){
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();

        textView.setText("Longitude:" + longitude + "\n" + "Latitude:" + latitude);
    }
    else{
        Log.e(TAG, "onLocationChanged -- location is null!");
    }
}

注意:

万一你不知道&#34; TAG&#34;通常会添加到大多数Android类的开头,如下所示:

public class MainActivity extends AppCompatActivity implements LocationListener {

      private static final String TAG = MainActivity.class.getSimpleName();

为什么MainActivity.class.getSimpleName()而不仅仅是&#34; MainActivity&#34;?因为如果您重构代码,那么名称将自动更改。

修改

您是否在清单文件中添加了必要的权限?

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps"/>