如何从Android设备中选择文件并发送到服务器。运行后,我的主要活动将导致onresume
活动错误。因为在选择文件后,它会在运行时异常时给出nullpointer
。
btnUpload = (Button) findViewById(R.id.btnUploadPhoto);
btnUpload.setOnClickListener(this);
btnDownload.setOnClickListener(this);
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(Constants.DROPBOX_APP_KEY,
Constants.DROPBOX_APP_SECRET);
AndroidAuthSession session;
String[] stored = getKeys();
if (stored != null) {
AccessTokenPair accessToken = new AccessTokenPair(stored[0],
stored[1]);
session = new AndroidAuthSession(appKeyPair, Constants.ACCESS_TYPE,
accessToken);
} else {
session = new AndroidAuthSession(appKeyPair, Constants.ACCESS_TYPE);
}
return session;
}
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(
Constants.ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(Constants.ACCESS_KEY_NAME, null);
String secret = prefs.getString(Constants.ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
@Override
public void onClick(View v) {
if (v == btnDownload) {
startActivity(new Intent(MainActivity.this, DropboxDownload.class));
} else if (v == btnUpload) {
createDir();
if (mLoggedIn) {
logOut();
}
// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// f = new File(Utils.getPath(),new Date().getTime()+".jpg");
// intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
// intent.setType("file/*");
// startActivityForResult(intent,TAKE_PHOTO);
//Intent intent = new Intent(MediaStore.ACTION_GET_CONTENT);
// startActivityForResult(intent, TAKE_PHOTO);
/* Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, TAKE_PHOTO); */
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
Intent f = Intent.createChooser(intent, "File");
startActivityForResult(f, TAKE_PHOTO);
}
}
private void logOut() {
mApi.getSession().unlink();
clearKeys();
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(
Constants.ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private void createDir() {
File dir = new File(Utils.getPath());
if (!dir.exists()) {
dir.mkdirs();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == TAKE_PHOTO) {
// f = new File(Utils.getPath() + "/temp.jpg");
if (Utils.isOnline(MainActivity.this)) {
mApi.getSession().startAuthentication(MainActivity.this);
onResume = true;
} else {
Utils.showNetworkAlert(MainActivity.this);
}
}
}
}
public void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
UploadFile upload = new UploadFile(MainActivity.this, mApi, DIR, f);
upload.execute();
onResume = true;
}
}
private void storeKeys(String key, String secret) {
SharedPreferences prefs = getSharedPreferences(
Constants.ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(Constants.ACCESS_KEY_NAME, key);
edit.putString(Constants.ACCESS_SECRET_NAME, secret);
edit.commit();
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
@Override
protected void onResume() {
AndroidAuthSession session = mApi.getSession();
if (session.authenticationSuccessful()) {
try {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(onResume);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:"
+ e.getLocalizedMessage());
}
}
super.onResume();
}
}
这是我的崩溃报告:
01-25 13:30:20.629 9008-9008/com.example.pranit.cloudexample W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x419eacf8)
01-25 13:30:20.629 9008-9008/com.example.pranit.cloudexample W/dalvikvm: threadid=1: uncaught exception occurred
01-25 13:30:20.630 9008-9008/com.example.pranit.cloudexample W/System.err: java.lang.RuntimeException: Unable to resume activity {com.example.pranit.cloudexample/com.example.pranit.cloudexample.MainActivity}: java.lang.NullPointerException
01-25 13:30:20.631 9008-9008/com.example.pranit.cloudexample W/System.err: at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3003)
01-25 13:30:20.631 9008-9008/com.example.pranit.cloudexample W/System.err: at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3032)
01-25 13:30:20.631 9008-9008/com.example.pranit.cloudexample W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
01-25 13:30:20.632 9008-9008/com.example.pranit.cloudexample W/System.err: at android.os.Handler.dispatchMessage(Handler.java:110)
01-25 13:30:20.632 9008-9008/com.example.pranit.cloudexample W/System.err: at android.os.Looper.loop(Looper.java:193)
01-25 13:30:20.632 9008-9008/com.example.pranit.cloudexample W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5333)
01-25 13:30:20.632 9008-9008/com.example.pranit.cloudexample W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
01-25 13:30:20.632 9008-9008/com.example.pranit.cloudexample W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
01-25 13:30:20.632 9008-9008/com.example.pranit.cloudexample W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
01-25 13:30:20.632 9008-9008/com.example.pranit.cloudexample W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
01-25 13:30:20.633 9008-9008/com.example.pranit.cloudexample W/System.err: at dalvik.system.NativeStart.main(Native Method)
01-25 13:30:20.633 9008-9008/com.example.pranit.cloudexample W/System.err: Caused by: java.lang.NullPointerException
01-25 13:30:20.638 9008-9008/com.example.pranit.cloudexample W/System.err: at com.example.pranit.cloudexample.UploadFile.<init>(UploadFile.java:76)
01-25 13:30:20.638 9008-9008/com.example.pranit.cloudexample W/System.err: at com.example.pranit.cloudexample.MainActivity.setLoggedIn(MainActivity.java:162)
01-25 13:30:20.638 9008-9008/com.example.pranit.cloudexample W/System.err: at com.example.pranit.cloudexample.MainActivity.onResume(MainActivity.java:194)
01-25 13:30:20.639 9008-9008/com.example.pranit.cloudexample W/System.err: at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1197)
01-25 13:30:20.639 9008-9008/com.example.pranit.cloudexample W/System.err: at android.app.Activity.performResume(Activity.java:5422)
01-25 13:30:20.639 9008-9008/com.example.pranit.cloudexample W/System.err: at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
01-25 13:30:20.640 9008-9008/com.example.pranit.cloudexample W/System.err: ... 10 more
01-25 13:30:20.640 9008-9008/com.example.pranit.cloudexample W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
01-25 13:30:20.647 9008-9008/com.example.pranit.cloudexample E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.pranit.cloudexample, PID: 9008
java.lang.RuntimeException: Unable to resume activity {com.example.pranit.cloudexample/com.example.pranit.cloudexample.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3003)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3032)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.pranit.cloudexample.UploadFile.<init>(UploadFile.java:76)
at com.example.pranit.cloudexample.MainActivity.setLoggedIn(MainActivity.java:162)
at com.example.pranit.cloudexample.MainActivity.onResume(MainActivity.java:194)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1197)
at android.app.Activity.performResume(Activity.java:5422)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3032)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
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:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
如果您的设备/模拟器&gt; api 24
由于权限问题而产生此崩溃作为android M和N的新规则。
因此,如果您正在为文件选择器工作,请为用户提供有关// GameScene.swift
// StackOverflow
//
// Created by Sumner on 1/17/17.
// Copyright © 2017 Sumner. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var cam: SKCameraNode!
var sprite = SKSpriteNode(imageNamed: "sprite")
var sprite2 = SKSpriteNode(imageNamed: "sprite2")
let pauseLabel = SKLabelNode(text: "Pause!")
/*
*
* START: NEW CODE
*
*/
let gameNode = SKNode()
var pauseMenuSprite: SKShapeNode!
let pauseMenuTitleLabel = SKLabelNode(text: "Pause Menu")
let pauseMenuContinueLabel = SKLabelNode(text: "Resume game?")
let pauseMenuToMainMenuLabel = SKLabelNode(text: "Main Menu?")
/*
*
* END: NEW CODE
*
*/
var timeStart: Date!
init(size: CGSize, difficulty: String) {
super.init(size: size)
gameDifficulty = difficulty
timeStart = Date()
/*
*
* START: NEW CODE
*
*/
pauseMenuSprite = SKShapeNode(rectOf: size)
/*
*
* END: NEW CODE
*
*/
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
backgroundColor = SKColor.white
print("Game starting with \(gameDifficulty) difficulty")
// Scale Sprites
sprite.setScale(0.3)
sprite2.setScale(0.3)
sprite.position = CGPoint(x: size.width/4,y: size.height/2)
sprite2.position = CGPoint(x: size.width/4 * 3,y: size.height/2)
/*
*
* START: NEW CODE
*
*/
gameNode.addChild(sprite)
gameNode.addChild(sprite2)
addChild(gameNode)
/*
*
* END: NEW CODE
*
*/
if gameDifficulty == "hard" {
let sprite3 = SKSpriteNode(imageNamed: "sprite")
sprite3.setScale(0.3)
sprite3.position = CGPoint(x: size.width/4 * 2,y: size.height/2)
addChild(sprite3)
}
pauseLabel.fontColor = SKColor.black
pauseLabel.position = CGPoint(x: size.width/4 * 2,y: size.height/4)
addChild(pauseLabel)
}
func touchDown(atPoint pos : CGPoint) {
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let touchLocation = touch!.location(in: self)
let pausedTouchLocation = touch?.location(in: pauseMenuSprite)
if sprite.contains(touchLocation) {
print("You tapped the blue sprite")
/*
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let menuScene = MenuScene(size: self.size)
self.view?.presentScene(menuScene, transition: reveal)
}
alert.addAction(action)
if let vc = self.scene?.view?.window?.rootViewController {
vc.present(alert, animated: true, completion: nil)
}
*/
}
if sprite2.contains(touchLocation) {
print("You tapped the purple sprite")
let now = Date()
let howLong = now.timeIntervalSinceReferenceDate - timeStart.timeIntervalSinceReferenceDate
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let scoreScene = ScoreScene(size: self.size, score: howLong)
self.view?.presentScene(scoreScene, transition: reveal)
}
/*
*
* START: NEW CODE
*
*/
if pauseMenuContinueLabel.contains(pausedTouchLocation!) {
pauseMenuSprite.removeFromParent()
pauseMenuSprite.removeAllChildren()
gameNode.isPaused = true
}
if pauseMenuToMainMenuLabel.contains(pausedTouchLocation!) {
let reveal = SKTransition.doorsOpenVertical(withDuration: 0.5)
let menuScene = MenuScene(size: self.size)
self.view?.presentScene(menuScene, transition: reveal)
}
if pauseLabel.contains(touchLocation) {
print("pause")
setParametersForPauseMenu(size: size)
addChild(pauseMenuSprite)
gameNode.isPaused = true
}
/*
*
* END: NEW CODE
*
*/
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
/*
*
* START: NEW CODE
*
*/
func setParametersForPauseMenu(size: CGSize) {
pauseMenuSprite.fillColor = SKColor.white
pauseMenuSprite.alpha = 0.85
pauseMenuSprite.position = CGPoint(x: size.width / 2, y: size.height / 2)
pauseMenuSprite.zPosition = 100
pauseMenuTitleLabel.fontColor = SKColor.black
pauseMenuContinueLabel.fontColor = SKColor.black
pauseMenuToMainMenuLabel.fontColor = SKColor.black
pauseMenuTitleLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 )
pauseMenuContinueLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 * 4 )
pauseMenuToMainMenuLabel.position = CGPoint(x: 0 ,y: size.height / 2 - pauseMenuSprite.frame.size.height / 6 * 5)
pauseMenuSprite.addChild(pauseMenuTitleLabel)
pauseMenuSprite.addChild(pauseMenuContinueLabel)
pauseMenuSprite.addChild(pauseMenuToMainMenuLabel)
}
/*
*
* END: NEW CODE
*
*/
}
和android.permission.WRITE_EXTERNAL_STORAGE
或参考Android 6.0 Marshmallow. Cannot write to SD Card
其他分享崩溃日志。
答案 1 :(得分:0)
@Pranit
尝试
@Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
try {
if (session.authenticationSuccessful()) {
session.finishAuthentication();
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(onResume);
}
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:"
+ e.getLocalizedMessage());
}
}