gpt4 book ai didi

java - Android Studio : App crashes when calling startActivityForResult

转载 作者:行者123 更新时间:2023-12-02 03:20:04 25 4
gpt4 key购买 nike

我正在开发一个文件传输应用程序,用于在 Android 和运行 Java 的计算机之间进行传输。我的文件打开对话框出现问题,该对话框应该在按下按钮时出现。

我知道它出现在哪一行,但我不知道为什么。我的所有权限都设置正确。该行是下面代码中带有一堆 ////////////////////// 的行:

MainActivity.java

package com.jmoore.aeft;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public OutputStream out = null;
public Socket socket = null;
public File myFile = null;
public byte[] buffer;
Button button;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = (Button) findViewById(R.id.sendB);
button.setOnClickListener(this);
}

public void onClick(View v) {
Intent i;
Toast.makeText(this,"INTENTNT CRETED",Toast.LENGTH_LONG).show();
i = new Intent(this, OpenFileActivity.class);
this.setContentView(R.layout.activity_open_file);
this.startActivityForResult(i, v.getId());//////////////////////////////////////////////////////////////////////////////////
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
EditText et = (EditText) findViewById(R.id.editText3);
if (resultCode == RESULT_OK) {
String fileName = data.getStringExtra("fileName");
String shortFileName = data.getStringExtra("shortFileName");

Toast.makeText(this,
"Selected File: " + fileName,
Toast.LENGTH_SHORT).show();


et.setText(shortFileName);

} else {
Toast.makeText(this,
"No File Selected, Cancel Or Back Pressed",
Toast.LENGTH_SHORT).show();
et.setText("");
}

//NETWORK STUFF HERE
try {
String IP = et.getText().toString();
socket = new Socket(IP, 25000);
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream in = new BufferedInputStream(fis);
in.read(buffer, 0, buffer.length);
out.flush();
out.close();
in.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

OpenFileActivity.java

package com.jmoore.aeft;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class OpenFileActivity extends Activity
implements OnClickListener, OnItemClickListener {

ListView LvList;

ArrayList<String> listItems = new ArrayList<String>();

ArrayAdapter<String> adapter;

Button BtnOK;
Button BtnCancel;

String currentPath = null;

String selectedFilePath = null; /* Full path, i.e. /mnt/sdcard/folder/file.txt */
String selectedFileName = null; /* File Name Only, i.e file.txt */

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_file);

try {
/* Initializing Widgets */
LvList = (ListView) findViewById(R.id.LvList);
BtnOK = (Button) findViewById(R.id.BtnOK);
BtnCancel = (Button) findViewById(R.id.BtnCancel);

/* Initializing Event Handlers */

LvList.setOnItemClickListener(this);

BtnOK.setOnClickListener(this);
BtnCancel.setOnClickListener(this);

//

setCurrentPath(Environment.getExternalStorageDirectory().getAbsolutePath() + "/");
} catch (Exception ex) {
Toast.makeText(this,
"Error in OpenFileActivity.onCreate: " + ex.getMessage(),
Toast.LENGTH_SHORT).show();
}
}

void setCurrentPath(String path) {
ArrayList<String> folders = new ArrayList<String>();

ArrayList<String> files = new ArrayList<String>();

currentPath = path;

File[] allEntries = new File(path).listFiles();

for (int i = 0; i < allEntries.length; i++) {
if (allEntries[i].isDirectory()) {
folders.add(allEntries[i].getName());
} else if (allEntries[i].isFile()) {
files.add(allEntries[i].getName());
}
}

Collections.sort(folders, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});

Collections.sort(files, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});

listItems.clear();

for (int i = 0; i < folders.size(); i++) {
listItems.add(folders.get(i) + "/");
}

for (int i = 0; i < files.size(); i++) {
listItems.add(files.get(i));
}

adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
adapter.notifyDataSetChanged();

LvList.setAdapter(adapter);
}

@Override
public void onBackPressed()
{
if (!currentPath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/")) {
setCurrentPath(new File(currentPath).getParent() + "/");
} else {
super.onBackPressed();
}
}

@Override
public void onClick(View v) {
Intent intent;

switch (v.getId()) {
case R.id.BtnOK:

intent = new Intent();
intent.putExtra("fileName", selectedFilePath);
intent.putExtra("shortFileName", selectedFileName);
setResult(RESULT_OK, intent);

this.finish();

break;
case R.id.BtnCancel:

intent = new Intent();
intent.putExtra("fileName", "");
intent.putExtra("shortFileName", "");
setResult(RESULT_CANCELED, intent);

this.finish();

break;
}
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String entryName = (String)parent.getItemAtPosition(position);
if (entryName.endsWith("/")) {
setCurrentPath(currentPath + entryName);
} else {
selectedFilePath = currentPath + entryName;

selectedFileName = entryName;

this.setTitle(this.getResources().getString(R.string.title_activity_open_file)
+ "[" + entryName + "]");
}
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jmoore.aeft">

<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>


<activity android:label="@string/title_activity_open_file" android:name=".OpenFileActivity"> </activity>

</application>

</manifest>

activity_main.xml

<?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="com.jmoore.aeft.MainActivity">


<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="IP Address"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/sendB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="Send"
app:layout_constraintLeft_toRightOf="@+id/editText3"
android:layout_marginRight="16dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="16dp" />

</android.support.constraint.ConstraintLayout>

activity_open_file.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ListView
android:id="@+id/LvList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >

</ListView>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<Button
android:id="@+id/BtnOK"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK" />

<Button
android:id="@+id/BtnCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel" />

</LinearLayout>

</LinearLayout>

我使用的是带有内置 Nexus 5 Android 8.0 模拟器的 Windows 10 64 位。

知道为什么我的应用程序会在那个地方崩溃吗?我在编辑器中没有错误,所以它一定是运行时错误(?)。

感谢任何帮助,谢谢:)

编辑: Logcat 崩溃结果:

07-12 14:23:19.196 5786-5786/com.jmoore.aeft E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jmoore.aeft, PID: 5786
java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
at android.support.v4.app.BaseFragmentActivityGingerbread.checkForValidRequestCode(BaseFragmentActivityGingerbread.java:91)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:856)
at com.jmoore.aeft.MainActivity.onClick(MainActivity.java:48)
at android.view.View.performClick(View.java:6219)
at android.view.View$PerformClick.run(View.java:24482)
at android.os.Handler.handleCallback(Handler.java:769)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
07-12 14:23:19.198 1555-2335/system_process W/ActivityManager: Force finishing activity com.jmoore.aeft/.MainActivity

最佳答案

您必须传递结果代码 this.startActivityForResult(i, v.getId()); 您正在传递按钮 id,例如:this.startActivityForResult(i, 2) ;,并且您在 onActivityResult 中检查它

if (resultCode == 2)

检查this .

关于java - Android Studio : App crashes when calling startActivityForResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45066766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com