携帯電話の内部ストレージにアクセスして、内部ストレージからファイルを添付しようとしています。しかし、とにかく、例外 "java.lang.NullPointerException:uri at com.android.internal.util.Preconditions.checkNotNull"が発生しています。 getCountメソッドがnullでないことを確認しました。しかし、まだ、私はこの問題に直面しています。私は何をしますか?Preconditions.checkNotNull Androidヌルポインタ例外
**Code:**
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
public class User_Issue extends AppCompatActivity {
EditText estoreissue, estorename, edescribe;
Button b, btupload;
RequestQueue requestQueue;
TextView tvupload;
private static final int IMAGE_REQUEST_CODE = 3;
private static final int STORAGE_PERMISSION_CODE = 123;
private ImageView imageView;
private EditText etCaption;
private Uri filePath;
Bitmap bitmap;
int serverResponseCode = 0;
//final String uploadFilePath = "/mnt/Environment.getRootDirectory().getAbsolutePath()/";
//final String uploadFileName = "";
String upLoadServerUri = null;
// Create string variable to hold the Edit\Text Value.
String issue, storename, describe;
// Creating Progress dialog.
ProgressDialog progressDialog;
String HttpUrl = "http://10.238.4.153/user_issue.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user__issue);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imageView = (ImageView)findViewById(R.id.imupload);
etCaption = (EditText)findViewById(R.id.etupload);
tvupload = (TextView) findViewById(R.id.tvupload);
estorename = (EditText) findViewById(R.id.editTextstorename);
estoreissue = (EditText) findViewById(R.id.editTextissue);
edescribe = (EditText) findViewById(R.id.editTextdescribe);
b = (Button) findViewById(R.id.button3);
btupload = (Button) findViewById(R.id.buttonupload);
tvupload.setText("Uploading File : 'mnt/Environment.getRootDirectory().getAbsolutePath()/" + "'");
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
requestStoragePermission();
// Creating Volley newRequestQueue .
requestQueue = Volley.newRequestQueue(User_Issue.this);
progressDialog = new ProgressDialog(User_Issue.this);
btupload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v==imageView)
{
Intent in=new Intent();
in.setType("imupload/*");
in.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(in, "Complete action using"), IMAGE_REQUEST_CODE);
}else if(v == btupload){
uploadMultipart();
}
}
});
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog.setMessage("Please wait, while we upload your data to server");
progressDialog.show();
GetValueFromEditText();
// Creating string request with post method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing response message coming from server.
Toast.makeText(User_Issue.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Hiding the progress dialog after all task complete.
progressDialog.dismiss();
// Showing error message if something goes wrong.
Toast.makeText(User_Issue.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("storename", storename);
params.put("issue", issue);
params.put("describ", describe);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(User_Issue.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
}
});
}
// Creating method to get value from EditText.
public void GetValueFromEditText() {
storename = estorename.getText().toString().trim();
issue = estoreissue.getText().toString().trim();
describe = edescribe.getText().toString().trim();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
tvupload.setText("Path: ". concat(getPath(filePath)));
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void uploadMultipart() {
String caption = etCaption.getText().toString().trim();
//getting actual path
String path = getPath(filePath);
//uploading <code>
try {
String uploadID= UUID.randomUUID().toString();
new MultipartUploadRequest(this, uploadID, HttpUrl)
.addFileToUpload(path, "image") //Adding file
.addParameter("caption", caption) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public String getPath(Uri uri) {
Cursor cursor=null;
cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor!=null && cursor.getCount()>0) {
cursor.moveToFirst();
}
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
if(cursor!=null && cursor.getCount()>0) {
cursor.moveToFirst();
}
//cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
}として
Logcat:
FATAL EXCEPTION: main
Process: com.example.mi.mikpiadmin, PID: 14255
java.lang.NullPointerException: uri
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
at android.content.ContentResolver.query(ContentResolver.java:474)
at android.content.ContentResolver.query(ContentResolver.java:434)
at com.example.mi.mikpiadmin.User_Issue.getPath(User_Issue.java:204)
at com.example.mi.mikpiadmin.User_Issue.uploadMultipart(User_Issue.java:187)
at com.example.mi.mikpiadmin.User_Issue$2.onClick(User_Issue.java:101)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
クラッシュログを追加してください – nomag