1

i have tried the code from these question at StackOverflow.

The sending routine is in a AsyncTask. The other code is similar to the code in the question.

When i am trying to send a image to the PC, i get a java.lang.NullPointerException caused at SendImageTask.java line 25 and line 14. I cannot understand the Exception. Can somebody help me? Here is the code: MainActivity:

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

private static final int SELECT_PICTURE = 1;

public static String selectedImagePath;
private ImageView img;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_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) {

            new SendImageTask().execute();

        }
    });
}
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 = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
}

SendImageTask

class SendImageTask extends AsyncTask<Void, Void, Void> {


@Override
protected Void doInBackground(Void... voids) {
    Socket sock;
    try {
        sock = new Socket("myip", 8000);
        System.out.println("Connecting...");

        // sendfile
        File myFile = new File (MainActivity.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();
    }
return null;
}
}
  • `SendImageTask.java line 25 and line 14.` Well what is on those lines? You should provide that info. We cannot count the lines you know ;-). Please post the complete exception. – greenapps Jan 19 '18 at 12:35
  • `cursor.moveToFirst();` You should check if cursor==null before use. And using a `getPath()` function is a bad idea as you can open an InputStream for the obtained uri instead of a FileInputStream for a file that you cannot find. – greenapps Jan 19 '18 at 12:37

2 Answers2

0

Do away with getPath().

FileInputStream fis = new FileInputStream(myFile);

Change that to

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

And use that stream like you did before.

greenapps
  • 11,154
  • 2
  • 16
  • 19
  • Hi, i tried your solution. But what is "data" at InputStream is = getContentResolver().openInputStream(data.getData()) ? And I get the error "cannot resolve the method getContentResolver" –  Jan 21 '18 at 12:38
  • Well the same data.getData() that we can see in the code you posted. – greenapps Jan 21 '18 at 15:53
  • You need a Context to call getContexResolver(). Add it as parameter to your asynctask or thread. It is unclear where you defined the async task class. – greenapps Jan 21 '18 at 15:56
0

As you can see your app crash at this line

  FileInputStream fis = new FileInputStream(myFile);

You can test with debugger and try to create a FileInputStream with your path, you will get "not file found"

This is because your path is not correct, your getpath function is not correct. If you want the path for an image take from the gallery you need to change your getPath function to this :

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;
}
Vodet
  • 1,491
  • 1
  • 18
  • 36
  • I have done it like your description. Now i get in the class "SendImageTask.java" an nullpointerexception at File myFile = new File (MainActivity.selectedImagePath); –  Jan 21 '18 at 12:36
  • Can you print the selectedImagePath when you try to create the file – Vodet Jan 21 '18 at 15:18