- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在从设备中选择文件时使用这个 fileutils 类:
public class FileUtils {
private FileUtils() {
}
private static final String TAG = "FileUtils";
private static final boolean DEBUG = false;
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
private 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()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
//// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// This is for checking Main Memory
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return Environment.getExternalStorageDirectory() + "/";
}
// This is for checking SD Card
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
String[] data = new String[2];
data[0] = id.replaceFirst("raw:", "");
data[1] = null;
return data[0];
}
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
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);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
我在 onActivityResult
中这样调用这个类:
String sourcePath = FileUtils.getPath(this, data.getData());
由于某种原因,我遇到了以下崩溃:
Caused by java.lang.IllegalArgumentException: Unknown URI: content://downloads/public_downloads/230
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:165)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:418)
at android.content.ContentResolver.query(ContentResolver.java:760)
at android.content.ContentResolver.query(ContentResolver.java:710)
at android.content.ContentResolver.query(ContentResolver.java:668)
at com.HBiSoft.ProGolf.Utils.FileUtils.getDataColumn(FileUtils.java:50)
at com.HBiSoft.ProGolf.Utils.FileUtils.getPath(FileUtils.java:116)
at com.HBiSoft.ProGolf.MainActivity.onActivityResult(MainActivity.java:652)
at android.app.Activity.dispatchActivityResult(Activity.java:7638)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4515)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
at android.app.ActivityThread.-wrap21(Unknown Source)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1779)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
崩溃仅在从下载文件夹中选择文件时发生。
有人可以帮我解决这个问题吗?
最佳答案
我已经创建了一个gist
来解决这个问题,这里是link .
重要!!
当您从 Google Drive 或 Dropbox 选择文件时,您将收到以下错误消息:
Caused by java.lang.IllegalArgumentException: column '_data' does not exist
要解决此问题,您实际上必须为您尝试选择的文件制作一个临时副本。
首先您必须检查 content://
uri 是否来自 Google 云端硬盘,您可以通过执行以下操作来完成此操作:
public boolean isGoogleDrive(Uri uri) {
return String.valueOf(uri).toLowerCase().contains("com.google.android.apps");
}
如果它是来自 Google Drive 的文件,这将返回 true。如果是,我将调用一个AsyncTask
,如下所示:
//The data.getData() below refers to the uri you get in onActivityResult
if (isGoogleDrive(data.getData())) {
DownloadAsyncTask asyntask = new DownloadAsyncTask(data.getData(), this);
asyntask.execute();
asyntask.callback = this;
}
在 AsyncTask
中,我们将使用 Uri
打开一个 InputStream
并取回我们将用于制作副本的字节数据的文件。
这是 AsyncTask
类(我添加了注释以使其更易于理解):
class DownloadAsyncTask extends AsyncTask<Uri, Void, String> {
private Uri mUri;
CallBackTask callback;
Context mContext;
private AlertDialog mdialog;
DownloadAsyncTask(Uri uri, Context context) {
this.mUri = uri;
mContext = context;
}
// In the onPreExecute() I'm displaying a custom dialog, this is not necessary, but recommended for when the user selects a large file
@Override
protected void onPreExecute() {
final AlertDialog.Builder mPro = new AlertDialog.Builder(new ContextThemeWrapper(mContext, R.style.myDialog));
@SuppressLint("InflateParams")
//Get reference to dialog layout
final View mPView = LayoutInflater.from(mContext).inflate(R.layout.dialog, null);
//Get reference to dialog title
final TextView title = mPView.findViewById(R.id.txtTitle);
//Get reference to dialog description
final TextView desc = mPView.findViewById(R.id.txtDesc);
//Set title text
title.setText("Please wait..");
//Set description text
desc.setText("Drive files needs to be imported, this might take some time depending on the file size.");
mPro.setView(mPView);
mdialog = mPro.create();
mdialog.show();
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected String doInBackground(Uri... params) {
//This will be the file we will use (the one that will be copied)
File file = null;
try {
//Create a temporary folder where the copy will be saved to
File temp_folder = mContext.getExternalFilesDir("TempFolder");
//Use ContentResolver to get the name of the original name
//Create a cursor and pass the Uri to it
Cursor cursor = mContext.getContentResolver().query(mUri, null, null, null, null);
//Check that the cursor is not null
assert cursor != null;
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
cursor.moveToFirst();
//Get the file name
String filename = cursor.getString(nameIndex);
//Close the cursor
cursor.close();
//open a InputStream by passing it the Uri
//We have to do this in a try/catch
InputStream is = null;
try {
is = mContext.getContentResolver().openInputStream(mUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//We now have a folder and a file name, now we can create a file
file = new File(temp_folder + "/" + filename);
//We can now use a BufferedInputStream to pass the InputStream we opened above to it
BufferedInputStream bis = new BufferedInputStream(is);
//We will write the byte data to the FileOutputStream, but we first have to create it
FileOutputStream fos = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
int count;
//Below we will read all the byte data and write it to the FileOutputStream
while ((count = bis.read(data)) != -1) {
total += count;
fos.write(data, 0, count);
}
//The FileOutputStream is done and the file is created and we can clean and close it
fos.flush();
fos.close();
} catch (IOException e) {
Log.e("IOException = ", String.valueOf(e));
}
//Finally we can pass the path of the file we have copied
return file.getAbsolutePath();
}
protected void onPostExecute(String result) {
//We are done and can cancel the dialog
if (mdialog != null && mdialog.isShowing()) {
mdialog.cancel();
}
//I'm using a callback to let my Activity know that the AsyncTask is done. I pass the path along.
callback.getResultFromAsynTask(result);
}
}
您会看到在上面的 onPostExecute()
中我有 callback.getResultFromAsynTask(result);
。正如我在评论中提到的,我正在使用回调方法让 Activity 知道我已完成并将路径传递给回调。
在您的 Activity 中,您必须实现回调,如下所示:
public class MainActivity extends AppCompatActivity implements CallBackTask {
CallBackTask
将如下所示:
interface CallBackTask {
void getResultFromAsynTask(String result);
}
现在您必须在您的 Activity
中实现它才能在您的 Activity
中获得结果:
@Override
public void getResultFromAsynTask(String result) {
// Do what you need with the result like starting your new Activity and passing the path
final Intent intent = new Intent();
intent.setClass(MainActivity.this, Player.class);
intent.putExtra("path", result);
startActivity(intent);
}
太棒了,您现在有一个来自 File://
的 Uri
(而不是 content://
) 您临时复制的。但是,不要忘记在用完文件后将其删除,否则您的应用程序会越来越大。
下面,我将删除我们之前创建的 TempFolder
,我将在 Activity onBackPressed
中执行此操作(这也应该在 onDestroy() 中完成):
@Override
public void onBackPressed() {
super.onBackPressed();
File dir = getBaseContext().getExternalFilesDir("TempFolder");
deleteRecursive(dir);
}
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
读了很多,但是...通过这种方式,您将永远不会遇到任何 content://
Uri
的问题。
关于java - 从下载中选择文件时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54266179/
是否有某种方法可以使用 JPA 或 Hibernate Crtiteria API 来表示这种 SQL?或者我应该将其作为 native 执行吗? SELECT A.X FROM (SELECT X,
在查询中, select id,name,feature,marks from (....) 我想删除其 id 在另一个 select 语句中存在的那些。 从 (...) 中选择 id 我是 sql
我想响应用户在 select 元素中选择一个项目。然而这个 jQuery: $('#platypusDropDown').select(function () { alert('You sel
这个问题在这里已经有了答案: SQL select only rows with max value on a column [duplicate] (27 个回答) 关闭8年前。 我正在学习 SQL
This question already has answers here: “Notice: Undefined variable”, “Notice: Undefined index”, and
我在 php 脚本中调用 SQL。有时“DE”中没有值,如果是这种情况我想从“EN”中获取值 应该是这样的,但不是这样的 IF (EXISTS (SELECT epf_application_deta
这可能是一个奇怪的问题,但不知道如何研究它。执行以下查询时: SELECT Foo.col1, Foo.col2, Foo.col3 FROM Foo INNER JOIN Bar ON
如何在使用 Camera.DestinationType.FILE_URI. 时在 phonegap camera API 中同时选择或拾取多个图像我能够一次只选择一张图像。我可以使用 this 在
这是一个纯粹的学术问题。这两个陈述实际上是否相同? IF EXISTS (SELECT TOP 1 1 FROM Table1) SELECT 1 ELSE SELECT 0 相对 IF EXIS
我使用 JSoup 来解析 HTML 响应。我有多个 Div 标签。我必须根据 ID 选择 Div 标签。 我的伪代码是这样的 Document divTag = Jsoup.connect(link
我正在处理一个具有多个选择框的表单。当用户从 selectbox1 中选择一个选项时,我需要 selectbox2 active 的另一个值。同样,当他选择 selectbox2 的另一个值时,我需要
Acme Inc. Christa Woods Charlotte Freeman Jeffrey Walton Ella Hubbard Se
我有一个login.html其中form定义如下: First Initial Plus Last Name : 我的do_authorize如下: "; pri
$.get( 'http://www.ufilme.ro/api/load/maron_online/470', function(data
我有一个下拉列表“磅”、“克”、“千克”和“盎司”。我想要这样一种情况,当我选择 gram 来执行一个函数时,当我在输入字段中输入一个值时,当我选择 pounds 时,我想要另一个函数来执行时我在输入
我有一个 GLSL 着色器,它从输入纹理的 channel 之一(例如 R)读取,然后写入输出纹理中的同一 channel 。该 channel 必须由用户选择。 我现在能想到的就是使用一个 int
我想根据下拉列表中的选定值生成输入文本框。 Options 2 3 4 5 就在这个选择框之后,一些输入字段应该按照选定的数字出现。 最佳答案 我建议您使用响应式(Reac
我是 SQL 新手,我想问一下如何根据首选项和分组选择条目。 +----------+----------+------+ | ENTRY_ID | ROUTE_ID | TYPE | +------
我有以下表结构: CREATE TABLE [dbo].[UTS_USERCLIENT_MAPPING_USER_LIST] ( [MAPPING_ID] [int] IDENTITY(1,1
我在移除不必要的床单时遇到了问题。我查看了不同的论坛并将不同的解决方案混合在一起。 此宏删除工作表(第一张工作表除外)。 Sub wrong() Dim sht As Object Applicati
我是一名优秀的程序员,十分优秀!