Can't trigger the onActivityResult method - java

I have an issue with onActivityResult.
I'm using startActivityForResult to update some elements which data source is from a local database when these activities that I'm starting are over.
It works for two activities but, for some reason, it don't work in the last one. The statements that I put on onActivityResult don't trigger.
This is the code of the first activity, which calls the others:
public class ActivityEquipos extends AppCompatActivity {
public ArrayList<String> equipos = new ArrayList<>();
Spinner spEquipos;
ListView lvJugadores, lvPartidos;
Button btAddJugador, btAddPartido;
final public static int CODE_ADD_JUGADOR = 1, CODE_ADD_PARTIDO = 2, CODE_NEW_EQUIPO = 3;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_equipo, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.itNuevo:
Intent i = new Intent(getApplicationContext(), ActivityNewEquipo.class);
startActivityForResult(i, CODE_NEW_EQUIPO);
break;
case R.id.itVolver:
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_equipos);
spEquipos = findViewById(R.id.spEquipos);
lvJugadores = findViewById(R.id.lvJugadores);
lvPartidos = findViewById(R.id.lvPartidos);
btAddJugador = findViewById(R.id.btAddJugador);
btAddPartido = findViewById(R.id.btAddPartido);
cargaSpinner();
spEquipos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
actualizarJugadoresPartidos(i);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_ADD_JUGADOR && resultCode == RESULT_OK){
actualizarJugadoresPartidos(spEquipos.getSelectedItemPosition());
Toast.makeText(ActivityEquipos.this, "Jugador añadido con éxito.", Toast.LENGTH_SHORT).show();
} else if (requestCode == CODE_ADD_JUGADOR && resultCode == RESULT_CANCELED){
Toast.makeText(ActivityEquipos.this, "Añadido cancelado.", Toast.LENGTH_SHORT).show();
} else if (requestCode == CODE_ADD_PARTIDO && resultCode == RESULT_OK){
actualizarJugadoresPartidos(spEquipos.getSelectedItemPosition());
Toast.makeText(ActivityEquipos.this, "Partido añadido con éxito.", Toast.LENGTH_SHORT).show();
} else if (requestCode == CODE_NEW_EQUIPO && requestCode == RESULT_OK){
Log.d("carga", "precarga");
cargaSpinner();
Log.d("carga", "postcarga");
Toast.makeText(ActivityEquipos.this, "Equipo añadido con éxito.", Toast.LENGTH_SHORT).show();
} else if (requestCode == CODE_NEW_EQUIPO && requestCode == RESULT_CANCELED){
Toast.makeText(ActivityEquipos.this, "Añadido de equipo cancelado.", Toast.LENGTH_SHORT).show();
}
}
private void cargaSpinner(){
BaloncestoSQLiteHelper helper = new BaloncestoSQLiteHelper(this, "baloncesto", null, 7);
SQLiteDatabase db = helper.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM equipos", null);
equipos.clear();
if (c.moveToFirst()){
do {
equipos.add(c.getString(0));
} while (c.moveToNext());
}
spEquipos.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item, equipos));
db.close();
helper.close();
}
private void actualizarJugadoresPartidos(int i){
BaloncestoSQLiteHelper helper = new BaloncestoSQLiteHelper(ActivityEquipos.this, "baloncesto", null, 7);
final SQLiteDatabase db = helper.getWritableDatabase();
ArrayList<String> jugadores = new ArrayList<>();
final Cursor c = db.rawQuery("SELECT * FROM jugadores WHERE Nombre_equipo='" + equipos.get(i) + "'", null);
if (c.moveToFirst()){
do {
jugadores.add(c.getString(1));
} while (c.moveToNext());
}
ListJugadoresAdapter adapter = new ListJugadoresAdapter(ActivityEquipos.this, jugadores);
lvJugadores.setAdapter(adapter);
Log.d("tam", "" + jugadores.size());
//PARTIDOS
BaloncestoSQLiteHelper helperP = new BaloncestoSQLiteHelper(ActivityEquipos.this, "baloncesto", null, 7);
final SQLiteDatabase dbP = helperP.getWritableDatabase();
ArrayList<Partido> partidos = new ArrayList<>();
final Cursor cP = dbP.rawQuery("SELECT * FROM partidos WHERE equipo_local='" + equipos.get(i) + "' OR equipo_visitante='" + equipos.get(i) + "'", null);
if (cP.moveToFirst()){
do {
Partido partido = new Partido(cP.getString(1), cP.getString(2), cP.getInt(3), cP.getInt(4), cP.getString(5));
partidos.add(partido);
} while (cP.moveToNext());
}
ListPartidosAdapter partidosAdapter = new ListPartidosAdapter(ActivityEquipos.this, partidos);
lvPartidos.setAdapter(partidosAdapter);
dbP.close();
}
I removed the other activity calls from the code to make easier to see with which activity I have the problem.
Here is the second activity:
public class ActivityNewEquipo extends AppCompatActivity {
EditText etNombre, etConferencia, etDivision, etCiudad;
Button btAceptar, btCancelar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_equipo);
etNombre = findViewById(R.id.etNombreEquipo);
etConferencia = findViewById(R.id.etConferenciaEquipo);
etDivision = findViewById(R.id.etDivisionEquipo);
etCiudad = findViewById(R.id.etDivisionEquipo);
btAceptar = findViewById(R.id.btAniadirEquipo);
btCancelar = findViewById(R.id.btCancelarEquipo);
btCancelar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setResult(RESULT_CANCELED);
finish();
}
});
btAceptar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (etNombre.getText().toString().trim().isEmpty() ||
etCiudad.getText().toString().trim().isEmpty() ||
etConferencia.getText().toString().trim().isEmpty() ||
etDivision.getText().toString().trim().isEmpty()){
Toast.makeText(getApplicationContext(), "Campos vacíos. Imposible introducir", Toast.LENGTH_SHORT).show();
} else{
BaloncestoSQLiteHelper helper = new BaloncestoSQLiteHelper(getApplicationContext(), "baloncesto", null, 7);
final SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Nombre", etNombre.getText().toString().trim());
values.put("Ciudad", etCiudad.getText().toString().trim());
values.put("Conferencia", etConferencia.getText().toString().trim());
values.put("Division", etDivision.getText().toString().trim());
try{
db.insert("equipos", null, values);
db.close();
setResult(Activity.RESULT_OK);
finish();
}catch (SQLiteConstraintException ex){
Toast.makeText(getApplicationContext(), "Nombre de equipo duplicado", Toast.LENGTH_SHORT).show();
}
}
}
});
}

} else if (requestCode == CODE_NEW_EQUIPO && requestCode == RESULT_OK){
Change to
} else if (requestCode == CODE_NEW_EQUIPO && resultCode == RESULT_OK){
And... you made that error twice!!!
If you only -as a test- had put one Toast in it only...

Related

My app keep showing "permission denied can't use the app"

My app is an sos app that can send an sms with location by shaking the phone to a saved contact.
But when i want to try my app it keep show me "permission denied can't use the app" although i added the permission (contact and location and sms)
Can you please help me to solve this problem
This is my code :
Button button1;
ListView listView;
databaseOpenHelper db;
List<ContactModel> list;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone);
// check for runtime permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.READ_CONTACTS}, 100);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 100);
}
// start the service
SensorService sensorService = new SensorService();
Intent intent = new Intent(this, sensorService.getClass());
if (!isMyServiceRunning(sensorService.getClass())) {
startService(intent);
}
button1 = findViewById(R.id.Button1);
listView = (ListView) findViewById(R.id.ListView);
db = new databaseOpenHelper(this);
list = db.getAllContacts();
customAdapter = new CustomAdapter(this, list);
listView.setAdapter(customAdapter);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calling of getContacts()
if (db.count() != 5) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
} else {
Toast.makeText(phone.this, "Can't Add more than 5 Contacts", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i("Service status", "Running");
return true;
}
}
Log.i("Service status", "Not running");
return false;
}
#Override
protected void onDestroy() {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, ReactivateService.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Permissions Denied!\n Can't use the App!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// get the contact from the PhoneBook of device
switch (requestCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String phone = null;
try {
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
phones.moveToFirst();
phone = phones.getString(phones.getColumnIndex("data1"));
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
db.addcontact(new ContactModel(0, name, phone));
list = db.getAllContacts();
customAdapter.refresh(list);
} catch (Exception ex) {
}
}
}
break;
}
}
}

How do I convert an image to a String to read/write it to a SQLite Database - Android Studio (Java)

I am having trouble converting an image to a String to read/write it to a SQLite Database on Android Studio using Java. I have watch loads of tutorials and cannot seem to find what I am missing. Any help at all would be appreciated!!
My error stems from not converting it from AddData in the Main Activity:
DATABASE HELPER:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "relove.db";
public static final String TABLE_NAME = "PLGarments_Table";
public static final String COL_ID = "ID";
public static final String COL_TITLE = "TITLE";
public static final String COL_DESCRIPTION = "DESCRIPTION";
public static final String COL_OWNER = "OWNER";
public static final String COL_IMAGE = "image";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME , null, 1);
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, TITLE TEXT, DESCRIPTION TEXT, OWNER TEXT, IMAGE BLOB)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" Drop table if exists " + TABLE_NAME );
onCreate(db);
}
public void queryData(String sql){
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
} //unnecessary?
public boolean insertData(String TITLE, String DESCRIPTION, String OWNER, byte[] image){ //CREATE
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_TITLE,TITLE);
contentValues.put(COL_DESCRIPTION,DESCRIPTION);
contentValues.put(COL_OWNER,OWNER);
contentValues.put(COL_IMAGE, image);
long result = db.insert(TABLE_NAME, null,contentValues );
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData(){ //RETRIEVE
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public boolean updateData(String ID,String TITLE, String DESCRIPTION, String OWNER, byte[] image ){ //UPDATE
SQLiteDatabase db = this.getWritableDatabase(); //instance of database
ContentValues contentValues = new ContentValues();
contentValues.put(COL_ID, ID);
contentValues.put(COL_TITLE,TITLE);
contentValues.put(COL_DESCRIPTION,DESCRIPTION);
contentValues.put(COL_OWNER,OWNER);
contentValues.put(COL_IMAGE, image);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] {ID});
return true;
}
public Integer deleteData (String ID){ //DELETE
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?", new String[] {ID});
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editTitle, editDescription, editOwner, editTextID;
Button btnAddData, btnviewAll, btnviewUpdate, btnDelete, btnLogOut;
ImageView mImageView;
final int REQUEST_CODE_GALLERY = 999;
//use lines 37 - 40 when starting a new activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this); /*calling constructor*/
editTitle = (EditText)findViewById(R.id.editText_title);
editDescription = (EditText)findViewById(R.id.editText_description);
editOwner = (EditText)findViewById(R.id.editText_owner);
editTextID = (EditText)findViewById(R.id.editText_id);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
btnviewUpdate = (Button)findViewById(R.id.button_update);
btnDelete = (Button)findViewById(R.id.button_delete);
btnLogOut = (Button)findViewById(R.id.button_logout);
mImageView = (ImageView)findViewById(R.id.imageView);
AddData();
viewAll();
UpdateGarment();
DeleteGarment();
btnLogOut.setOnClickListener( new View.OnClickListener(){
#Override
public void onClick(View view){
launchLoginActivity();
}
}
); // Learn2Crack - Android Switching Between Activities
mImageView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//read external storage permissions to select image from gallery
// Runtime permission for devices Android 6.0 and above
ActivityCompat.requestPermissions(
MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_GALLERY
);
}
});
}
//back to login
public void launchLoginActivity(){
Intent intent = new Intent (this, LoginActivity.class);
startActivity(intent);
} // Learn2Crack - Android Switching Between Activities
//Create
public void AddData(){
btnAddData.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted = myDb.insertData(editTitle.getText().toString(), editDescription.getText().toString(),
editOwner.getText().toString(), *mImageView.*);
if (isInserted == true)
Toast.makeText(MainActivity.this, "Garment Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Garment Not Inserted", Toast.LENGTH_LONG).show(); }
});
} /*end of add button*/
//Retrieve
public void viewAll(){
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) { /*the actual action goes in here */
Cursor res = myDb.getAllData();
if (res.getCount() == 0){
//show message
showMessage("Error", "No Garments Found");
return;
}
StringBuffer buffer = new StringBuffer();
while ( res.moveToNext()){
buffer.append("ID :" + res.getString(0)+ "\n");
buffer.append("TITLE :" + res.getString(1)+ "\n");
buffer.append("DESCRIPTION :" + res.getString(2)+ "\n");
buffer.append("OWNER :" + res.getString(3)+ "\n\n");
}
//show all data
showMessage("Garments", buffer.toString());
}
}
);
}
//Update
public void UpdateGarment(){
btnviewUpdate.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isUpdate = myDb.updateData(editTextID.getText().toString(), editTitle.getText().toString(),
editDescription.getText().toString(), editOwner.getText().toString() );
if (isUpdate == true)
Toast.makeText(MainActivity.this, "Garment Updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Garment Not Updated", Toast.LENGTH_LONG).show();
}
}
);
}
//Delete
public void DeleteGarment(){
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(editTextID.getText().toString());
if (deletedRows > 0)
Toast.makeText(MainActivity.this, "Garment Deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Garment Not Deleted", Toast.LENGTH_LONG).show();
}
}
);
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
//Gallary permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_GALLERY){
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//gallery intent
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, REQUEST_CODE_GALLERY);
}
else {
Toast.makeText(this, "Don't have permission to access file location", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK){
Uri resultUri = result.getUri();
//set image chosen from gallery to image view
mImageView.setImageURI(resultUri);
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Exception error = result.getError();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
You need to convert mImageView. to a byte[] (bitmap).
So
BitmapDrawable d = (BitmapDrawable) mImageView.getDrawable();
Bitmap b = d.getBitmap();
boolean isInserted = myDb.insertData(editTitle.getText().toString(), editDescription.getText().toString(),
editOwner.getText().toString(), b);
If bitmap larger than 2Mb then cannot be got from Cursor. It is not advised to store bitmap in database but to store bitmap as file and to store path in database.

How to pass data from return activity to dialog in previous activity?

Visitor Details
I have a dialog in Visitor Activity. When I click on the icon, it will redirect to Camera Activity. Then when click Confirm button in Camera Activity, it will send the intent back to previous Activity which is Visitor Activity. The problem is how should I pass the intent result from Camera Activity back to the dialog in Visitor Activity. The intent data should be placed in the Pass No Edit Text. I'm using material dialog without any Fragment that attached to that dialog. It all placed in Visitor Activity. Can someone please help me? Thank you!
private void checkin()
{
final MaterialDialog dialog = new MaterialDialog.Builder(VisitorDetailActivity.this)
.customView(R.layout.sample,false)
.build();
View view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
final EditText etVehicleNo = (EditText) view.findViewById(R.id.etVehicleNo);
final ImageView ivScanCode = (ImageView) view.findViewById(R.id.ivScanCode);
final TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
final TextView tvSubmit = (TextView) view.findViewById(R.id.tvSubmit);
etVehicleNo.setText(model.getFldVehicleNo());
if(barCode != null)
{
etPassNo.setText(barCode);
}
ivScanCode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(VisitorDetailActivity.this, "Bar code scanner", Toast.LENGTH_SHORT).show();
Intent i = new Intent(VisitorDetailActivity.this, ScanCodeActivity.class);
startActivityForResult(i,97);
}
});
tvCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
tvSubmit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etPassNo.getText().toString().trim().isEmpty())
{
Toast.makeText(VisitorDetailActivity.this, "Pass No is required", Toast.LENGTH_SHORT).show();
return;
}
if(selImage == null)
{
proceedCheckin(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
else
{
proceedCheckinImage(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 98 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if (requestCode == 99 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if(requestCode == 97 && resultCode == RESULT_OK)
{
barCode = data.getStringExtra("barCode");
}
}
First you need to take the view object globally out of that checkIn methoed
View view;
view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
Now under your onActivityResult method, as i can see you already getting the barcode there, so just initiate the EditText object again on that same simply set the data in it.
barCode = data.getStringExtra("barCode");
EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
etPassNo.setText(barCode);
Let me know if that works.
you can do it using interface
public interface OnBarcodeSelect{
void onBarcodeSelected(String barcode);}
OnBarcodeSelect onBarcodeSelect;
private void checkin()
{
final MaterialDialog dialog = new MaterialDialog.Builder(VisitorDetailActivity.this)
.customView(R.layout.sample,false)
.build();
View view = dialog.getCustomView();
final EditText etPassNo = (EditText) view.findViewById(R.id.etPassNo);
final EditText etVehicleNo = (EditText) view.findViewById(R.id.etVehicleNo);
final ImageView ivScanCode = (ImageView) view.findViewById(R.id.ivScanCode);
final TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
final TextView tvSubmit = (TextView) view.findViewById(R.id.tvSubmit);
etVehicleNo.setText(model.getFldVehicleNo());
if(barCode != null)
{
etPassNo.setText(barCode);
}
ivScanCode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(VisitorDetailActivity.this, "Bar code scanner", Toast.LENGTH_SHORT).show();
Intent i = new Intent(VisitorDetailActivity.this, ScanCodeActivity.class);
onBarcodeSelect = new OnBarcodeSelect() {
#Override
public void onBarcodeSelected(String barcode) {
//handle barcode here
etPassNo.setText(barcode);
}
}
startActivityForResult(i,97);
}
});
tvCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dialog.dismiss();
}
});
tvSubmit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etPassNo.getText().toString().trim().isEmpty())
{
Toast.makeText(VisitorDetailActivity.this, "Pass No is required", Toast.LENGTH_SHORT).show();
return;
}
if(selImage == null)
{
proceedCheckin(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
else
{
proceedCheckinImage(etPassNo.getText().toString(), etVehicleNo.getText().toString());
}
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 98 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if (requestCode == 99 && resultCode == RESULT_OK)
{
selImage = data.getStringExtra("photo");
Glide.with(VisitorDetailActivity.this).load(selImage).into(iDrivingLicense);
}
else if(requestCode == 97 && resultCode == RESULT_OK)
{
barCode = data.getStringExtra("barCode");
if(onBarcodeSelect != null){
onBarcodeSelect.onBarcodeSelected(barCode);
}
}
}

Image do not show after i saved it in a sqlite database

In this app I save products in a sqlite database. Could you help me understand why I can’t see the image when I want to edit a product? I can see it when I add it but not when I click on product to edit it.
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final int EXISTING_PRODUCT_LOADER = 1;
private static final int PICTURE_GALLERY_REQUEST = 1;
private static final String STATE_PICTURE_URI = "STATE_PICTURE_URI";
private Uri mPictureUri;
private Uri mCurrentProductUri;
private EditText mNameEditText;
private EditText mPriceEditText;
private EditText mQuantityEditText;
private EditText mSupplierEditText;
private EditText mMailEditText;
private int mProductQuantity=-1;
private Button mIncreaseQuantityButton;
private Button mDecreaseQuantityButton;
private Button mSelectImageButton;
private ImageView mProductImageView;
private String picturePath;
private String stringUri;
private Button mOrderButton;
final Context mContext = EditorActivity.this;
private boolean mProductHasChanged = false;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mProductHasChanged = true;
return false;
}
};
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 70, image.length);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor_activity);
Intent intent = getIntent();
mCurrentProductUri = intent.getData();
if (mCurrentProductUri == null) {
setTitle(getString(R.string.editor_activity_title_new_product));
invalidateOptionsMenu();
} else {
setTitle(getString(R.string.editor_activity_title_edit_product));
getLoaderManager().initLoader(EXISTING_PRODUCT_LOADER, null, this);
}
initialiseViews();
setOnTouchListener();
}
private void setOnTouchListener() {
mNameEditText.setOnTouchListener(mTouchListener);
mPriceEditText.setOnTouchListener(mTouchListener);
mQuantityEditText.setOnTouchListener(mTouchListener);
mSupplierEditText.setOnTouchListener(mTouchListener);
mMailEditText.setOnTouchListener(mTouchListener);
mIncreaseQuantityButton.setOnTouchListener(mTouchListener);
mDecreaseQuantityButton.setOnTouchListener(mTouchListener);
mSelectImageButton.setOnTouchListener(mTouchListener);
mOrderButton.setOnTouchListener(mTouchListener);
}
private void initialiseViews() {
mOrderButton = (Button) findViewById(R.id.order_button);
mOrderButton.setVisibility(View.VISIBLE);
mOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String productName = mNameEditText.getText().toString().trim();
String emailAddress = "mailto:" + mMailEditText.getText().toString().trim();
String subjectHeader = "Order For: " + productName;
String orderMessage = "Please send a unit of " + productName + ". " + " \n\n" + "Thank you.";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setData(Uri.parse(emailAddress));
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, orderMessage);
intent.putExtra(Intent.EXTRA_SUBJECT, subjectHeader);
startActivity(Intent.createChooser(intent, "Send Mail..."));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
mNameEditText = (EditText) findViewById(R.id.edit_name);
mPriceEditText = (EditText) findViewById(R.id.edit_price);
mQuantityEditText = (EditText) findViewById(R.id.edit_quantity);
mSupplierEditText = (EditText) findViewById(R.id.edit_supplier);
mMailEditText= (EditText) findViewById(R.id.edit_supplier_mail);
mIncreaseQuantityButton = (Button) findViewById(R.id.editor_increase);
mIncreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {
Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);
mProductQuantity++;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}}
});
mDecreaseQuantityButton = (Button) findViewById(R.id.editor_decrease);
mDecreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quanititynumber = mQuantityEditText.getText().toString();
if (TextUtils.isEmpty(quanititynumber)) {
Toast.makeText(EditorActivity.this, "Quantity field is Empty", Toast.LENGTH_SHORT).show();
return;
} else {
mProductQuantity = Integer.parseInt(quanititynumber);
if (mProductQuantity > 0) {
mProductQuantity--;
mQuantityEditText.setText(String.valueOf(mProductQuantity));
}
}}
});
mProductImageView = (ImageView) findViewById(R.id.image);
mSelectImageButton = (Button) findViewById(R.id.upload_image);
mSelectImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent openPictureGallery = new Intent(Intent.ACTION_OPEN_DOCUMENT);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
openPictureGallery.setDataAndType(data, "image/*");
startActivityForResult(openPictureGallery, PICTURE_GALLERY_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
// checking if the request code and result code match our request
if (requestCode == PICTURE_GALLERY_REQUEST && resultCode == Activity.RESULT_OK) {
if (resultData != null) {
try {
//this is the address of the image on the sd cards
mPictureUri = resultData.getData();
int takeFlags = resultData.getFlags();
takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
picturePath = mPictureUri.toString();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContentResolver().takePersistableUriPermission(mPictureUri, takeFlags);
}
} catch (SecurityException e) {
e.printStackTrace();
}
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
} catch (Exception e) {
e.printStackTrace();
//Show the user a Toast mewssage that the Image is not available
Toast.makeText(EditorActivity.this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
public Bitmap getBitmapFromUri(Uri uri, Context mContext, ImageView imageView) {
if (uri == null || uri.toString().isEmpty())
return null;
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
InputStream input = null;
try {
input = this.getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
if (input != null)
input.close();
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
Bitmap.createScaledBitmap(bitmap, 88, 88, false);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
Log.e("EditorActivity", "Failed to load image.", fne);
return null;
} catch (Exception e) {
Log.e("EditorActivity", "Failed to load image.", e);
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {
}
}
}
private void saveProduct() {
String nameString = mNameEditText.getText().toString().trim();
String quantityString = mQuantityEditText.getText().toString().trim();
String priceString = mPriceEditText.getText().toString().trim();
String supplierString = mSupplierEditText.getText().toString().trim();
String supplierEmailString = mMailEditText.getText().toString().trim();
if (mCurrentProductUri == null &&
TextUtils.isEmpty(nameString) && TextUtils.isEmpty(quantityString) &&
TextUtils.isEmpty(priceString) && TextUtils.isEmpty(supplierString)&& TextUtils.isEmpty(supplierEmailString)) {
return;
}
int quantity = parseInt(quantityString);
double price = Double.parseDouble(mPriceEditText.getText().toString().trim());
ContentValues values = new ContentValues();
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME, nameString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE, priceString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY, quantityString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER, supplierString);
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL, supplierEmailString);
if(mPictureUri!=null) {
picturePath = mPictureUri.toString().trim();
}
else{
picturePath=stringUri;
}
values.put(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE, picturePath);
if (mCurrentProductUri == null) {
Uri newUri = getContentResolver().insert(ProductContract.ProductEntry.CONTENT_URI, values);
if (newUri == null) {
Toast.makeText(this, getString(R.string.editor_insert_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_insert_product_successful),
Toast.LENGTH_SHORT).show();
}
} else {
int rowsAffected = getContentResolver().update(mCurrentProductUri, values, null, null);
if (rowsAffected == 0) {
Toast.makeText(this, getString(R.string.editor_update_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_update_product_successful),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_editor, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mCurrentProductUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveProduct();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!mProductHasChanged) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
}
};
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (!mProductHasChanged) {
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
};
showUnsavedChangesDialog(discardButtonClickListener);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
ProductContract.ProductEntry._ID,
ProductContract.ProductEntry.COLUMN_PRODUCT_NAME,
ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE,
ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER,
ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL,
ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE};
return new CursorLoader(this, // Parent activity context
mCurrentProductUri, // Query the content URI for the current product
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
});
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);
String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);
Uri uriData = Uri.parse(stringUri);
mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
if (mPictureUri!=null){
if (stringUri!=null)
mProductImageView.setImageURI(uriData);
else {
Bitmap bM = getBitmapFromUri(mPictureUri, mContext, mProductImageView);
mProductImageView.setImageBitmap(bM);
}}
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mNameEditText.setText("");
mPriceEditText.setText("");
mQuantityEditText.setText("");
mSupplierEditText.setText("");
mMailEditText.setText("");
mProductImageView.setImageResource(R.drawable.ic_add_a_photo_black_24dp);
}
private void showUnsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.unsaved_changes_dialog_msg);
builder.setPositiveButton(R.string.discard, discardButtonClickListener);
builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.delete_dialog_msg);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteProduct();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteProduct() {
if (mCurrentProductUri != null) {
int rowsDeleted = getContentResolver().delete(mCurrentProductUri, null, null);
if (rowsDeleted == 0) {
Toast.makeText(this, getString(R.string.editor_delete_product_failed),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.editor_delete_product_successful),
Toast.LENGTH_SHORT).show();
}
}
finish();
}
}
The link to the full code is : https://drive.google.com/open?id=1aQFcWHinIqqXHbTyssfPYTD20o9E2piA
and if you can’t find the java files here they are: https://drive.google.com/drive/folders/1VKp0CoJlJssSdKzK4ctk26KFY0_xIDzU?usp=sharing
In your onLoadFinished you assume mPictureURI is set and is not empty.
Now you have set a listener on mProductImageView for changes. No matter what you write/set down below the mProductImageView finally the in the listener it was set back to mPictureURI which was empty hence showing an empty image space.
Please have a look at the code below(also verified that it works).
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (cursor == null || cursor.getCount() < 1) {
return;
}
if (cursor.moveToFirst()) {
int nameColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_QUANTITY);
int supplierColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER);
int mailColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_SUPPLIER_MAIL);
int pictureColumnIndex = cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRODUCT_PICTURE);
String name = cursor.getString(nameColumnIndex);
String price = cursor.getString(priceColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
String mail = cursor.getString(mailColumnIndex);
stringUri = cursor.getString(pictureColumnIndex);
mPictureUri = Uri.parse(stringUri);
mNameEditText.setText(name);
mPriceEditText.setText(price);
mQuantityEditText.setText(String.valueOf(quantity));
mSupplierEditText.setText(supplier);
mMailEditText.setText(mail);
}
ViewTreeObserver viewTreeObserver = mProductImageView.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mProductImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
if(mPictureUri !=null) {
mProductImageView.setImageBitmap(getBitmapFromUri(mPictureUri, mContext, mProductImageView));
}
}
}
});
}

Replace the original image on a new image in android application

In this MainActivity java class on Android Application Project I can't replace the original image given by the system with the one different selected from the photo gallery of smartphone.
When I select the one different photo I have always the original image.
public class MainActivity extends Activity implements OnClickListener {
Button uploadButton, btnselectpic;
ImageView imageview;
private ProgressDialog dialog = null;
private String imagepath = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button) findViewById(R.id.uploadButton);
btnselectpic = (Button) findViewById(R.id.btnselectpic);
imageview = (ImageView) findViewById(R.id.imageview);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
#Override
public void onClick(View arg0) {
if (arg0 == btnselectpic) {
selectImage();
} else if (arg0 == uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && requestCode == 2 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
}
}
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();
return cursor.getString(column_index);
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
The problem is that your onActivityResult() will never do anything.
You start this method off with:
if (requestCode == 1 && requestCode == 2 && resultCode == RESULT_OK) {
// ...
}
requestCode cannot be both 1 and 2, so this conditional will always be false.
You are likely looking for something more like this:
if ((requestCode == 1 && resultCode == RESULT_OK) ||
(requestCode == 2 && resultCode == RESULT_OK)) {
// ...
}

Categories

Resources