0
我做了一個小方法來檢查定義的文件夾是否有特定擴展名的文件。我在run.pls上找到空點異常,以幫助查找errors.method正在檢查.mp4文件,如果找到並顯示消息,則返回true。檢查文件擴展名在android中
這裏是代碼:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView filecheck;
filecheck = (TextView) findViewById(R.id.filecheck);
filecheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (accept()) {
Toast.makeText(MainActivity.this, "Files Found", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Files Not Found", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean accept() {
final File pathname = new File("/sdcard/test/");
String files[] = pathname.list();
System.out.println(files.length);
for (String s : files) {
if (s.contains(".mp4")) {
System.out.println(s);
return true;
}
return false;
}
return false;
}
}
這裏是例外:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: jss.testmethods, PID: 23659
java.lang.NullPointerException
at jss.testmethods.MainActivity.accept(MainActivity.java:38)
at jss.testmethods.MainActivity$1.onClick(MainActivity.java:24)
at android.view.View.performClick(View.java:4478)
at android.view.View$PerformClick.run(View.java:18698)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
顯示帶有NullPointerException的logcat,並告訴哪個代碼行導致它。 – greenapps
'pathname.list()'可能返回null。所以空指針異常。使用前檢查。 – greenapps
's.contains(「。mp4」)'。更好:'s.endsWith(「.mp4」)'。 – greenapps