Search all .pdf files present in the Android device - android

How can I search all .pdf and .doc files present in the Android device through a programmatic way?

Try using the below code. This will work for you.
public void walkdir(File dir) {
String pdfPattern = ".pdf";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pdfPattern)){
//Do whatever you want
}
}
}
}
}
To search on the whole SD card, call this function using:
walkdir(Environment.getExternalStorageDirectory());

Have a look at File, list.
Basically, get a starting Directory, call "list" with a filter(FilenameFilter), and then traverse sub directories. I am not sure if there is a one function that does all this for you.

Download source code from here (Open pdf file from SD card in android programmatically)
Add this Dependency in your Gradle file:
compile ‘com.github.barteksc:android-pdf-viewer:2.0.3’
MainActivity.java:
package com.pdffilefromsdcard;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);
Log.e(“Position”, i + “”);
}
});
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
}
else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
}
else {
}
}
if (booleanpdf) {
booleanpdf = false;
}
else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
}
else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}
else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();
}
}
}
}
PdfActivity.java:
package com.pdffilefromsdcard;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.io.File;
import java.util.List;
public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
#Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}

Have a look at Stack Overflow question How can I get all audio files from the SD card on Android?.
Change the extension of the file like if you want all PDF files then extension ".pdf". Use this to get all PDF files from the device.

I found this method in my old project. This function will get you the PDF file and its information.
ManageFIleInfoForRecycler is my custom class to store the file information.
"storage" passes as "external".
public ArrayList<ManageFIleInfoForRecycler> fileList(String storage) {
ArrayList< ManageFIleInfoForRecycler > fileInfo = new ArrayList<>();
// Can give any file type, "doc", "pdf", etc.
String pdf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
int j = 0;
Uri table = MediaStore.Files.getContentUri(storage);
// Column
String[] column = {MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.TITLE};
// Where
String where = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String[] args = new String[]{pdf};
Cursor fileCursor = getApplicationContext().getContentResolver().query(table, column, where, args, null);
String [] filesLists = new String[]{};
while (fileCursor.moveToNext()) {
int pathString = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
int nameIndex = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE);
String path = fileCursor.getString(pathString);
String name = fileCursor.getString(nameIndex);
ManageFIleInfoForRecycler temp = new ManageFIleInfoForRecycler();
temp.filePath = path;
temp.fileName = name;
fileInfo.add(temp);
}
return fileInfo;
}

Related

mDatabase.child(key).addValueEventListener() is not triggering android studio

So I set up an event listener, but after checking several times, I see that it doesn't even trigger in the first place.
package com.example.globe_all;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginScreen extends AppCompatActivity {
private Button signup, login;
private EditText user_email, password;
private TextView errortext, forgotpassword, usernameText, passwordText, appearText;
private String checkPass;
private int count = 0;
private ImageView globe;
private FrameLayout frame;
private Boolean buttonFlag = false;
private String accessKey = "";
private FirebaseAuth mAuth;
private FirebaseDatabase database;
private DatabaseReference mDatabase;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
private SharedPreferences gamePrefs;
private SharedPreferences.Editor gamePrefsEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
signup = findViewById(R.id.signup);
login = findViewById(R.id.loginButton);
user_email = findViewById(R.id.user_email);
password = findViewById(R.id.password);
errortext = findViewById(R.id.loginerror);
usernameText = findViewById(R.id.usernametext);
passwordText = findViewById(R.id.passwordtext);
forgotpassword = findViewById(R.id.forgotpassword);
globe = findViewById(R.id.globe);
frame = findViewById(R.id.frame);
appearText = findViewById(R.id.appearText);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
gamePrefs = getSharedPreferences("gamePrefs", MODE_PRIVATE);
gamePrefsEditor = gamePrefs.edit();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance("https://globall-326315-default-rtdb.europe-west1.firebasedatabase.app/");
mDatabase = database.getReference("user");
globe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (giveBool("first") && giveBool("second")) {
Log.d("counter", " " + count);
switch (count) {
case 0:
signup.setVisibility(View.GONE);
case 1:
login.setVisibility(View.GONE);
case 2:
usernameText.setVisibility(View.GONE);
case 3:
password.setVisibility(View.GONE);
case 4:
user_email.setVisibility(View.GONE);
case 5:
passwordText.setVisibility(View.GONE);
case 6:
forgotpassword.setVisibility(View.GONE);
case 7:
ViewGroup.LayoutParams params = frame.getLayoutParams();
params.height = 300;
params.width = 300;
frame.setLayoutParams(params);
appearText.setVisibility(View.VISIBLE);
gamePrefsEditor.clear();
gamePrefsEditor.commit();
case 8:
Intent intent = new Intent(LoginScreen.this, MainActivity.class);
finish();
startActivity(intent);
}
count++;
}
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email_user = user_email.getText().toString();
String pass = password.getText().toString();
accessKey = encrypt(email_user) + "&&&" + encrypt(pass);
Log.d("useruser", " " + mDatabase.child(accessKey));
buttonFlag = true;
}
});
mDatabase.child(accessKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User u = snapshot.getValue(User.class);
checkPass = u.getPassword();
Log.d("checkPass", " " + checkPass);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("snapshot", "Error!");
throw error.toException();
}
});
if (buttonFlag && checkPass != null) {
checkPass = decrypt(checkPass);
String email_user = user_email.getText().toString();
String pass = password.getText().toString();
Log.d("decrypt", " " + checkPass);
if (pass.equals(checkPass)) {
errortext.setVisibility(View.GONE);
String email = mDatabase.child(accessKey).child("email").toString();
mAuth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(LoginScreen.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
loginPrefsEditor.putString("username", encrypt(email_user));
loginPrefsEditor.putBoolean("loggedIn", true);
loginPrefsEditor.commit();
Toast.makeText(LoginScreen.this, "Successfully logged in!", Toast.LENGTH_LONG).show();
Intent home = new Intent(LoginScreen.this, MainActivity.class);
finish();
startActivity(home);
}
});
} else {
errortext.setVisibility(View.VISIBLE);
}
} else {
errortext.setVisibility(View.VISIBLE);
}
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signup = new Intent(LoginScreen.this, SignupScreen.class);
startActivity(signup);
finish();
}
});
}
private String decrypt (String toDec) {
String sh = "abcdefghijklmnopqrstuvwxyz";
String ab = "xytaipckejzsrlfnmhvqgubowd";
String numshuf = "0123456789";
String num = "3298561740";
StringBuilder enc = new StringBuilder();
CharacterIterator it = new StringCharacterIterator(toDec);
while (it.current() != CharacterIterator.DONE)
{
char c = it.current();
if(!Character.isDigit(it.current())) {
for (int i = 0; i < ab.length(); i++) {
if (!(ab.charAt(i) == Character.toLowerCase(c)))
continue;
if (Character.isLowerCase(it.current()))
enc.append(sh.charAt(i));
else
enc.append(Character.toUpperCase(sh.charAt(i)));
break;
}
} else if (Character.isDigit(it.current())) {
for (int i = 0; i < num.length(); i++) {
if (!(num.charAt(i) == c))
continue;
enc.append(numshuf.charAt(i));
break;
}
} else if (!Character.isLetterOrDigit(it.current()))
enc.append(it.current());
it.next();
}
return enc.toString();
}
public String encrypt (String toEnc) {
String ab = "abcdefghijklmnopqrstuvwxyz";
String sh = "xytaipckejzsrlfnmhvqgubowd";
String num = "0123456789";
String numshuf = "3298561740";
StringBuilder enc = new StringBuilder();
CharacterIterator it = new StringCharacterIterator(toEnc);
while (it.current() != CharacterIterator.DONE)
{
char c = it.current();
if(!Character.isDigit(it.current())) {
for (int i = 0; i < ab.length(); i++) {
if (!(ab.charAt(i) == Character.toLowerCase(c)))
continue;
if (Character.isLowerCase(it.current()))
enc.append(sh.charAt(i));
else
enc.append(Character.toUpperCase(sh.charAt(i)));
break;
}
} else if (Character.isDigit(it.current())) {
for (int i = 0; i < num.length(); i++) {
if (!(num.charAt(i) == c))
continue;
enc.append(numshuf.charAt(i));
break;
}
} else if (!Character.isLetterOrDigit(it.current()))
enc.append(it.current());
it.next();
}
return enc.toString();
}
public boolean giveBool(String s) {
return gamePrefs.getBoolean(s, false);
}
}
I've updated the code, and pasted in the entirety of the code.
I've taken the addValueEventListener() out of my Onclick() method, and now I see that onDataChange does indeed trigger, but now I seem to face a problem of an Asynchronious nature, as I am still not getting a null out of my data. I am sure that the data I am trying to retrieve exists, so that's not the problem
So I figured out what was happening - seems that when I put my listener in the onClick() it wasn't triggering at all, so I took it out of there.
Then, it was always returning null so I figured it's about the async, and I went on checking how to fix that problem.
I followed the instructions and created a callback interface that was being used to retrieve the data from the database.
I called the interface in a function:
public void readData (MyCallBack myCallBack) {
mDatabase.child(accessKey).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String value = snapshot.getValue(User.class).getPassword();
myCallBack.onCallback(value);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
And the interface:
public interface MyCallBack {
void onCallback(String value);
}

Unable to upload right photo URL to firebase

When I try to upload the image and click the submit button, the logcat show out this message.
Logcat Result
2018-10-15 22:21:32.191 22289-22477/com.example.edward.neweventmanagementsystem E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.
Java File
package com.example.edward.neweventmanagementsystem;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.edward.neweventmanagementsystem.Model.EventInfo;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Calendar;
import java.util.regex.Pattern;
import static android.widget.Toast.LENGTH_SHORT;
public class CreateEvent extends AppCompatActivity {
private static final String TAG = "activity_create_event";
private Uri filePath;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private DatabaseReference mDatabaseReference;
private Button mRegisterButton;
EditText mEventNameText, mContactNumText, mEventLocationText, mRegisterEventId;;
TextView mEventDate;
RadioGroup mEventType;
FirebaseStorage storage;
StorageReference storageRef,imageRef;
Uri uriImage ;//= Uri.parse("com.example.edward.eventmanagementsystem.ManageEvent/"+ R.drawable.ic_launcher_background);
public static final int PICK_IMAGE = 1;
ImageView mimageToUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
FirebaseDatabase firebaseDatabase;
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("ListOfEvent"); //.push();
mRegisterButton = (Button)findViewById(R.id.btnRegisterEvent);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
mDisplayDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
CreateEvent.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: date: mm/dd/yyyy: " + month + "/" + day + "/" + year);
String date = month + "/" + day + "/" + year;
mDisplayDate.setText(date);
}
};
//insert data to database
mRegisterEventId = (EditText) findViewById(R.id.RegisterEventId);
mEventNameText = (EditText) findViewById(R.id.RegisterEventName);
mContactNumText = (EditText) findViewById(R.id.RegisterContactNumber);
mEventDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mEventType = (RadioGroup) findViewById(R.id.RegisterEventRadiogroup);
mEventLocationText = (EditText) findViewById(R.id.RegisterEventLocation);
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
mRegisterButton = (Button) findViewById(R.id.btnRegisterEvent);
mimageToUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CreateEvent.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else {
ActivityCompat.requestPermissions(CreateEvent.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(CreateEvent.this);
mDialog.setMessage("Please waiting...");
mDialog.show();
int selectedId = mEventType.getCheckedRadioButtonId();
final RadioButton radioButton = (RadioButton)findViewById(selectedId);
final String id = mRegisterEventId.getText().toString().trim();
final String name = mEventNameText.getText().toString().trim();
final String contact = mContactNumText.getText().toString().trim();
final String date = mEventDate.getText().toString().trim();
final String type = radioButton.getText().toString().trim();
final String location = mEventLocationText.getText().toString().trim();
if (TextUtils.isEmpty(id)) {
mRegisterEventId.setError("Enter Event ID!");
return;
}
if (TextUtils.isEmpty(name)) {
mEventNameText.setError("Enter Event Name!");
return;
}
if (TextUtils.isEmpty(location)) {
mEventLocationText.setError("Enter Location!");
return;
}
if (TextUtils.isEmpty(type)) {
radioButton.setError("Please select type of event type!");
return;
}
if(isValidPhone(contact)){
Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
}else {
mContactNumText.setError("Phone number is not valid");
Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(date)) {
mEventDate.setError("Please select event date!");
return;
}
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(mRegisterEventId.getText().toString()).exists()) {
mDialog.dismiss();
Toast.makeText(CreateEvent.this, "ID already exists!", Toast.LENGTH_SHORT).show();
}else {
mDialog.dismiss();
EventInfo eventInfo = new EventInfo(mRegisterEventId.getText().toString().trim(),mEventNameText.getText().toString().trim(), mContactNumText.getText().toString().trim(), mEventDate.getText().toString().trim(), radioButton.getText().toString().trim(), mEventLocationText.getText().toString().trim());
mDatabaseReference.child(mRegisterEventId.getText().toString()).setValue(eventInfo);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
final String fileName = System.currentTimeMillis()+"";
if(uriImage != null) {
final StorageReference storageReference = storage.getReference();
System.out.println(uriImage);
storageReference.child("profileImageUrl").child(fileName).putFile(uriImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
// Uri downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().getResult();
// String urlImage = downloadUrl.toString();
mDatabaseReference.child(id).child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
System.out.println(taskSnapshot.getUploadSessionUri().toString());
}
else{
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}else{
}
Toast.makeText(getApplicationContext(),"New event created successfully!",LENGTH_SHORT).show();
Intent ManageEventMenu = new Intent(CreateEvent.this, com.example.edward.neweventmanagementsystem.ManageEventMenu.class);
startActivity(ManageEventMenu);
}
});
}
public boolean isValidPhone(CharSequence phone) {
boolean check=false;
if(!Pattern.matches("[a-zA-Z]+", phone))
{
if(phone.length() < 10 || phone.length() > 11)
{
check = false;
}
else
{
check = true;
}
}
else
{
check=false;
}
return check;
}
private void selectPdf() {
Intent photoPickerIntent = new Intent();
photoPickerIntent .setType("image/*");
photoPickerIntent .setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(photoPickerIntent ,86);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 86 && resultCode == RESULT_OK && data != null){
final Uri imageUri = data.getData();
uriImage = imageUri;
mimageToUpload.setImageURI(uriImage);
}
else {
Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
}
}
}
Anyone know how to solve this problem. Thanks a lot.
Also that, I also face problem when try to display the message in my apps. There was no problem with other field such as Text, RadioButton, Date, only photo I unable to up the real url.
fyi. currenly the url display in firebase database is the photo storage location
It seems like the user is not signed (authenticated from the Firebase ) .
their is two method to solve the problem
1)authenticate the user using authentication
2)set your rule to public for fire-base real-time database
copy and paste this rule in Firebase real-time database >rule
{
"rules": {
".read": true,
".write": true
}
}
But doing this will make
your security rules are defined as public, so anyone can steal, modify or delete data in your database
The Exception clearly says that you are trying to perform operations without having the user logged in.
You can follow this manuel to authenticate and then perform your operations
https://firebase.google.com/docs/auth/android/password-auth

Android get attribute value from xml

I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();

How can I setAllowFileAccess for a react-native android WebView?

I want to disable file access within an Android WebView I'm creating using react-native's built-in WebView component.
The Android WebView docs say "File access is enabled by default.", and this is a security concern for my organization.
The react-native 0.31 docs mention a getWebViewHandle method that can be used to access the underlying WebView node; if this worked, then I could (presumably) write:
import { WebView, Platform } from 'react-native';
//...
var reactWebview = <Webview [props here] />
if (Platform.OS === 'android') {
var webview = reactWebview.getWebViewHandle();
webview.setAllowFileAccess(false);
}
However, later versions of the react-native docs don't mention getWebViewHandle, and when I run code like this in react-native 0.44 on an Android device, I get the error webview.getWebViewHandle is not a function.
My questions are:
Is file access enabled by default for the Android WebViews created by react-native?
If so, how can we disable this file access? Could we accomplish this by extending the WebView class, or would we need to fork and modify react-native?
Thanks for your time!
Questions 1: As see from the source code of ReactWebViewManager.java, RN does not call WebView.setAllowFileAccess, so file access is enabled by Android WebView, not by RN.
Questions 2: You can create a custom WebView to do what you need, or just get the reference of your WebView from a Native Module, then you can access all the apis of Android WebView like setAllowFileAccess in that Native Module.
Native Module
public class WebViewSettingModule extends ReactContextBaseJavaModule {
public WebViewSettingModule(ReactApplicationContext reactContext) {
super(reactContext);
}
#Override
public String getName() {
return "WebViewSetting";
}
#ReactMethod
public void setWebView() {
Activity activity = getCurrentActivity();
//the id for the ReactRootView is always be 1
#IdRes int id = 1;
View view = activity.findViewById(id);
if (view instanceof ReactRootView) {
ReactRootView reactRootView = (ReactRootView) view;
//make sure the WebView is directly child of ReactRootView
reactRootView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
#Override
public void onChildViewAdded(View parent, final View child) {
if (child instanceof WebView) {
Log.e("onChildViewAdded: ", ((WebView) child).getUrl());
//get the reference to the WebView and setAllowFileAccess
((WebView) child).getSettings().setAllowFileAccess(false);
}
}
#Override
public void onChildViewRemoved(View parent, View child) {
}
});
}
}
}
index.android.js
import React, {Component} from "react";
import {AppRegistry, View, WebView} from "react-native";
//the native module
import MyWebView from "./src/MyWebView";
export default class WebViewSetting extends Component {
componentDidMount() {
//notify native code to modify WebView setting
MyWebView.setWebView();
}
render() {
return (
<View style={{flex: 1}}>
<WebView
source={{uri: 'https://github.com/'}}
style={{marginTop: 20}}/>
</View>
);
}
}
AppRegistry.registerComponent('WebViewSetting', () => WebViewSetting);
the whole code can be found here
node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/views/ReactWebViewManager.java
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.views.webview;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Picture;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import com.facebook.common.logging.FLog;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.common.build.ReactBuildConfig;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.ContentSizeChangeEvent;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.views.webview.events.TopLoadingErrorEvent;
import com.facebook.react.views.webview.events.TopLoadingFinishEvent;
import com.facebook.react.views.webview.events.TopLoadingStartEvent;
import com.facebook.react.views.webview.events.TopMessageEvent;
import org.json.JSONObject;
import org.json.JSONException;
#ReactModule(name = ReactWebViewManager.REACT_CLASS)
public class ReactWebViewManager extends SimpleViewManager<WebView> {
protected static final String REACT_CLASS = "RCTWebView";
private static final String HTML_ENCODING = "UTF-8";
private static final String HTML_MIME_TYPE = "text/html; charset=utf-8";
private static final String BRIDGE_NAME = "__REACT_WEB_VIEW_BRIDGE";
private static final String HTTP_METHOD_POST = "POST";
public static final int COMMAND_GO_BACK = 1;
public static final int COMMAND_GO_FORWARD = 2;
public static final int COMMAND_RELOAD = 3;
public static final int COMMAND_STOP_LOADING = 4;
public static final int COMMAND_POST_MESSAGE = 5;
public static final int COMMAND_INJECT_JAVASCRIPT = 6;
private static final String BLANK_URL = "about:blank";
public static final int INPUT_FILE_REQUEST_GALLERY_IMAGE = 1001;
public static final int REQUEST_SELECT_FILE_LEGACY = 1012;
private WebViewConfig mWebViewConfig;
private
#Nullable
WebView.PictureListener mPictureListener;
private ValueCallback<Uri[]> mFilePathCallbackArr;
private ValueCallback<Uri> mFilePathCallback; // Legacy (Android 4.1+)
private String mCameraPhotoPath;
protected static class ReactWebViewClient extends WebViewClient {
private boolean mLastLoadFailed = false;
#Override
public void onPageFinished(WebView webView, String url) {
super.onPageFinished(webView, url);
if (!mLastLoadFailed) {
ReactWebView reactWebView = (ReactWebView) webView;
reactWebView.callInjectedJavaScript();
reactWebView.linkBridge();
emitFinishEvent(webView, url);
}
}
#Override
public void onPageStarted(WebView webView, String url, Bitmap favicon) {
super.onPageStarted(webView, url, favicon);
mLastLoadFailed = false;
dispatchEvent(
webView,
new TopLoadingStartEvent(
webView.getId(),
createWebViewEvent(webView, url)));
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("http://") || url.startsWith("https://") ||
url.startsWith("file://")) {
return false;
} else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
FLog.w(ReactConstants.TAG, "activity not found to handle uri scheme for: " + url, e);
}
return true;
}
}
#Override
public void onReceivedError(
WebView webView,
int errorCode,
String description,
String failingUrl) {
super.onReceivedError(webView, errorCode, description, failingUrl);
mLastLoadFailed = true;
emitFinishEvent(webView, failingUrl);
WritableMap eventData = createWebViewEvent(webView, failingUrl);
eventData.putDouble("code", errorCode);
eventData.putString("description", description);
dispatchEvent(
webView,
new TopLoadingErrorEvent(webView.getId(), eventData));
}
#Override
public void doUpdateVisitedHistory(WebView webView, String url, boolean isReload) {
super.doUpdateVisitedHistory(webView, url, isReload);
dispatchEvent(
webView,
new TopLoadingStartEvent(
webView.getId(),
createWebViewEvent(webView, url)));
}
private void emitFinishEvent(WebView webView, String url) {
dispatchEvent(
webView,
new TopLoadingFinishEvent(
webView.getId(),
createWebViewEvent(webView, url)));
}
private WritableMap createWebViewEvent(WebView webView, String url) {
WritableMap event = Arguments.createMap();
event.putDouble("target", webView.getId());
event.putString("url", url);
event.putBoolean("loading", !mLastLoadFailed && webView.getProgress() != 100);
event.putString("title", webView.getTitle());
event.putBoolean("canGoBack", webView.canGoBack());
event.putBoolean("canGoForward", webView.canGoForward());
return event;
}
}
protected static class ReactWebView extends WebView implements LifecycleEventListener {
private
#Nullable
String injectedJS;
private boolean messagingEnabled = false;
private class ReactWebViewBridge {
ReactWebView mContext;
ReactWebViewBridge(ReactWebView c) {
mContext = c;
}
#JavascriptInterface
public void postMessage(String message) {
mContext.onMessage(message);
}
}
public ReactWebView(ThemedReactContext reactContext) {
super(reactContext);
}
#Override
public void onHostResume() {
// do nothing
}
#Override
public void onHostPause() {
// do nothing
}
#Override
public void onHostDestroy() {
cleanupCallbacksAndDestroy();
}
public void setInjectedJavaScript(#Nullable String js) {
injectedJS = js;
}
public void setMessagingEnabled(boolean enabled) {
if (messagingEnabled == enabled) {
return;
}
messagingEnabled = enabled;
if (enabled) {
addJavascriptInterface(new ReactWebViewBridge(this), BRIDGE_NAME);
linkBridge();
} else {
removeJavascriptInterface(BRIDGE_NAME);
}
}
public void callInjectedJavaScript() {
if (getSettings().getJavaScriptEnabled() &&
injectedJS != null &&
!TextUtils.isEmpty(injectedJS)) {
loadUrl("javascript:(function() {\n" + injectedJS + ";\n})();");
}
}
public void linkBridge() {
if (messagingEnabled) {
if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// See isNative in lodash
String testPostMessageNative = "String(window.postMessage) === String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage')";
evaluateJavascript(testPostMessageNative, new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
if (value.equals("true")) {
FLog.w(ReactConstants.TAG, "Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined");
}
}
});
}
loadUrl("javascript:(" +
"window.originalPostMessage = window.postMessage," +
"window.postMessage = function(data) {" +
BRIDGE_NAME + ".postMessage(String(data));" +
"}" +
")");
}
}
public void onMessage(String message) {
dispatchEvent(this, new TopMessageEvent(this.getId(), message));
}
private void cleanupCallbacksAndDestroy() {
setWebViewClient(null);
destroy();
}
}
public ReactWebViewManager() {
mWebViewConfig = new WebViewConfig() {
public void configWebView(WebView webView) {
}
};
}
public ReactWebViewManager(WebViewConfig webViewConfig) {
mWebViewConfig = webViewConfig;
}
#Override
public String getName() {
return REACT_CLASS;
}
#Override
protected WebView createViewInstance(final ThemedReactContext reactContext) {
ReactWebView webView = new ReactWebView(reactContext);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onConsoleMessage(ConsoleMessage message) {
if (ReactBuildConfig.DEBUG) {
return super.onConsoleMessage(message);
}
return true;
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = new File(
storageDir,
imageFileName + ".jpg"
);
return imageFile;
}
private Intent getVideoCaptureIntent() {
Intent recordVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
recordVideoIntent
.resolveActivity(
reactContext
.getCurrentActivity()
.getPackageManager()
);
recordVideoIntent.putExtra("type", "foobar");
return recordVideoIntent;
}
public boolean onShowFileChooser(
WebView webView,
ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams
) {
if (mFilePathCallbackArr != null) {
mFilePathCallbackArr.onReceiveValue(null);
}
mFilePathCallbackArr = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
ComponentName comp = takePictureIntent
.resolveActivity(
reactContext
.getCurrentActivity()
.getPackageManager()
);
if (comp != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
FLog.e(ReactConstants.TAG, "Unable to create Image File", ex);
}
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent videoCaptureIntent = getVideoCaptureIntent();
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
intentArray = new Intent[]{
intentArray[0],
videoCaptureIntent
};
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_GALLERY_IMAGE);
return true;
}
});
reactContext.addLifecycleEventListener(webView);
reactContext.addActivityEventListener(new ActivityEventListener() {
// Android 5+
#Override
public void onActivityResult (Activity activity, int requestCode, int resultCode, Intent data) {
if(requestCode != INPUT_FILE_REQUEST_GALLERY_IMAGE || mFilePathCallbackArr == null) {
return;
}
Uri[] results = null;
if(resultCode == Activity.RESULT_OK) {
if(data == null || data.getData() == null) {
if(mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
if(results == null) {
mFilePathCallbackArr.onReceiveValue(new Uri[]{});
}
else {
mFilePathCallbackArr.onReceiveValue(results);
}
mFilePathCallbackArr = null;
return;
}
#Override
public void onNewIntent(Intent intent) {}
});
mWebViewConfig.configWebView(webView);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setDomStorageEnabled(true);
webView.setLayoutParams(
new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
return webView;
}
#ReactProp(name = "javaScriptEnabled")
public void setJavaScriptEnabled(WebView view, boolean enabled) {
view.getSettings().setJavaScriptEnabled(enabled);
}
#ReactProp(name = "scalesPageToFit")
public void setScalesPageToFit(WebView view, boolean enabled) {
view.getSettings().setUseWideViewPort(!enabled);
}
#ReactProp(name = "domStorageEnabled")
public void setDomStorageEnabled(WebView view, boolean enabled) {
view.getSettings().setDomStorageEnabled(enabled);
}
#ReactProp(name = "userAgent")
public void setUserAgent(WebView view, #Nullable String userAgent) {
if (userAgent != null) {
// TODO(8496850): Fix incorrect behavior when property is unset (uA == null)
view.getSettings().setUserAgentString(userAgent);
}
}
#ReactProp(name = "mediaPlaybackRequiresUserAction")
public void setMediaPlaybackRequiresUserAction(WebView view, boolean requires) {
view.getSettings().setMediaPlaybackRequiresUserGesture(requires);
}
#ReactProp(name = "allowUniversalAccessFromFileURLs")
public void setAllowUniversalAccessFromFileURLs(WebView view, boolean allow) {
view.getSettings().setAllowUniversalAccessFromFileURLs(allow);
}
#ReactProp(name = "injectedJavaScript")
public void setInjectedJavaScript(WebView view, #Nullable String injectedJavaScript) {
((ReactWebView) view).setInjectedJavaScript(injectedJavaScript);
}
#ReactProp(name = "messagingEnabled")
public void setMessagingEnabled(WebView view, boolean enabled) {
((ReactWebView) view).setMessagingEnabled(enabled);
}
#ReactProp(name = "source")
public void setSource(WebView view, #Nullable ReadableMap source) {
if (source != null) {
if (source.hasKey("html")) {
String html = source.getString("html");
if (source.hasKey("baseUrl")) {
view.loadDataWithBaseURL(
source.getString("baseUrl"), html, HTML_MIME_TYPE, HTML_ENCODING, null);
} else {
view.loadData(html, HTML_MIME_TYPE, HTML_ENCODING);
}
return;
}
if (source.hasKey("uri")) {
String url = source.getString("uri");
String previousUrl = view.getUrl();
if (previousUrl != null && previousUrl.equals(url)) {
return;
}
if (source.hasKey("method")) {
String method = source.getString("method");
if (method.equals(HTTP_METHOD_POST)) {
byte[] postData = null;
if (source.hasKey("body")) {
String body = source.getString("body");
try {
postData = body.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
postData = body.getBytes();
}
}
if (postData == null) {
postData = new byte[0];
}
view.postUrl(url, postData);
return;
}
}
HashMap<String, String> headerMap = new HashMap<>();
if (source.hasKey("headers")) {
ReadableMap headers = source.getMap("headers");
ReadableMapKeySetIterator iter = headers.keySetIterator();
while (iter.hasNextKey()) {
String key = iter.nextKey();
if ("user-agent".equals(key.toLowerCase(Locale.ENGLISH))) {
if (view.getSettings() != null) {
view.getSettings().setUserAgentString(headers.getString(key));
}
} else {
headerMap.put(key, headers.getString(key));
}
}
}
view.loadUrl(url, headerMap);
return;
}
}
view.loadUrl(BLANK_URL);
}
#ReactProp(name = "onContentSizeChange")
public void setOnContentSizeChange(WebView view, boolean sendContentSizeChangeEvents) {
if (sendContentSizeChangeEvents) {
view.setPictureListener(getPictureListener());
} else {
view.setPictureListener(null);
}
}
#ReactProp(name = "mixedContentMode")
public void setMixedContentMode(WebView view, #Nullable String mixedContentMode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (mixedContentMode == null || "never".equals(mixedContentMode)) {
view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
} else if ("always".equals(mixedContentMode)) {
view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
} else if ("compatibility".equals(mixedContentMode)) {
view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
}
}
}
#Override
protected void addEventEmitters(ThemedReactContext reactContext, WebView view) {
view.setWebViewClient(new ReactWebViewClient());
}
#Override
public
#Nullable
Map<String, Integer> getCommandsMap() {
return MapBuilder.of(
"goBack", COMMAND_GO_BACK,
"goForward", COMMAND_GO_FORWARD,
"reload", COMMAND_RELOAD,
"stopLoading", COMMAND_STOP_LOADING,
"postMessage", COMMAND_POST_MESSAGE,
"injectJavaScript", COMMAND_INJECT_JAVASCRIPT
);
}
#Override
public void receiveCommand(WebView root, int commandId, #Nullable ReadableArray args) {
switch (commandId) {
case COMMAND_GO_BACK:
root.goBack();
break;
case COMMAND_GO_FORWARD:
root.goForward();
break;
case COMMAND_RELOAD:
root.reload();
break;
case COMMAND_STOP_LOADING:
root.stopLoading();
break;
case COMMAND_POST_MESSAGE:
try {
JSONObject eventInitDict = new JSONObject();
eventInitDict.put("data", args.getString(0));
root.loadUrl("javascript:(function () {" +
"var event;" +
"var data = " + eventInitDict.toString() + ";" +
"try {" +
"event = new MessageEvent('message', data);" +
"} catch (e) {" +
"event = document.createEvent('MessageEvent');" +
"event.initMessageEvent('message', true, true, data.data, data.origin, data.lastEventId, data.source);" +
"}" +
"document.dispatchEvent(event);" +
"})();");
} catch (JSONException e) {
throw new RuntimeException(e);
}
break;
case COMMAND_INJECT_JAVASCRIPT:
root.loadUrl("javascript:" + args.getString(0));
break;
}
}
#Override
public void onDropViewInstance(WebView webView) {
super.onDropViewInstance(webView);
((ThemedReactContext) webView.getContext()).removeLifecycleEventListener((ReactWebView) webView);
((ReactWebView) webView).cleanupCallbacksAndDestroy();
}
private WebView.PictureListener getPictureListener() {
if (mPictureListener == null) {
mPictureListener = new WebView.PictureListener() {
#Override
public void onNewPicture(WebView webView, Picture picture) {
dispatchEvent(
webView,
new ContentSizeChangeEvent(
webView.getId(),
webView.getWidth(),
webView.getContentHeight()));
}
};
}
return mPictureListener;
}
private static void dispatchEvent(WebView webView, Event event) {
ReactContext reactContext = (ReactContext) webView.getContext();
EventDispatcher eventDispatcher =
reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
eventDispatcher.dispatchEvent(event);
}
}
I could not find this solution anywhere so I thought I would share, I hope it helps...
To enable the browse button to work and subsequently allow file access you can replace the above and this react-native files with these modified versions:
node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/ThemedReactContext.java
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.uimanager;
import javax.annotation.Nullable;
import android.app.Activity;
import android.content.Context;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.LifecycleEventListener;
//
/**
* Wraps {#link ReactContext} with the base {#link Context} passed into the constructor.
* It provides also a way to start activities using the viewContext to which RN native views belong.
* It delegates lifecycle listener registration to the original instance of {#link ReactContext}
* which is supposed to receive the lifecycle events. At the same time we disallow receiving
* lifecycle events for this wrapper instances.
* TODO: T7538544 Rename ThemedReactContext to be in alignment with name of ReactApplicationContext
*/
public class ThemedReactContext extends ReactContext {
private final ReactApplicationContext mReactApplicationContext;
public ThemedReactContext(ReactApplicationContext reactApplicationContext, Context base) {
super(base);
initializeWithInstance(reactApplicationContext.getCatalystInstance());
mReactApplicationContext = reactApplicationContext;
}
#Override
public void addLifecycleEventListener(LifecycleEventListener listener) {
mReactApplicationContext.addLifecycleEventListener(listener);
}
#Override
public void removeLifecycleEventListener(LifecycleEventListener listener) {
mReactApplicationContext.removeLifecycleEventListener(listener);
}
#Override
public void addActivityEventListener(ActivityEventListener listener) {
mReactApplicationContext.addActivityEventListener(listener);
}
#Override
public void removeActivityEventListener(ActivityEventListener listener) {
mReactApplicationContext.removeActivityEventListener(listener);
}
#Override
public boolean hasCurrentActivity() {
return mReactApplicationContext.hasCurrentActivity();
}
#Override
public
#Nullable
Activity getCurrentActivity() {
return mReactApplicationContext.getCurrentActivity();
}
}
The second file is listed above

How to upload multi-images from Android to Spring Server?

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

Categories

Resources