0

The whole code works fine and the application runs completely fine, But my problem is getting the string value of the result TextView from another java class.

In the classifyImage() method, the " result.setText(classes[maxPos]); " works and it changes the Text of the result TextView, but I cant seem to get the text value of result from another java class. it just returns blank.

Im gonna put my whole MainActivity below, but just skip to the classifyImage() method the part where result.setText(classes[maxPos]); is located, since that's where my problem is focusing. and I also pasted my 2nd Java class below.

public class MainActivity extends AppCompatActivity {

    TextView result, confidence;
    ImageView imageView;
    Button picture, gallery, guides;
    int imageSize = 224;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        result = findViewById(R.id.result);
        confidence = findViewById(R.id.confidence);
        imageView = findViewById(R.id.imageView);
        picture = findViewById(R.id.button);
        gallery = findViewById(R.id.button2);
        guides = findViewById(R.id.button3);

        picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Launch camera if we have permission
                if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, 3);
                } else {
                    //Request camera permission if we don't have it.
                    requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
                }
            }
        });

        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(cameraIntent, 1);
            }
        });

        guides.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {

                startActivity(new Intent(MainActivity.this, PlantInfoActivity.class));

            }
        });
    }


    public void classifyImage(Bitmap image) {

        PlantClasses PlantClass = new PlantClasses();
        PlantInfoActivity PlantInfo = new PlantInfoActivity();

        try {
            Model model = Model.newInstance(getApplicationContext());

            // Creates inputs for reference.
            TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.FLOAT32);
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * imageSize * imageSize * 3);
            byteBuffer.order(ByteOrder.nativeOrder());

            // get 1D array of 224 * 224 pixels in image
            int[] intValues = new int[imageSize * imageSize];
            image.getPixels(intValues, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());

            // iterate over pixels and extract R, G, and B values. Add to bytebuffer.
            int pixel = 0;
            for (int i = 0; i < imageSize; i++) {
                for (int j = 0; j < imageSize; j++) {
                    int val = intValues[pixel++]; // RGB
                    byteBuffer.putFloat(((val >> 16) & 0xFF) * (1.f / 255.f));
                    byteBuffer.putFloat(((val >> 8) & 0xFF) * (1.f / 255.f));
                    byteBuffer.putFloat((val & 0xFF) * (1.f / 255.f));
                }
            }

            inputFeature0.loadBuffer(byteBuffer);

            // Runs model inference and gets result.
            Model.Outputs outputs = model.process(inputFeature0);
            TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();

            float[] confidences = outputFeature0.getFloatArray();
            // find the index of the class with the biggest confidence.
            int maxPos = 0;
            float maxConfidence = 0;
            for (int i = 0; i < confidences.length; i++) {
                if (confidences[i] > maxConfidence) {
                    maxConfidence = confidences[i];
                    maxPos = i;
                }
            }

            String[] classes = PlantClass.plantclass;

            result.setText(classes[maxPos]);
            confidence.setText(String.format("%.1f%%", maxConfidence * 100));
            guides.setVisibility(View.VISIBLE);

            // Releases model resources if no longer used.
            model.close();

        } catch (IOException e) {
            // TODO Handle the exception
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode == RESULT_OK){
            if(requestCode == 3){
                Bitmap image = (Bitmap) data.getExtras().get("data");
                int dimension = Math.min(image.getWidth(), image.getHeight());
                image = ThumbnailUtils.extractThumbnail(image, dimension, dimension);
                imageView.setImageBitmap(image);


                image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);
                Intent intent = new Intent(MainActivity.this, PlantInfoActivity.class);
                intent.putExtra("image", image);

                classifyImage(image);

            }else{
                Uri dat = data.getData();
                Bitmap image = null;
                try {
                    image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), dat);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                imageView.setImageBitmap(image);

                image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);
                Intent intent = new Intent(MainActivity.this, PlantInfoActivity.class);
                intent.putExtra("image", image);

                classifyImage(image);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}

Below is the 2nd class where I want to use the value of result. I aim to change the value of plantname2 to the same value of result. specifically i want to set the Text of plantname2 to the same Text as result. but i still cant seem to retrieve the string value of result in the main activity.

public class PlantInfoActivity extends AppCompatActivity {

    MainActivity MainAct = new MainActivity();


    Button backbutton;
    ImageView imageView2;
    TextView plantname2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plant_info);

        plantname2 = findViewById(R.id.plantname2);
        backbutton = findViewById(R.id.backbutton);
        imageView2 = findViewById(R.id.imageView2);

        backbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

}

Context of the program. it uses image recognition to identify plants, after selecting a photo from the gallery or taking a picture, it identifies the plants by outputting the image of the plant above and outputting the name of plant which is the result. and the confidence rate value of the plant.

THEN THIS IS WHERE THE PROBLEM BEGINS there is a button that switches to a new activity to show more texts/information about the plant. there is a TextView in that new activity where it should suppose to display the same Value of the result.

I've tried adding this to my 2nd java class in the onCreate method.

String resultString = MainAct.result.getText().toString();
        plantname2.setText(resultString);

But it just seems to crash after switching to the other activity.

I've also tried using the MainActivity's classifyImage() method to change the TextView of the 2nd Activity. but it just crashes after selecting a photo.

            result.setText(classes[maxPos]);
            confidence.setText(String.format("%.1f%%", maxConfidence * 100));
            guides.setVisibility(View.VISIBLE);

            PlantInfo.plantname2.setText(classes[maxPos]);

I've Tried testing and declaring public strings outside the onCreate method. and setting the string to a fixed value just to test. like

String plantname = "test"

and use that call that variable in the 2nd class and use it to set the text. IT WORKS but when i try to change it to a value from the result. it just crashes.

please Bear with me and my problems, im still learning Java and im at lost now, i hope you guys can help me. thanks in advance.

  • `MainActivity MainAct = new MainActivity();` you should *never* create an activity instance like this. This will make a whole new activity (not the same as the one that was shown previously) and it will not be correctly bound to its lifecycle, so many things will be null and crash if you try to use it. You should use an intent to pass data from one activity to another. Have a look [here](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application). – Tyler V Apr 22 '23 at 15:47

1 Answers1

0

You can't just reference one activity view's data in the other activity. Pass the data with the Intent when you switch activities as you have done here.

Intent intent = new Intent(MainActivity.this, PlantInfoActivity.class);
            intent.putExtra("image", image);

Pass the value of content of 'result' with the intent when you switch activities. That should solve the problem.

Lakshmi
  • 92
  • 1
  • 7
  • Thanks dude! helped me quite alot! adding the new Intent inside the classify image just seem to crash after switching to the new activity. though it took me an hour but i managed to figure it out. adding the intent code inside the button that switches to the other activity worked. – AsianOnCode Apr 23 '23 at 08:16