无法使用 java 套接字将图像从 android studio 发送到 pc,filePath 返回 null

Posted

技术标签:

【中文标题】无法使用 java 套接字将图像从 android studio 发送到 pc,filePath 返回 null【英文标题】:Can not send image from android studio to pc using java sockets, filePath returns null 【发布时间】:2021-11-23 20:45:03 【问题描述】:

我尝试了Client-Server: File transfer from android to PC connected via socket 中的代码,但应用程序在发送图像时崩溃。选择图像后,图像的路径返回 null。该应用正在模拟器上运行。

我当前的代码是 MainActivity:

package com.example.floweridentifier;

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

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity 
    /** Called when the activity is first created. */

    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    private ImageView img;

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        System.out.println("34");
        img = (ImageView) findViewById(R.id.ivPic);
        System.out.println("36");
        ((Button) findViewById(R.id.bBrowse))
                .setOnClickListener(new OnClickListener() 
                    public void onClick(View arg0) 
                        System.out.println("40");
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(
                                Intent.createChooser(intent, "Select Picture"),
                                SELECT_PICTURE);
                        System.out.println("47");
                    
                );
        ;
        System.out.println("51");
        Button send = (Button) findViewById(R.id.bSend);
        final TextView status = (TextView) findViewById(R.id.tvStatus);

        send.setOnClickListener(new View.OnClickListener() 

            @Override
            public void onClick(View arg0) 

                Socket sock;
                try 
                    sock = new Socket("My pc's public ip", 800);
                    System.out.println("Connecting...");

                    // sendfile
                    File myFile = new File (selectedImagePath);
                    byte [] mybytearray  = new byte [(int)myFile.length()];
                    FileInputStream fis = new FileInputStream(myFile);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    bis.read(mybytearray,0,mybytearray.length);
                    OutputStream os = sock.getOutputStream();
                    System.out.println("Sending...");
                    os.write(mybytearray,0,mybytearray.length);
                    os.flush();

                    sock.close();
                 catch (UnknownHostException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                 catch (IOException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                



            
        );
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
        if (resultCode == RESULT_OK) 
            if (requestCode == SELECT_PICTURE) 
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                TextView path = (TextView) findViewById(R.id.tvPath);
                path.setText("Image Path : " + selectedImagePath);
                img.setImageURI(selectedImageUri);
            
        
    

    public String getPath(Uri uri) 
        String[] projection = MediaStore.Images.Media.DATA;
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(projection[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.floweridentifier">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <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/Theme.FlowerIdentifier">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.FlowerIdentifier.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvStatus"
        android:layout_
        android:layout_
        android:text="@string/hello" />

    <TextView
        android:id="@+id/tvPath"
        android:layout_
        android:layout_
        android:text="@string/path" />

    <Button
        android:id="@+id/bBrowse"
        android:layout_
        android:layout_
        android:text="@string/browse" />

    <Button
        android:id="@+id/bSend"
        android:layout_
        android:layout_
        android:text="@string/send" />

    <ImageView
        android:id="@+id/ivPic"
        android:layout_
        android:layout_
        android:contentDescription="@string/todo">
    </ImageView>

</LinearLayout>
strings.xml

字符串.xml

<resources>
    <string name="app_name">Flower identifier</string>
    <string name="action_settings">Settings</string>
    <!-- Strings used for fragments for navigation -->
    <string name="first_fragment_label">First Fragment</string>
    <string name="second_fragment_label">Second Fragment</string>
    <string name="next">Next</string>
    <string name="previous">Previous</string>

    <string name="hello_first_fragment">Hello first fragment</string>
    <string name="hello_second_fragment">Hello second fragment. Arg: %1$s</string>
    <string name="hello">Flower identifier</string>
    <string name="path">Path</string>
    <string name="browse">browse</string>
    <string name="send">send</string>
    <string name="todo">todo</string>
</resources>

【问题讨论】:

不要使用空路径。不要让您的应用程序崩溃开始。你的意思是selectedImagePath 吗?如果是,那你为什么不说? 进一步你的应用程序崩溃不是 NullPointerException 而是 NetworkOnMainThreadException。 请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example。 【参考方案1】:
FileInputStream fis = new FileInputStream(myFile);
             

替换为:

InputStream is = getContentResolver().openInputStream(data.getData());

并使用is 而不是fis

丢弃 selectedImagePath。

【讨论】:

以上是关于无法使用 java 套接字将图像从 android studio 发送到 pc,filePath 返回 null的主要内容,如果未能解决你的问题,请参考以下文章

无法连接到android上的蓝牙套接字

无法将图像文件从 Android 应用程序发布到托管在 Tomcat 上的 Java servlet

使用python套接字编程将图像文件从服务器传输到客户端

如何通过套接字发送和接收图像

从android客户端通过套接字发送后收到黑色图像

发送图像时出现 Python 套接字错误。无法解码字节/意外 EOF