Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So my application is an Image to text and text-to-speech app. The idea is to scan text from any source and it is read out to the user. The basic functionality of the app is working, when I click on "Capture Image" on the main screen, it opens the camera, takes a pic, and extracts text. But I also added another function where the user can manually add pictures from his gallery by clicking on the gallery icon.

So the problem is when I select the gallery and choose my own image, it won't add to the main image view canvas, instead, it crashes the application. There is no error in the code, but it just won't run.

Here are 20-second clips I have attached on Google Drive to show you the precise problem for a better understanding for you all. I’m very close!

https://drive.google.com/drive/folders/18oCeFkVEvi1xPv_O4DEI3EZz0TtVyZ36?usp=sharing

Kindly please let me know what the problem is, as Android studio does not give any warnings or errors when the project is run.

Please open the Google Drive link for better understanding, the below code is mainly for the image icon shown on the top right, in the action bar to import images from Gallery and camera.

What I have tried:

MAIN ACTIVITY JAVA
Java
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
    ImageView imageView;
    TextView textView;
    private TextToSpeech engine;




 
    private void showImageImportDialog() {
        //Options or Items displayed in dialog once it is clicked

        String[] items = {"Camera", "Gallery"};
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);

        //Set TITLE
        dialog.setTitle("Select Image");

        dialog.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    //Camera Option Clicked
                    if (!checkCameraPermission()) {
                        ///Camera permission is not allowed, thats why we request it here
                        requestCameraPermission();
                    } else {
                        //Permission allowed, take picture
                        pickCamera();
                    }
                }

                if (which == 1) {
                    //Gallery Option Clicked
                    if (!checkStoragePermission()) {
                        //Storage Permissions Granted
                        requestStoragePermission();
                    } else {
                        //Permission allowed, take picture
                        pickGallery();
                    }
                }
            }
        });
        dialog.create().show(); //SHOW DIALOG
    }

    private void pickGallery() {
        //Intent to Pick image from gallery
        Intent intent = new Intent(Intent.ACTION_PICK);
        //Set intent type to image
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);

        int GET_FROM_GALLERY = 3;
        startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
    }

    private void pickCamera() {
        //Takes Image from Camera and saves it in storage for HIGH QUALITY
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "NewPic"); //TITLE OF THE PIC

        values.put(MediaStore.Images.Media.DESCRIPTION, "Images to text"); //Description
        image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
        startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);

    }

    private void requestStoragePermission() {
        ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
    }

    private boolean checkStoragePermission() {
        boolean result = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
        return result;
    }

    private void requestCameraPermission() {
        ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_REQUEST_CODE);
    }

    private boolean checkCameraPermission() {

        boolean result = ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);

        boolean result1 = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
        return result && result1;

    }
    //Also add gallery permission.





    String cameraPermission[];

    String storagePermission[];
    Uri image_uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        engine = new TextToSpeech(this, this);

        if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //Grants Permission and Prompts User
            requestPermissions(new String[]{Manifest.permission.CAMERA}, 101);

        }
    }

   

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    { if(resultCode == RESULT_OK) {
        super.onActivityResult(requestCode, resultCode, data);


        Bundle bundle = data.getExtras();

        //From bundle extract image
        Bitmap bitmap = (Bitmap) bundle.get("data");


        task.addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(FirebaseVisionText firebaseVisionText) {
                String s = firebaseVisionText.getText();
                textView.setText(s);

                //Conversion of text to speech
                String rawText = String.valueOf(textView.getText());

                speakText(rawText);
                ;               /* tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
                    @Override
                    public void onInit(int i) {
                        if (i == TextToSpeech.SUCCESS) {
                            //SELECTING LANGUAGE
                            int lang = tts.setLanguage(Locale.ENGLISH);

                        }
                    }
                });*/


            }


        });

  
    public void speakText(String textContents) {

        //String textContents = text.getText().toString();
        engine.speak(textContents, TextToSpeech.QUEUE_FLUSH, null, null);

    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @Override
    public void onInit(int i) {


        if (i == TextToSpeech.SUCCESS) {
            //Setting speech Language
            engine.setLanguage(Locale.ENGLISH);
            engine.setPitch(1);
        }
    }

    ///Handle Permission Result
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:

                if (grantResults.length > 0) {
                    boolean cameraAccepted = grantResults[0] ==
                            PackageManager.PERMISSION_GRANTED;
                    //Changed from 0 to 1
                    boolean writeStorageAccepted = grantResults[1] ==
                            PackageManager.PERMISSION_GRANTED;

                    if (cameraAccepted && writeStorageAccepted) {
                        pickCamera();
                    } else {
                        Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();

                    }
                }
                break;

            case STORAGE_REQUEST_CODE: {
                boolean writeStorageAccepted = grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED;
                if (writeStorageAccepted) {
                    pickGallery();
                } else {
                    Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();

                }
            }
            break;

        }


    }

 
}


Activity_MainXML
XML
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!-- Added scroll view, made sure scroll view has only one child in it. Very time consuming -->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:ignore="UselessParent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:ignore="UselessLeaf" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Image Preview:"
                android:verticalScrollbarPosition="defaultPosition"
                android:textColor="@color/design_default_color_primary_dark"
                android:textSize="22sp"
                tools:ignore="HardcodedText">

            </TextView>


            <ImageView

                android:id="@+id/imageId"
                android:layout_width="353dp"
                android:layout_height="368dp"
                android:layout_margin="26dp" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="63dp"
                android:onClick="doProcess"
                android:text="Capture Image" />

            <TextView
                android:id="@+id/textId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Result:"
                android:textColor="@color/design_default_color_primary_dark"
                android:textSize="22sp" />


        </LinearLayout>
    </ScrollView>

</LinearLayout>


AndroidManifest XML
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.textrecognition">

    <!-- User Permissions to give access to camera -->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>



    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Dream Eye Text Recognizer"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TextRecognition">
        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity
            android:name=".ui.login.LoginActivity"
            android:label="@string/title_activity_login" />

        <meta-data
            android:name="com.google.firebase.ml.vision.DEPENDENCIES"
            android:value="ocr" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <!-- Crop image Activity  -->
        <activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
            android:theme="@style/Base.Theme.AppCompat"/> <!-- or AppTheme optional (needed if default theme has no action bar) -->

    </application>

</manifest> 
Posted
Updated 17-Jul-21 0:52am
v8
Comments
Richard MacCutchan 17-Jul-21 6:31am    
"Kindly please let me know what the problem is"
The problem is somewhere in all that (400+ lines) code, but there is far too much for anyone here to be able to tell what it is or even where. You need to do some debugging and provide more detailed information for anyone to be able to help you.
Badar Ismail 17-Jul-21 6:51am    
Yes you are right. Im sorry about that, that's the problem with Android Studio. Anyways I have updated it a little now, is it okay?
[no name] 17-Jul-21 13:17pm    
You need "something" to "catch" any errors.

https://www.w3schools.com/java/java_try_catch.asp

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900