Java Android Studio:调用startActivityForResult时应用程序崩溃

Java Android Studio:调用startActivityForResult时应用程序崩溃,java,android,xml,crash,Java,Android,Xml,Crash,我正在开发一个文件传输应用程序,用于Android和运行Java的计算机之间的传输。我的文件打开对话框有问题,该对话框应该在按下按钮时出现 我知道它发生在哪一行,但我不知道为什么。我的所有权限都设置正确。该行在下面的代码中包含一组////: MainActivity.java package com.jmoore.aeft; import android.app.AlertDialog; import android.content.Context; import android.conten

我正在开发一个文件传输应用程序,用于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();
        }
    }
}
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 + "]");
        }
    }
}
OpenFileActivity.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();
        }
    }
}
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 + "]");
        }
    }
}

您需要将正数传递给
startActivityForResult

我会尝试更改
这个.startActivityForResult(I,v.getId())类似于
this.startActivityForResult(i,1)


您使用
v.getId()
有什么具体原因吗?

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

if(resultCode==2)


检查。

我仍然希望看到我编辑的堆栈跟踪(Logcat)@KristyWelsh,以显示Logcat结果。您能详细说明吗?我从另一个论坛网站借用了代码,所以我不知道第二个参数到底是什么。是的,我刚刚编辑了我的答案,你想在其中包含正数。我猜v.getId()返回的是负数或大于65535的数字。谢谢您的回复。我刚刚使用完易卜拉欣的答案,它起了作用,当我刷新页面时,我看到你更新了答案。不过,谢谢你的帮助,这也行:)谢谢你,我会试试这个。是的!这个给我修好了。谢谢你的帮助:)
<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>
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