在我的课程中,我使用以下方法获取文件路径,但它仅适用于模拟器;为什么吗
我的问题在于真实设备(三星Galaxy j5):
如何解决此问题?问题在于我的代码的哪一部分。
UploaderActivity:
public class UploaderActictivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG ="MyPath" ;
private static final int REQUEST_CODE =10052 ;
Uri URI =null ;
private Button button;
private String path;
TextView messageText;
Button uploadButton,BrowsButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
ImageView imNotify;
JustifiedTextView js;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploader);
js=findViewById(R.id.textDes);
js.setText( getResources().getString(des) + "\n" +
getResources().getString(des1)+ "\n" +
getResources().getString(des2)+ "\n" +
getResources().getString(des3));
uploadButton = findViewById(R.id.upload);
BrowsButton = findViewById(R.id.browse);
BrowsButton.setOnClickListener(this);
uploadButton.setOnClickListener(this);
messageText =findViewById(R.id.messageText);
imNotify =findViewById(R.id.notify);
String msg=messageText.getText().toString();
if(msg.isEmpty()){
messageText.setVisibility(View.GONE);
imNotify.setVisibility(View.GONE);
}
}
@Override
public void onClick(View v) {
if(v==BrowsButton) {
showFileChooser();
}
if(v==uploadButton) {
//upload to site
if(path != null){
dialog = ProgressDialog.show(UploaderActictivity.this, "", "آپلود فایل، لطفاً صبر کنید...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
imNotify.setVisibility(View.VISIBLE);
messageText.setVisibility(View.VISIBLE);
messageText.setText("در حال آپلود فایل...");
}
});
uploadFile(path);
}
}).start();
}
else{
Toast.makeText(UploaderActictivity.this,"ابتدا یک فایل انتخاب کنید!",Toast.LENGTH_SHORT).show();
}
}
}
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("*/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"انتخاب فایل..."),REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CODE) {
if (data == null) {
//no data present
return;
}
Uri currFileURI = data.getData();
path = FilePath.getPath(getApplicationContext(),currFileURI);
if(path != null && !path.equals("") ){
imNotify.setVisibility(View.VISIBLE);
messageText.setVisibility(View.VISIBLE);
Log.i(TAG, "Selected File Path:" + path);
messageText.setText(path);
}else{
Toast.makeText(this,"شما قادر به آپلود محتوای فایل نیستید!",Toast.LENGTH_SHORT).show();
}
}
}
}
public int uploadFile(final String path) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final int UserID =prefs.getInt("UserID", 0);
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 5 * 1024 * 1024;
File sourceFile = new File(path);
String[] parts = path.split("/");
final String fileName = UserID + "_" + parts[parts.length-1];
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+path);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("محتوایی در این مسیر وجود ندارد!"
+path);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(AppConfig.upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "فايل مورد نظر آپلود شد." +
"\n" + getResources().getString(DescriptionForUpload)
;
messageText.setText(msg);
Toast.makeText(UploaderActictivity.this, "آپلود فايل کامل شد.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploaderActictivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
Toast.makeText(UploaderActictivity.this, "مشکلی رخ داده است!", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploaderActictivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
Toast.makeText(UploaderActictivity.this, "مشکلی رخ داده است!", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
FilePath类:
public class FilePath {
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
}
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
}
return null;
}
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
}
答案 0 :(得分:1)
开始时你想做的事情是错误的。
不要尝试获取文件系统路径。
你有一个内容uri。用它来打开输入流。之后,您可以像打开文件输入流一样使用内容。