I am trying to access my phone's internal storage to attach a file from internal storage. But anyhow I am getting an exception "java.lang.NullPointerException: uri at com.android.internal.util.Preconditions.checkNotNull". I have checked getCount method is not null. But still, i am facing this issue. what do I do?
**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)
check Access permissions as required
Also make sure to use .checkDirExists() to see file availablity
You should make sure that filePath is not null before using it with getContentResolver().query()
Related
I'm trying to add data to a document to Firebase Firestore. I've added a collection named users to it. Also, the read/write permissions are open for now. I'm following this doc. And I'm not able to add data to document only on this Activity. on other activity, I can add data easily
Here is my Code:
package com.example.ewulife;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.annotations.Nullable;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener {
Button next;
FirebaseFirestore fstore;
FirebaseAuth fAuth;
String userID;
Spinner bloodgroup;
RadioGroup radioGroup;
RadioButton gender;
ArrayList<String> arrayList_blood;
ArrayAdapter<String> rr_blood;
EditText fullname,Mobile,credit,semister,cgpa;
String Fullname, Blood, Gender;
ImageView condition, upload;
CircleImageView profile_image;
StorageReference storageReference;
double cred2,semi2,cgpa2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_info);
fAuth = FirebaseAuth.getInstance();
fstore = FirebaseFirestore.getInstance();
userID = fAuth.getCurrentUser().getUid();
storageReference = FirebaseStorage.getInstance().getReference();
bloodgroup = findViewById(R.id.spinner00);
fullname = findViewById(R.id.editTextTextPersonName00);
Mobile =findViewById(R.id.editTextTextPersonName200);
next = findViewById(R.id.button1300);
upload = findViewById(R.id.imageView1600);
profile_image = findViewById(R.id.profile_image300);
credit = findViewById(R.id.editTextNumber);
semister = findViewById(R.id.editTextNumberDecimal);
cgpa = findViewById(R.id.editTextNumberDecimal2);
profile_image.setOnClickListener(this);
upload.setOnClickListener(this);
next.setOnClickListener(this);
{
radioGroup = findViewById(R.id.gender00);
arrayList_blood = new ArrayList<>();
arrayList_blood.add("Select");
arrayList_blood.add("BBA");
arrayList_blood.add("BSS in Economics");
arrayList_blood.add("BA in English");
arrayList_blood.add("LL.B (Hon’s)");
arrayList_blood.add("BSS in Sociology");
arrayList_blood.add("BSS in ISLM");
arrayList_blood.add("BS in Applied Statistics");
arrayList_blood.add("B.Sc. in ETE");
arrayList_blood.add("B.Sc. in ICE");
arrayList_blood.add("B.Sc. in CSE");
arrayList_blood.add("B.Sc. in EEE");
arrayList_blood.add("B.Pharm.");
arrayList_blood.add("B.Sc. in GEB");
arrayList_blood.add("B.Sc. in Civil Engineering");
arrayList_blood.add("B.Sc. in ECE");
arrayList_blood.add("Select");
arrayList_blood.add("MBA");
arrayList_blood.add("EMBA");
arrayList_blood.add("MDS");
arrayList_blood.add("MSS in Economics");
arrayList_blood.add("MA in English");
arrayList_blood.add("MA in ELT");
arrayList_blood.add("LL.M");
arrayList_blood.add("MPRHGD");
arrayList_blood.add("PPDM");
arrayList_blood.add("MS in Applied Statistics");
arrayList_blood.add("MS in TE");
arrayList_blood.add("MS in CSE");
arrayList_blood.add("MS in APE");
arrayList_blood.add("M. Pharm");
}
rr_blood = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList_blood);
bloodgroup.setAdapter(rr_blood);
int selectedId = radioGroup.getCheckedRadioButtonId();
gender = findViewById(selectedId);
StorageReference profRef = storageReference.child("ewuuser/"+userID+"profile.jpg");
profRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profile_image);
//Picasso.get().load(uri).into(edit_pic);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #androidx.annotation.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
Uri imageuri = data.getData();
profile_image.setImageURI(imageuri);
//back_pic.setImageURI(imageuri);
uploadImageToFirebase(imageuri);
}
}
}
private void uploadImageToFirebase(Uri imageUri) {
//upload
final StorageReference fileRef = storageReference.child("ewuuser/" + userID + "profile.jpg");
fileRef.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profile_image);
//Picasso.get().load(uri).into(back_pic);
//progressBar_prof.setVisibility(View.GONE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#androidx.annotation.NonNull Exception e) {
Toast.makeText(UserInfoActivity.this, "File is not Uploaded" + e, Toast.LENGTH_SHORT).show();
//progressBar_prof.setVisibility(View.GONE);
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.imageView1600) {
Intent openGalery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalery, 1000);
}
if (v.getId() == R.id.button1300) {
int selectedId = radioGroup.getCheckedRadioButtonId();
gender = findViewById(selectedId);
final String name = fullname.getText().toString();
final String number = Mobile.getText().toString();
if (name.isEmpty()) {
fullname.setError("Name Required");
return;
}
if (gender == null) {
Toast.makeText(UserInfoActivity.this, "Selected Gender", Toast.LENGTH_SHORT).show();
return;
}
String blood_group = bloodgroup.getSelectedItem().toString();
if (blood_group.equals("Select")) {
Toast.makeText(UserInfoActivity.this, "Selected Department", Toast.LENGTH_SHORT).show();
return;
}
String gen = gender.getText().toString();
final String cre = credit.getText().toString();
if(cre.isEmpty()){
credit.setError("Enter Valid Credit");
Toast.makeText(UserInfoActivity.this, "Enter Valid Credit or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
if((Double.parseDouble(cre))>200){
credit.setError("Enter valid Credit");
Toast.makeText(UserInfoActivity.this, "Enter valid CGPA or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
final String semi = semister.getText().toString();
if(semi.isEmpty()){
semister.setError("Enter valid semister");
Toast.makeText(UserInfoActivity.this, "Enter valid Semister or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
if((Double.parseDouble(semi))>20){
semister.setError("Enter valid Semister");
Toast.makeText(UserInfoActivity.this, "Enter valid CGPA or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
final String cgpa1 = cgpa.getText().toString();
if(cgpa1.isEmpty()){
cgpa.setError("Enter valid CGPA");
Toast.makeText(UserInfoActivity.this, "Enter valid CGPA or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
if((Double.parseDouble(cgpa1))>4){
cgpa.setError("Enter valid CGPA");
Toast.makeText(UserInfoActivity.this, "Enter valid CGPA or leave it blank if you are new", Toast.LENGTH_SHORT).show();
return;
}
final DocumentReference documentReference3 = fstore.collection("EWU_student").document(userID);
//here error 242 // documentReference3.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot1, #Nullable FirebaseFirestoreException e2) {
Map<String, Object> user1 = new HashMap<>();
user1.put("Name",name);
user1.put("EWU_ID",number);
user1.put("Credit",cre);
user1.put("Semister",semi);
user1.put("Program",blood_group);
user1.put("Gender",gen);
user1.put("USER ID",userID);
user1.put("Drop",'0');
// user1.put("Profile Photo","ewuuser/"+userID+"profile.jpg");
user1.put("CGPA",cgpa1);
//here error show 260// documentReference3.set(user1).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(UserInfoActivity.this, "User Updated" + userID, Toast.LENGTH_LONG).show();
Intent intent = new Intent(UserInfoActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UserInfoActivity.this, "User not updated 3 " + e.toString(), Toast.LENGTH_LONG).show();
}
});
}
});
}
}
}
In Logs I see only these thing and can not under the problem:
2021-03-20 15:15:05.637 8348-8348/com.example.ewulife E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ewulife, PID: 8348
java.lang.IllegalArgumentException: Could not serialize object. Characters are not supported, please use Strings (found in field 'Drop')
at com.google.firebase.firestore.util.CustomClassMapper.serializeError(CustomClassMapper.java:555)
at com.google.firebase.firestore.util.CustomClassMapper.serialize(CustomClassMapper.java:133)
at com.google.firebase.firestore.util.CustomClassMapper.serialize(CustomClassMapper.java:140)
at com.google.firebase.firestore.util.CustomClassMapper.serialize(CustomClassMapper.java:104)
at com.google.firebase.firestore.util.CustomClassMapper.convertToPlainJavaTypes(CustomClassMapper.java:78)
at com.google.firebase.firestore.UserDataReader.convertAndParseDocumentData(UserDataReader.java:231)
at com.google.firebase.firestore.UserDataReader.parseSetData(UserDataReader.java:75)
at com.google.firebase.firestore.DocumentReference.set(DocumentReference.java:167)
at com.google.firebase.firestore.DocumentReference.set(DocumentReference.java:147)
**at com.example.ewulife.UserInfoActivity$4.onEvent(UserInfoActivity.java:260)
at com.example.ewulife.UserInfoActivity$4.onEvent(UserInfoActivity.java:242)**
at com.google.firebase.firestore.DocumentReference.lambda$addSnapshotListenerInternal$2(DocumentReference.java:505)
at com.google.firebase.firestore.DocumentReference$$Lambda$3.onEvent(Unknown Source:6)
at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(AsyncEventListener.java:42)
at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
the error part is
**at com.example.ewulife.UserInfoActivity$4.onEvent(UserInfoActivity.java:260)
at com.example.ewulife.UserInfoActivity$4.onEvent(UserInfoActivity.java:242)**
**There are the sreenshot 1
There are the screenshot 2
**
Write this code user1.put("Drop","0") instead of this
user1.put("Drop",'0')
i know that quastion has asked lot of times, but im realy dont found solution.
i know the error come couse the object intent is null, but how? if i choose a picture from a gallery?
this is the the error i get
E/Volley: [497] NetworkDispatcher.processRequest: Unhandled exception java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at java.net.URLEncoder.encode(URLEncoder.java:205)
at com.android.volley.Request.encodeParameters(Request.java:491)
at com.android.volley.Request.getBody(Request.java:477)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:245)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:219)
at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:97)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
D/EGL_emulation: eglMakeCurrent: 0xa7685060: ver 3 1 (tinfo 0xa7683280)
D/EGL_emulation: eglMakeCurrent: 0xa7685060: ver 3 1 (tinfo 0xa7683280)
this is my intent object part:
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dexter.withActivity(uploadimage.this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select image"),1);
}
when i came to this part of the code, its fall, couse intent is null? but why is like that?
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==1 && requestCode==RESULT_OK && data!= null){
Uri filePath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filePath);
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
imageStore(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
what can be the problem?
i add to manifest the permission of READ_EXTERNAL_STORAGE .
this is all my code, if its relevant.
package com.example.yacovapp;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.toolbox.StringRequest;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
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.Volley;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import android.util.Base64;
public class uploadimage extends AppCompatActivity {
Button btnSelectImage, btnUploadImage;
ImageView imageView;
Bitmap bitmap;
String encodedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploadimage);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);
btnUploadImage = (Button) findViewById(R.id.buttonUploadImage);
imageView = findViewById(R.id.imView);
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dexter.withActivity(uploadimage.this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select image"),1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) { }
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { }
}).check();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, "https://kerron.xyz/htdocs/images.php"
, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(uploadimage.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(uploadimage.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map <String, String> param = new HashMap<>();
param.put("image", encodedImage);
return param;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(uploadimage.this);
requestQueue.add(request);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode==1 && requestCode==RESULT_OK && data!= null){
Uri filePath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filePath);
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
imageStore(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void imageStore(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte [] imageBytes = stream.toByteArray();
encodedImage = android.util.Base64.encodeToString(imageBytes,Base64.DEFAULT);
}
}
php file: (on server in the folder of public_html i create a folder htdocs and in this folder i have all my php files of the project)
<?php
$conn = mysqli_connect("78.140.191.36","kerronxy_yacov", "]k2oIl?WBRPh", "kerronxy_users");
if(isset($_POST['image'])) {
$target_dir = "htdocs/";
$image = $_POST['image'];
$imageStore = rand()."_".time()."jpeg";
$target_dir = $target_dir."/".$imageStore;
file_put_contents($target_dir, base64_decode($image));
$select = "INSERT INTO images (image) VALUES ($imageStore)";
$responce = mysqli_query($conn, $select);
if($responce) {
echo "Image Uploaded";
mysqli_close($conn);
}
}
The Logcat error indicates Nullpointer exception means that some of the variable are null at runtime.
You might have put some null value or key in your post parameters.Please make sure your postParams in your case
encodedImage is notnull before calling the request,because the keys or values that is returned from these methods should not be null.
Hope this helps..
Ia trying to get user locations whenever its login the application.I made a class and its working perfect seperately but when I embed it in my main project it didnt submit the location values in database.I want that whenever user login that class run for only once and submits its coordinates in database.
Here Is the code of my location class :
I want that when user login this class class run for once only all I want is to get user location when its loged in.
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
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.util.HashMap;
import java.util.Map;
public class getposition extends AppCompatActivity {
String URL_LOGIN = "api"
Button btn;
TextView tv1,tv2;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
String lg, lt , chk;
String lat_long;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getposition);
btn = findViewById(R.id.send);
tv1 = findViewById(R.id.lang);
tv2 = findViewById(R.id.lat);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
chk = getLocation();
loadlocation();
if(chk != "false"){
String foo = chk;
String[] split = foo.split("_");
lt = split[0];
lg = split[1];
Toast.makeText(getApplicationContext(),chk,Toast.LENGTH_LONG).show();
}
}
private void loadlocation() {
final RequestQueue requestQueue = Volley.newRequestQueue(getposition.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tv1.setText(response);
tv2.setText(response);
requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv1.setText("Something went wrong///");
error.printStackTrace();
requestQueue.stop();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id","12" );
params.put("user_lat", lt);
params.put("user_lng", lg);
return params;
}
};
VolleySingleton.getInstance(getposition.this).addToRequestQueue(stringRequest);
}
public String getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double latt = location.getLatitude();
double lng = location.getLongitude();
lat_long = latt + "_" + lng;
tv1.setText("Latitude: " + latt);
tv2.setText("Longitude: " + lng);
} else {
lat_long = "false";
tv1.setText("Unable to find correct location.");
tv2.setText("Unable to find correct location. ");
}
}
return lat_long;
}
}
This is my login class:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.vshine.neuron.riseshine.VolleySingleton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.vshine.neuron.riseshine.MainActivity;
import com.vshine.neuron.riseshine.R;
import com.vshine.neuron.riseshine.getregistered;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class login extends AppCompatActivity {
Button login_button;
ImageButton GetRegistered;
EditText userName_edt, password_edt;
String user_name, password;
Context mctx;
String json_response;
String URL_LOGIN = "api"
public static final String PREFS_NAME = "MyPreferenceFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mctx = this;
initBasic();
initLogin();
}
private void initBasic() {
login_button = (Button) findViewById(R.id.login_button);
GetRegistered = (ImageButton) findViewById(R.id.register);
userName_edt = (EditText) findViewById(R.id.user_name);
password_edt = (EditText) findViewById(R.id.password);
}
private void initLogin() {
GetRegistered.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(login.this,getregistered.class);
startActivity(intent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_name = userName_edt.getText().toString();
password = password_edt.getText().toString();
if (user_name.trim().equals("") || password.trim().equals("")) {
ShowToastMessage("Please enter the credentials properly");
}
else {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
// json_response = j_obj.getString("message");
if (response!= null) {
// Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
json_response = obj.getString("message");
// ShowToastMessage(json_response);
//getting the user from the response
JSONObject userJson = obj.getJSONObject("response");
//creating a new user object
String u_id = String.valueOf(userJson.getInt("id"));
// ShowToastMessage(u_id);
//storing the user in shared preferences
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("User_id", u_id);
editor.commit();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_name", user_name);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(login.this).addToRequestQueue(stringRequest);
}
}
});
}
private void ShowToastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
I am a newbie to the android world. I am trying to develop an app for my school project and stumble upon this issue. please someone help me.
My fragment code is bellow. Where I want to fill up a form with Image and upload to PHP, Mysql server for registration. But the app is crashing.
package com.dgdev.mtmicds;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dgdev.mtmicds.DbAccess.Remote.APIClient;
import com.dgdev.mtmicds.DbAccess.Remote.ApiInterface;
import com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.app.Activity.RESULT_OK;
import static android.provider.MediaStore.Images.Media.*;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;
/**
* A simple {#link Fragment} subclass.
*/
public class ProfileFragment extends Fragment {
View view;
AppCompatImageView imageView;
AppCompatEditText etFullname, etEmail, etDob, etMobile, etPsw, etRePsw, etAddr;
AppCompatButton btnRegister, btnCancel;
private static final int IMAGE_REQUEST = 7777;
Bitmap bitmap;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
imageView = (AppCompatImageView) view.findViewById(R.id.ProfileDP);
etFullname = (AppCompatEditText) view.findViewById(R.id.tvfullanme);
etEmail = (AppCompatEditText) view.findViewById(R.id.tvemail);
etDob = (AppCompatEditText) view.findViewById(R.id.tvdob);
etPsw = (AppCompatEditText) view.findViewById(R.id.tvpsw);
etRePsw = (AppCompatEditText) view.findViewById(R.id.tvpsw_re);
etAddr = (AppCompatEditText) view.findViewById(R.id.tvaddr);
etMobile = (AppCompatEditText) view.findViewById(R.id.tvmobile);
btnRegister = (AppCompatButton) view.findViewById(R.id.btnRegister);
btnCancel = (AppCompatButton) view.findViewById(R.id.btnCancel);
/*-----------------------------------------------------------------------------*/
/* this onClickListener will be responsible for getting image URI from gallery */
/*-----------------------------------------------------------------------------*/
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImageFromGallery();
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
return view;
}
private void uploadData() {
String fullname = etFullname.getText().toString();
String dob = convertTOMysqlDate(etDob.getText().toString());
String mobile = etMobile.getText().toString();
String addr = etAddr.getText().toString();
String psw = etPsw.getText().toString();
String prof_pic = imageToString();
Toast.makeText(view.getContext(), dob, Toast.LENGTH_LONG).show();
ApiInterface apiInterface = APIClient.GetClient().create(ApiInterface.class);
Call<UserRegistrationModel> call = apiInterface.RegisterUser(fullname, dob, mobile, addr, psw, prof_pic);
call.enqueue(new Callback<UserRegistrationModel>() {
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
UserRegistrationModel res = response.body();
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<UserRegistrationModel> call, Throwable t) {
Toast.makeText(view.getContext(), "You are not able to talk to server!", Toast.LENGTH_LONG).show();
}
});
}
private String convertTOMysqlDate(String s) {
String $MysqlDateString;
String[] DateParts = s.split("/");
$MysqlDateString = DateParts[2] + "-" + DateParts[1] + "-" + DateParts[0];
return $MysqlDateString;
}
private void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = getBitmap(getActivity().getApplicationContext().getContentResolver(), path);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String imageToString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, outputStream);
byte[] ImageBytes = outputStream.toByteArray();
return Base64.encodeToString(ImageBytes, Base64.DEFAULT);
}
}
And I am getting bellow message in logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel.getStatus()' on a null object reference
at com.dgdev.mtmicds.ProfileFragment$3.onResponse(ProfileFragment.java:105)
Please Help me...I am a newbie...
Try this
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
if(response.isSuccessful()) {
UserRegistrationModel res = response.body();
if(res!=null) {
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(view.getContext(), "Didn't get response", Toast.LENGTH_LONG).show();
}
}
}
Your com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel is null. Check whether it is being alloted any value by getting in debug mode. Run the code step by step in debug mode and check how it is getting initialized.
Hint: Check this line of your code in debugger:
UserRegistrationModel res = response.body();
I want to upload multi-images from Android to Spring Server, using Retrofit2, but it is not working.
I refer to this website: https://futurestud.io/tutorials/retrofit-2-how-to-upload-multiple-files-to-server
My code is below:
package com.example.gdtbg.fileupload;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.ipaulpro.afilechooser.utils.FileUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import gun0912.tedbottompicker.TedBottomPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST = 100;
private int PICK_IMAGE_FROM_GALLERY_REQUEST = 1;
ArrayList<Uri> test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test = new ArrayList<Uri>();
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST);
}
Button uploadbutton = (Button) findViewById(R.id.submit);
uploadbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TedBottomPicker tedBottomPicker = new TedBottomPicker.Builder(MainActivity.this)
.setOnMultiImageSelectedListener(new TedBottomPicker.OnMultiImageSelectedListener() {
#Override
public void onImagesSelected(ArrayList<Uri> uriList) { //this function return Uri file uri type("file://")
uploadAlbum(uriList);
}
})
.setSelectMaxCount(3)
.setEmptySelectionText("선택된게 없습니다! 이미지를 선택해 주세요!")
.create();
tedBottomPicker.show(getSupportFragmentManager());
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
return;
}
}
}
#NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
}
public static Uri getImageContentUri(Context context, File imageFile) throws FileNotFoundException{
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) throws FileNotFoundException {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
ContentResolver cr = getContentResolver();
Uri castedUri = getImageContentUri(getApplicationContext(), file);
// create RequestBody instance from file
try {
Log.d("testfile", castedUri.toString());
if(cr.getType(castedUri)==null)
{
Log.d("testfile", "content uri is null");
Log.d("testfile", cr.getType(castedUri).toString());
}
else
{
Log.d("testfile", "content uri is not null");
Log.d("testfile", cr.getType(castedUri).toString());
}
RequestBody requestFile =
RequestBody.create(MediaType.parse(cr.getType(castedUri)),file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void uploadAlbum(List<Uri> fileUris) {
final EditText description = (EditText) findViewById(R.id.editText);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://192.168.0.3:8089/Test/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
UserClient client = retrofit.create(UserClient.class);
ArrayList<MultipartBody.Part> parts = new ArrayList<>();
Log.d("giduck", "Hello World!");
Log.d("giduck", "" + fileUris.size());
for (int i = 0; i < fileUris.size(); i++) {
Log.d("sendTest", fileUris.get(i).toString());
Log.d("sendTest", "" + fileUris.size());
try {
parts.add(prepareFilePart(""+i, fileUris.get(i)));
} catch (Exception e) {
e.printStackTrace();
}
Log.d("giduckfinal", "" + fileUris.get(i).toString());
Log.d("giduckfinal", "in loop");
}
Log.d("giduckfinal", "this is final position 1");
Call<ResponseBody> call = client.uploadAlbum(
createPartFromString(description.getText().toString()),
parts );
Log.d("final", "this is final position 2");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, "Success that Upload Image to Server", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Fail that Upload to Server", Toast.LENGTH_SHORT).show();
}
});
}
}
package com.example.gdtbg.fileupload;
import java.util.List;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
/**
* Created by gdtbg on 2017-06-21.
*/
public interface UserClient {
/* #Multipart
#POST("uploadForm")
Call<ResponseBody> uploadPhoto(
#Part("description") RequestBody description,
#Part MultipartBody.Part photo
);
#Multipart
#POST("uploadForm")
Call<ResponseBody> uploadPhotos(
#Part MultipartBody.Part profile,
#Part MultipartBody.Part panorama
); */
#Multipart
#POST("uploadForm")
Call<ResponseBody> uploadAlbum(
#Part("description") RequestBody description,
#Part List<MultipartBody.Part> files
);
}
i'm using this code and it works for me
upload.php
<?php
$attachment = $_FILES['attachment'];
define ("MAX_SIZE","9000");
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
// Method to extract the uploaded file extention
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Method to extract the uploaded file parameters
function getFileAttributes($file)
{
$file_ary = array();
$file_count = count($file['name']);
$file_key = array_keys($file);
for($i=0;$i<$file_count;$i++)
{
foreach($file_key as $val)
{
$file_ary[$i][$val] = $file[$val][$i];
}
}
return $file_ary;
}
// Check if the POST Global variable were set
if(!empty($attachment) && isset($_POST['dirname']))
{
$dirname = $_POST['dirname'];
$uploaddir = "/var/www/html/uploads/".$dirname."/";
//Check if the directory already exists.
if(!is_dir($uploaddir)){
//Directory does not exist, so create it.
mkdir($uploaddir, 0777, true);
}
$file_attributes = getFileAttributes($attachment);
//print_r($file_attributes);
$count = count($file_attributes);
$response["status"] = array();
$response["count"] = $count; // Count the number of files uploaded
array_push($response["status"], $file_attributes);
$file_dirs = array();
foreach($file_attributes as $val)
{
$old_file = $val['name'];
$ext = getExtension($old_file);
$ext = strtolower($ext);
if(in_array($ext, $valid_formats))
{
$response["files"] = array();
$new_file = date('YmdHis',time()).mt_rand(10,99).'.'.$ext;
move_uploaded_file($val['tmp_name'], $uploaddir.$new_file);
$file_dirs[] = 'http://192.168.50.10/gallery/uploads/'.$dirname."/".$new_file;
}
else
{
$file_dirs[] = 'Invalid file: '.$old_file;
}
}
array_push($response["files"], $file_dirs);
echo json_encode($response);
}
?>
then in xml put this
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="toegy.com.testmultiupload.MainActivity">
<TextView
android:id="#+id/select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="select"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
and in your activity put this
public class MainActivity extends AppCompatActivity {
TextView select;
int PICK_IMAGE_MULTIPLE = 1;
String imageEncoded;
List<String> imagesEncodedList;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
select = (TextView) findViewById(R.id.select);
pDialog = new ProgressDialog(MainActivity.this);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK && null != data) {
Log.e("++data", data.getClipData().getItemCount() + "");
List<Uri> uriList = new ArrayList<Uri>();
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
Uri selectedImage = data.getClipData().getItemAt(i).getUri();
Log.e("uri",selectedImage+"");
uriList.add(i,selectedImage);
}
uploadPhotos(uriList,"photos");
} else {
Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
public void uploadPhotos(final List<Uri> uriList, final String folderName) {
pDialog.setMessage("uploading ...............");
pDialog.show();
List<MultipartBody.Part> parts = new ArrayList<>();
for (Uri uri : uriList) {
parts.add(prepareFilePart("attachment[]", uri)); // Note: attachment[]. Not attachment
}
RequestBody requestBodyFolderName = createPartFromString(folderName);
HashMap<String, RequestBody> requestMap = new HashMap<>();
requestMap.put("dirname", requestBodyFolderName); // Note: dirname
FileUploadService service = RetrofitClient.getApiService();
Call<ResponseBody> call = service.uploadMultipleFilesDynamic(requestMap, parts);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 200) {
// multiple dynamic uploads were successful
Log.e("status", "done");
pDialog.hide();
} else {
Log.e("status", "not done " + response.code());
pDialog.hide();
}
Toast.makeText(MainActivity.this,response.code()+"",Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("status", "not done " + t.toString());
}
});
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
File file = new File(getRealPathFromURI(fileUri));
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
}
}
it will work prefect