Android Studio:调用startActivityForResult

时间:2017-07-12 20:16:46

标签: java android xml crash

我正在为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>

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

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

任何帮助表示感谢,谢谢:)

编辑:崩溃的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

2 个答案:

答案 0 :(得分:0)

您需要将正数传递给startActivityForResult

我会尝试将this.startActivityForResult(i, v.getId());更改为this.startActivityForResult(i, 1);

您使用v.getId()是否有任何特定原因?

答案 1 :(得分:0)

您必须传递正在传递按钮ID的结果代码this.startActivityForResult(i, v.getId());,例如:this.startActivityForResult(i, 2);,并在onActivityResult

中检查它

if (resultCode == 2)

检查this