0

My android app was supposed to send an image to a local java server via sockets and after processing the image the result has to be sent to the app again and i am supposed to display it in the text view.I have successfully received the result but while i am trying to display the result in the text view the app crashes showing the following error.

Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference

I am new to Android programming.I have tried many things but couldnt solve it.Please help me! Thanks in advance!

Code: Main Activity

package com.example.image1;

import android.app.Activity;
import android.app.MediaRouteButton;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
import java.util.Objects;

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

    private static final int SELECT_PICTURE = 1;
    private static final int GET_PICTURE =1 ;
    private PrintWriter printwriter;
    public static String selectedImagePath;
    public static String selectedImageUri;
    private ImageView img;
    public static  String st;
    TextView status1;
    @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 send = (Button) findViewById(R.id.bSend);
        //status = (TextView) findViewById(R.id.tvStatus);
        status1 = (TextView) findViewById(R.id.result);
        ((Button) findViewById(R.id.bBrowse))
                .setOnClickListener(new View.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");

        //status1.setText("fjfjf");
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //status1.setText("fjfjf");
                new SendImageTask().execute();

                //final TextView status1 = (TextView) findViewById(R.id.result);
                //status1.setText(s);
            }
        });
    }
    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;
    }


}


        SendImageTask code

package com.example.image1;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import java.text.BreakIterator;

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

    private PrintWriter printwriter;
    private Bitmap IOUtils;
    private BreakIterator status1;
    private static String st;



    @SuppressLint("WrongThread")
    @Override
    protected String doInBackground(Void... voids) {
        Socket sock;
        try {

            sock = new Socket("192.168.43.120", 8000);
            System.out.println("Connecting...");


            System.out.println("Sending...");

            String s = getFileToByte(MainActivity.selectedImagePath);
            System.out.println(s);

            printwriter = new PrintWriter(sock.getOutputStream(), true);
            printwriter.write(String.valueOf(s)); // write the message to output stream
            printwriter.flush();
            printwriter.close();


            sock.close();

            try {
                System.out.println("Another socket");
                Socket sock1 = new Socket("192.168.43.120", 6000);
                System.out.println("Connecting1...");

                InputStreamReader streamReader = new InputStreamReader(sock1.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);
                st = reader.readLine();
                System.out.println(st);
                System.out.println("ascscasc");

                sock1.close();
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return st;
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return st;
    }
    protected  void onPostExecute(String st){
        System.out.println("asasdcwdcwdc");
        System.out.println(st);
        status1.setText(String.valueOf(st));
    }
    public static String getFileToByte(String filePath){
        Bitmap bmp = null;
        ByteArrayOutputStream bos = null;
        byte[] bt = null;
        String encodeString = null;
        try{
            bmp = BitmapFactory.decodeFile(filePath);
            bos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bt = bos.toByteArray();
            encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        String str1=encodeString.replaceAll("[\r\n]+", " ");
        str1 = str1.replaceAll("\\s+","");
        return "data:image/jpeg;base64,"+str1+"/n";
    }

}

First my app was crashing because i was doing the textView operation in the doInBackground method and then after only i learnt that ui operations cant be done there. So then i executed those commands in onPostExecute method.But still my app is crashing saying NullPointerException.I will also include the logcat here.Thanks in advance.

Logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.image1, PID: 20241
    java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference
        at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:147)
        at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:19)
        at android.os.AsyncTask.finish(AsyncTask.java:667)
        at android.os.AsyncTask.-wrap1(AsyncTask.java)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:186)
        at android.app.ActivityThread.main(ActivityThread.java:6509)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:804)
I/Process: Sending signal. PID: 20241 SIG: 9
Rama
  • 3
  • 3
  • 1
    `status1` in `SendImageTask` is `null`, because you never assign a value to it. – CommonsWare Jun 06 '20 at 14:24
  • @CommonsWare I dont understand ,what should i assign it to? – Rama Jun 06 '20 at 14:26
  • 2
    Well, you declared it to be an instance of `BreakIterator`. I have never used that class, but [the JavaDocs](https://developer.android.com/reference/java/text/BreakIterator) show a few `static` factory methods for it. You would need to choose one. Also, note that your `onActivityResult()` has problems, as [there is no requirement that `ACTION_GET_CONTENT` return something that has a `DATA` column that points to a file on the filesystem that you can access](https://stackoverflow.com/a/54843979/115145). Also note that `AsyncTask` is deprecated starting with Android 11. – CommonsWare Jun 06 '20 at 14:34

1 Answers1

1

You need to initialize your BreakIterator object status1 otherwise it would be null.

I've not used BreakIterator, but a quick look at the docs shows that this is how you get an instance.

BreakIterator status1 = BreakIterator.getWordInstance();

Bottom line is to initialize it before using it.

varunkr
  • 5,364
  • 11
  • 50
  • 99
  • The `BreakIterator` constructor is `protected` according to [the JavaDocs](https://developer.android.com/reference/java/text/BreakIterator). – CommonsWare Jun 06 '20 at 14:31
  • @varunkr Still getting the same error stating null object reference – Rama Jun 06 '20 at 14:51
  • @Rama your problem is a very common and basic one. Null pointer exception occurs when the object on which you are calling the method is null. So in this case, your status1 is null. You need to make sure that it has a non-null value before you set Text on it. Hard to say what is going wrong now, without debugging it. You'd need to debug your code and see if your status1 variable is non-null before you call setText on it and make sure it is non-null. – varunkr Jun 06 '20 at 14:54