Search code examples
androidandroid-intentandroid-camera2

App goes back to wrong activity after exiting camera intent


I'm trying to write an app that, in part, creates a database of images that are organized by category. I'm having trouble using an intent to access the camera. I'm able to enter the camera and take an image, but the app goes back to the wrong activity. (MainActivity instead of NewWord Activity). I'm building this off of Google's "Room with a view" example project, if that's relevant. Thanks in advance!

public class MainActivity extends AppCompatActivity {

public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;

private WordViewModel mWordViewModel;

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

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    RecyclerView recyclerView = findViewById(R.id.recyclerview);
    recyclerView.setHasFixedSize(true); //Line to improve performance

    final WordListAdapter adapter = new WordListAdapter(this);
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new GridLayoutManager(this,4)); //Changed this

    // Get a new or existing ViewModel from the ViewModelProvider.
    mWordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);

    //Unload Intent to get Category
    String chosenCat = getIntent().getExtras().getString("CAT_KEY");

    //File DIR
    final String DIR = getFilesDir().toString();
   // final String DIR  = Environment.getExternalStoragePublicDirectory(
     //       Environment.DIRECTORY_PICTURES).toString();
    //final String picsDIR = getDir("Pictures", 0).toString();

    //Check what category and load

    // The onChanged() method fires when the observed data changes and the activity is
    // in the foreground.
    if(chosenCat.equals("BASIC")) {
        mWordViewModel.getBasicCatWords().observe(this, new Observer<List<Word>>() {
            @Override
            public void onChanged(@Nullable final List<Word> words) {
                // Update the cached copy of the words in the adapter.
                adapter.setWords(words);
                Toast.makeText(
                        getApplicationContext(),
                        "Category 1",
                        Toast.LENGTH_LONG).show();
            }
        });
    } //If Basic
    else if(chosenCat.equals("ALL")) {
        mWordViewModel.getAllWords().observe(this, new Observer<List<Word>>() {
            @Override
            public void onChanged(@Nullable final List<Word> words) {
                // Update the cached copy of the words in the adapter.
                adapter.setWords(words);
                Toast.makeText(
                        getApplicationContext(),
                        DIR,
                        Toast.LENGTH_LONG).show();
            }
        });
    } //Else if all
    else if(chosenCat.equals("PLAY")) {
        mWordViewModel.getPlayCatWords().observe(this, new Observer<List<Word>>() {
            @Override
            public void onChanged(@Nullable final List<Word> words) {
                // Update the cached copy of the words in the adapter.
                adapter.setWords(words);
                Toast.makeText(
                        getApplicationContext(),
                        "Category 2",
                        Toast.LENGTH_LONG).show();
            }
        });
    } //Else if play

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, NewWordActivity.class);
            startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);
        }
    });
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
        //Word word = new Word(data.getStringExtra(NewWordActivity.WORD_REPLY));
        Word word = new Word(data.getStringExtra(NewWordActivity.WORD_REPLY),data.getStringExtra(NewWordActivity.CAT_REPLY));
        mWordViewModel.insert(word);
    } else {
        Toast.makeText(
                getApplicationContext(),
                R.string.empty_not_saved,
                Toast.LENGTH_LONG).show();
    }
}

}

Main activity(above) uses an intent to go into NewWordActivity. (When the floating action button is pressed) An additional intent is then used to enter the camera when a "Take picture" button is pressed in NewWordActivity(below).

   /**
   * Activity for entering a word.
   */

public class NewWordActivity extends AppCompatActivity implements 
AdapterView.OnItemSelectedListener {

public static final String WORD_REPLY = "com.example.android.wordlistsql.WORD";
public static final String CAT_REPLY = "com.example.android.wordlistsql.CAT";
public static final String PIC_REPLY = "com.example.android.wordlistsql.PIC";

static final int REQUEST_IMAGE_CAPTURE = 2;

//DIR for Pictures
//final String picsDIR = getDir("Pictures", 0).toString();

private EditText mEditWordView;
String wordCategory;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_word);
    mEditWordView = findViewById(R.id.edit_word);

    //Category Spinner
    Spinner categories = findViewById(R.id.category_spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.word_categories, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    categories.setAdapter(adapter);
    categories.setOnItemSelectedListener(this);

    //Choose Image Button
    final Button choosePicButton = findViewById(R.id.button_getPic);
    choosePicButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            TakePictureIntent();
            finish();
        }
    });

    //Save Button
    final Button saveButton = findViewById(R.id.button_save);

    saveButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent replyIntent = new Intent();
            if (TextUtils.isEmpty(mEditWordView.getText())) {
                setResult(RESULT_CANCELED, replyIntent);
            } else {
                String word = mEditWordView.getText().toString();
                replyIntent.putExtra(WORD_REPLY, word);
                replyIntent.putExtra(CAT_REPLY, wordCategory);
                setResult(RESULT_OK, replyIntent);
            }
            finish();
        }
    });

}

//Methods for Category Spinner
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    wordCategory = parent.getItemAtPosition(position).toString();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

//Methods for Picture Selector
private void TakePictureIntent(){
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //MediaStore.ACTION_IMAGE_CAPTURE
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    Toast.makeText(
            getApplicationContext(),
            "I made it to result",
            Toast.LENGTH_LONG).show();
    //Preview Image
    ImageView picPreview = (ImageView)findViewById(R.id.picPreview);

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        picPreview.setImageBitmap(imageBitmap);
    }
}

}


Solution

  • Remove finish(); in choosePicButton on click. It will look like this

    choosePicButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                TakePictureIntent();
            }
    });