I'm working on an app that uploads an image to the firebase database from the gallery and camera.
From the gallery it works, but from the camera need create that image when I take it. All tutorial I found have mistakes and I don't know how do it.
private Button btnCamera, btnGallery, btnList;
private StorageReference storage; //referencia para usar Storage
private static final int GALLERY_INTENT = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private static final String AUTHORITY=BuildConfig.APPLICATION_ID+".provider";
private ProgressDialog progressDialog;
private File file = null;
ImageView imgView = null;
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fecha = df.format(c.getTime());
private EditText TextNombre;
private EditText TextApellidos;
private TextView TextSalida;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_method);
storage = FirebaseStorage.getInstance().getReference();
TextNombre = (EditText) findViewById(R.id.textN);
TextApellidos = (EditText) findViewById(R.id.textA);
TextSalida = (TextView) findViewById(R.id.salida);
progressDialog = new ProgressDialog(this);
btnCamera = (Button) findViewById(R.id.buttonCamera);
btnGallery = (Button) findViewById(R.id.buttonGallery);
btnList = (Button) findViewById(R.id.buttonList);
String dato = getIntent().getStringExtra("dato");
TextSalida.setText(dato);
This is the method to take a picture with the camera:
//-------------METODO TOMAR FOTO CON LA CAMARA-------------
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*Intent btnImage = new Intent(SelectMethod.this, TakePhoto.class);
startActivity(btnImage);*/
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
And this with gallery:
//-------------METODO SELECCIONAR IMAGEN DESDE GALERIA-------------
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent (Intent.ACTION_PICK); //selecciona una imagen de la galería
intent.setType("image/*"); //permitimos todas las extensiones de imagenes
startActivityForResult(intent,GALLERY_INTENT);
}
});
}
OnActivityResult for two methods:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GALLERY_INTENT:
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) { //verificamos que la imagen se obtuvo de manera correcta
Uri uri = data.getData();
StorageReference filePath = storage.child(getIntent().getStringExtra("dato")).child(fecha + " " + uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(SelectMethod.this, "La imagen se subió correctamente.", Toast.LENGTH_SHORT).show();
}
});
}
break;
case CAMERA_REQUEST_CODE:
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
imgView.setImageBitmap(bitmap);
}
break;
}
}
}
Related
I'm new to Android Studio and i'm trying to do a simple register and login app, but I have one problem with the Picasso on my "Profile Picture" ImageView where the image is uploaded and stored to firebase, but the stored image won't show on ImageView.
Here's the Upload Photo code
public class UploadFoto extends AppCompatActivity {
private ProgressBar progressBar;
private ImageView imageViewUploadPic;
private Button upload_pic_btn, upload_pic_choose_btn;
private FirebaseAuth authProfile;
private StorageReference storageReference;
private FirebaseUser firebaseUser;
private static final int PICK_IMAGE_REQUEST = 1;
private Uri uriImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_upload_foto);
getSupportActionBar().setTitle("Alterar Foto de Perfil");
Button buttonUploadPicChoose = findViewById(R.id.upload_pic_choose_btn);
Button buttonUploadPic = findViewById(R.id.upload_pic_btn);
ProgressBar progressBar = findViewById(R.id.progressBar);
imageViewUploadPic = findViewById(R.id.imageView_profile_dp);
authProfile = FirebaseAuth.getInstance();
firebaseUser = authProfile.getCurrentUser();
storageReference = FirebaseStorage.getInstance().getReference("DisplayPics");
Uri uri = firebaseUser.getPhotoUrl();
//Setar foto atual do usuário (caso já tenha sido upada pro firebase) no image view
//Regular Uris.
Picasso.with(UploadFoto.this).load(uri).into(imageViewUploadPic);
//Escolhe imagem pra dar upload
buttonUploadPicChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
//realizar upload da imagem pro storage do Firebase
buttonUploadPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
UploadPic();
}
});
}
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
uriImage = data.getData();
imageViewUploadPic.setImageURI(uriImage);
}
}
private void UploadPic(){
if (uriImage != null){
//Salvar imagem com o UID do usuário atual
StorageReference fileReference = storageReference.child(authProfile.getCurrentUser().getUid() + "."
+ getFileExtension(uriImage));
//Realizar Upload da imagem pro storage
fileReference.putFile(uriImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
firebaseUser = authProfile.getCurrentUser();
//Setar imagem do usuário após upload
UserProfileChangeRequest profireUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(downloadUri).build();
firebaseUser.updateProfile(profireUpdates);
}
});
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadFoto.this, "Imagem alterada com sucesso!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(UploadFoto.this, Perfil.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadFoto.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadFoto.this, "Nenhuma imagem foi selecionada!", Toast.LENGTH_SHORT).show();
}
}
//Obter extensão da imagem
private String getFileExtension(Uri uri){
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
//Criar actionbar menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflar menu
getMenuInflater().inflate(R.menu.common_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//Quando for selecionado qualquer opção do menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_atualizar){
//atualizar atividade/página
startActivity(getIntent());
finish();
overridePendingTransition(0, 0);
} /*else if (id == R.id.menu_alterarinfo){
Intent intent = new Intent(Perfil.this, AtualizarPerfil.class);
startActivity(intent);
} */else if (id == R.id.menu_sair){
authProfile.signOut();
Toast.makeText(UploadFoto.this, "Logout realizado com sucesso!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(UploadFoto.this, Login.class);
//Limpar
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(UploadFoto.this, "Ocorreu um erro, tente novamente.", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
And here is the Profile code
public class Perfil extends AppCompatActivity {
private TextView textViewApelido, textViewNome, textViewCNH, textViewCategoria, textViewNatural,
textViewEndereco, textViewBairro, textViewCEP, textViewEmail, textViewTelefone, textViewCelular, textViewProfissional,
textViewTipo_Sanguíneo, textViewEstado_Civil, textViewNome_Garupa, textViewNatural_Garupa, textViewEndereco_Garupa,
textViewBairro_Garupa, textViewCEP_Garupa, textViewEmail_Garupa, textViewTelefone_Garupa, textViewCelular_Garupa,
textViewTipo_Sanguíneo_Garupa, textViewMoto, textViewAno_Modelo, textViewCC, textViewPlaca, textViewNome_Contato_1,
textViewParentesco_Contato_1, textViewCelular_Contato_1, textViewNome_Contato_2, textViewParentesco_Contato_2,
textViewCelular_Contato_2, textViewNascimento, textViewNascimento_Garupa;
private String Apelido, Nome, CNH, Categoria, Natural, Endereco, Bairro, CEP, Email, Telefone, Celular,
Profissional, Tipo_Sanguíneo, Estado_Civil, Nome_Garupa, Natural_Garupa, Endereco_Garupa, Bairro_Garupa, CEP_Garupa, Email_Garupa,
Telefone_Garupa, Celular_Garupa, Tipo_Sanguíneo_Garupa, Moto, Ano_Modelo, CC, Placa, Nome_Contato_1, Parentesco_Contato_1, Celular_Contato_1,
Nome_Contato_2, Parentesco_Contato_2, Celular_Contato_2, Nascimento, Nascimento_Garupa;
private ImageView imageView;
private FirebaseAuth authProfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_perfil);
getSupportActionBar().setTitle("Perfil do Usuário");
textViewApelido = (TextView) findViewById(R.id.textView_show_apelido);
textViewNome = (TextView) findViewById(R.id.textView_show_nome);
textViewCNH = (TextView) findViewById(R.id.textView_show_CNH);
textViewCategoria = (TextView) findViewById(R.id.textView_show_categoria);
textViewNatural = (TextView) findViewById(R.id.textView_show_natural);
textViewEndereco = (TextView) findViewById(R.id.textView_show_endereco);
textViewBairro = (TextView) findViewById(R.id.textView_show_bairro);
textViewCEP = (TextView) findViewById(R.id.textView_show_CEP);
textViewEmail = (TextView) findViewById(R.id.textView_show_email);
textViewTelefone = (TextView) findViewById(R.id.textView_show_telefone);
textViewCelular = (TextView) findViewById(R.id.textView_show_celular);
textViewProfissional = (TextView) findViewById(R.id.textView_show_profissional);
textViewTipo_Sanguíneo = (TextView) findViewById(R.id.textView_show_sangue);
textViewEstado_Civil = (TextView) findViewById(R.id.textView_show_civil);
textViewNome_Garupa = (TextView) findViewById(R.id.textView_show_nomeg);
textViewNatural_Garupa = (TextView) findViewById(R.id.textView_show_naturalg);
textViewEndereco_Garupa = (TextView) findViewById(R.id.textView_show_enderecog);
textViewBairro_Garupa = (TextView) findViewById(R.id.textView_show_bairrog);
textViewCEP_Garupa = (TextView) findViewById(R.id.textView_show_CEPg);
textViewEmail_Garupa = (TextView) findViewById(R.id.textView_show_emailg);
textViewTelefone_Garupa = (TextView) findViewById(R.id.textView_show_telefoneg);
textViewCelular_Garupa = (TextView) findViewById(R.id.textView_show_celularg);
textViewTipo_Sanguíneo_Garupa = (TextView) findViewById(R.id.textView_show_sangueg);
textViewMoto = (TextView) findViewById(R.id.textView_show_moto);
textViewAno_Modelo = (TextView) findViewById(R.id.textView_show_anomodelo);
textViewCC = (TextView) findViewById(R.id.textView_show_CC);
textViewPlaca = (TextView) findViewById(R.id.textView_show_placa);
textViewNome_Contato_1 = (TextView) findViewById(R.id.textView_show_nomecont1);
textViewParentesco_Contato_1 = (TextView) findViewById(R.id.textView_show_parentcont1);
textViewCelular_Contato_1 = (TextView) findViewById(R.id.textView_show_celcont1);
textViewNome_Contato_2 = (TextView) findViewById(R.id.textView_show_nomecont2);
textViewParentesco_Contato_2 = (TextView) findViewById(R.id.textView_show_parentcont2);
textViewCelular_Contato_2 = (TextView) findViewById(R.id.textView_show_celcont2);
textViewNascimento = (TextView) findViewById(R.id.textView_show_nascimento);
textViewNascimento_Garupa = (TextView) findViewById(R.id.textView_show_nascimentog);
//ClickListener ao clicar no ImageView para editar foto de perfil
imageView = (ImageView) findViewById(R.id.foto);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Perfil.this, UploadFoto.class);
startActivity(intent);
}
});
authProfile = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = authProfile.getCurrentUser();
if (firebaseUser == null){
Toast.makeText(Perfil.this, "Erro, dados do usuário indisponíveis.", Toast.LENGTH_LONG).show();
} else{
CheckEmailVerified(firebaseUser);
showUserProfile(firebaseUser);
}
}
private void CheckEmailVerified(FirebaseUser firebaseUser) {
if (!firebaseUser.isEmailVerified()){
showAlertDialog();
}
}
private void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(Perfil.this);
builder.setTitle("Email não verificado");
builder.setMessage("Favor verificar seu e-mail.");
//open email app
builder.setPositiveButton("continuar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_APP_EMAIL);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showUserProfile(FirebaseUser firebaseUser) {
String userID = firebaseUser.getUid();
//Extrair referência do usuário do BD para "User"
DatabaseReference referenceProfile = FirebaseDatabase.getInstance().getReference("Users");
referenceProfile.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User readUser = snapshot.getValue(User.class);
if (readUser != null){
Apelido = readUser.Apelido;
Nome = readUser.Nome;
CNH = readUser.CNH;
Email = readUser.Email;
Categoria = readUser.Categoria;
Natural = readUser.Natural;
Endereco = readUser.Endereco;
Bairro = readUser.Bairro;
CEP = readUser.CEP;
Email = readUser.Email;
Telefone = readUser.Telefone;
Celular = readUser.Celular;
Profissional = readUser.Profissional;
Tipo_Sanguíneo = readUser.Tipo_Sanguíneo;
Estado_Civil = readUser.Estado_Civil;
Nome_Garupa = readUser.Nome_Garupa;
Natural_Garupa = readUser.Natural_Garupa;
Endereco_Garupa = readUser.Endereco_Garupa;
Bairro_Garupa = readUser.Bairro_Garupa;
CEP_Garupa = readUser.CEP_Garupa;
Email_Garupa = readUser.Email_Garupa;
Telefone_Garupa = readUser.Telefone_Garupa;
Celular_Garupa = readUser.Celular_Garupa;
Tipo_Sanguíneo_Garupa = readUser.Tipo_Sanguíneo_Garupa;
Ano_Modelo = readUser.Ano_Modelo;
CC = readUser.CC;
Placa = readUser.Placa;
Nome_Contato_1 = readUser.Nome_Contato_1;
Parentesco_Contato_1 = readUser.Parentesco_Contato_1;
Celular_Contato_1 = readUser.Celular_Contato_1;
Nome_Contato_2 = readUser.Nome_Contato_2;
Parentesco_Contato_2 = readUser.Parentesco_Contato_2;
Celular_Contato_2 = readUser.Celular_Contato_2;
Nascimento = readUser.Nascimento;
Nascimento_Garupa = readUser.Nascimento_Garupa;
textViewApelido.setText(Apelido);
textViewNome.setText(Nome);
textViewCNH.setText(CNH);
textViewCategoria.setText(Categoria);
textViewNatural.setText(Natural);
textViewEndereco.setText(Endereco);
textViewBairro.setText(Bairro);
textViewCEP.setText(CEP);
textViewEmail.setText(Email);
textViewTelefone.setText(Telefone);
textViewCelular.setText(Celular);
textViewProfissional.setText(Profissional);
textViewTipo_Sanguíneo.setText(Tipo_Sanguíneo);
textViewEstado_Civil.setText(Estado_Civil);
textViewNome_Garupa.setText(Nome_Garupa);
textViewNatural_Garupa.setText(Natural_Garupa);
textViewEndereco_Garupa.setText(Endereco_Garupa);
textViewBairro_Garupa.setText(Bairro_Garupa);
textViewCEP_Garupa.setText(CEP_Garupa);
textViewEmail_Garupa.setText(Email_Garupa);
textViewTelefone_Garupa.setText(Telefone_Garupa);
textViewCelular_Garupa.setText(Celular_Garupa);
textViewTipo_Sanguíneo_Garupa.setText(Tipo_Sanguíneo_Garupa);
textViewMoto.setText(Moto);
textViewAno_Modelo.setText(Ano_Modelo);
textViewCC.setText(CC);
textViewPlaca.setText(Placa);
textViewNome_Contato_1.setText(Nome_Contato_1);
textViewParentesco_Contato_1.setText(Parentesco_Contato_1);
textViewCelular_Contato_1.setText(Celular_Contato_1);
textViewNome_Contato_2.setText(Nome_Contato_2);
textViewParentesco_Contato_2.setText(Parentesco_Contato_2);
textViewCelular_Contato_2.setText(Celular_Contato_2);
textViewNascimento.setText(Nascimento);
textViewNascimento_Garupa.setText(Nascimento_Garupa);
//Setar foto do usuário após upload no perfil
Uri uri = firebaseUser.getPhotoUrl();
//ImageViewer setando Img no URI
Picasso.with(Perfil.this).load(uri).into(imageView);
}else {
Toast.makeText(Perfil.this, "Erro.", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Perfil.this, "Erro!", Toast.LENGTH_LONG).show();
}
});
}
//Criar actionbar menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflar menu
getMenuInflater().inflate(R.menu.common_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//Quando for selecionado qualquer opção do menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_atualizar){
//atualizar atividade/página
startActivity(getIntent());
finish();
overridePendingTransition(0, 0);
} /*else if (id == R.id.menu_alterarinfo){
Intent intent = new Intent(Perfil.this, AtualizarPerfil.class);
startActivity(intent);
} */else if (id == R.id.menu_sair){
authProfile.signOut();
Toast.makeText(Perfil.this, "Logout realizado com sucesso!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Perfil.this, Login.class);
//Limpar
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(Perfil.this, "Ocorreu um erro, tente novamente.", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
Using Picasso implementation 2.5.2.
Already have permission to internet.
Wanting Picasso to "fetch" the image from storage on firebase to display on the user profile.
Images and Text Uploader
Hallo Coders, i am new in Android. i have the above app to upload images to a server and write the image path to a database alongside the user inputted data as seen in the app UI. So far its uploading only one image with the below code and writing the path as appropriate. I am unable to pass the textview data alongside the image path to a mysql DB. I need the following.
1 Upload multiple images to server and write the images path and the other values to a mysql database.
2. Display the images from the server using the state/county select on a listview (Vertically or Horizontally)
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String UPLOAD_URL = "http://10.0.2.2/PhotoUpload/upload.php";
public static final String UPLOAD_KEY = "image";
private int PICK_IMAGE_REQUEST = 1;
private Button buttonChoose;
private Button buttonUpload;
private Button buttonView;
private ImageView imageView;
private Bitmap bitmap;
private Uri filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonView = (Button) findViewById(R.id.buttonViewImage);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
buttonView.setOnClickListener(this);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(){
class UploadImage extends AsyncTask<Bitmap,Void,String>{
ProgressDialog loading;
RequestHandler rh = new RequestHandler();
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Uploading...", null,true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String,String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
String result = rh.sendPostRequest(UPLOAD_URL,data);
return result;
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
}
#Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if(v == buttonUpload){
uploadImage();
}
if(v == buttonView){
viewImage();
}
}
Finally it worked as required by initialising all aspects in the code.
I have a question, by pressing long on imageView imageViewClick.setOnLongClickListener recognizes the voice and answers the question. How do I make the normal press imageViewClick.setOnClickListener recognize the text of the editText and answer the question?
i want know how Read text from editText and show the answer
Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
imageViewClick = (ImageView) findViewById(R.id.imageViewClick);
imageViewClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
imageViewClick.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent voice = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "es-ES");
voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "es-MX");
voice.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "pr-PR");
startActivityForResult(voice, VOICE_RECOGNIZER);
return false;
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == VOICE_RECOGNIZER){
ArrayList<String> recognized = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String listened = recognized.get(0);
editTextListening.setText(listened);
prepareAnswer(listened);
}
}
private void prepareAnswer(String listened) {
String normalize = Normalizer.normalize(listened, Normalizer.Form.NFD);
String withouttilde = normalize.replaceAll("[^\\p{ASCII}]", "");
int result;
String answer = arrayListAnswer.get(0).getAnswer();
for (int i = 0; i < arrayListAnswer.size(); i++) {
result = withouttilde.toLowerCase().indexOf(arrayListAnswer.get(i).getQuestion());
if(result != -1){
answer = arrayListAnswer.get(i).getAnswer();
}
}
answerTo(answer);
}
private void answerTo(String simpleAnswer) {
textViewAnswer.setText(simpleAnswer);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeechRead.speak(simpleAnswer, TextToSpeech.QUEUE_FLUSH, null, null);
}else {
textToSpeechRead.speak(simpleAnswer, TextToSpeech.QUEUE_FLUSH, null);
}
}
public void initialize(){
editTextListening = (EditText) findViewById(R.id.editTextQuestion);
textViewAnswer = (TextView) findViewById(R.id.textViewAnswer);
arrayListAnswer = provideData();
textToSpeechRead = new TextToSpeech(this, this);
}
#Override
public void onInit(int status) {
}
public ArrayList<AnswersActivity> provideData(){
ArrayList<AnswersActivity> answers = new ArrayList<>();
answers.add(new AnswersActivity("defecto", "No estoy programado para hablar de eso"));
answers.add(new AnswersActivity("puff", "Puff"));
answers.add(new AnswersActivity("chiste", "¿Sabes que mi hermano anda en bicicleta desde los 4 años? Mmm, ya debe estar lejos"));
answers.add(new AnswersActivity("adios", "que descanses"));
answers.add(new AnswersActivity("estas", "esperando serte de ayuda"));
answers.add(new AnswersActivity("dj", "YEY BALBIN"));
return answers;
}
}
To recognize the input in EditText and convert the input to speech, you can use the TextToSpeech class provided by Android. Example of this:
textToSpeech = new TextToSpeech(MainActivity.this, MainActivity.this);
editText = (EditText) findViewById(R.id.editText);
imageViewClick = (ImageView) findViewById(R.id.imageViewClick);
imageViewClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextToSpeechFunction() ;
}});
}
public void TextToSpeechFunction()
{
String text = editText.getText().toString();
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(MainActivity.this , text, Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
textToSpeech.shutdown();
super.onDestroy();
}
#Override
public void onInit(int TexttoSpeechCurrentStatus) {
if (TexttoSpeechCurrentStatus == TextToSpeech.SUCCESS) {
textToSpeech.setLanguage(Locale.US);
imageViewClick.setEnabled(true);
TextToSpeechFunction();
}
}
From the App I should be able to add an image from my gallery to the image button, then add Food name, Description and Price and finally click upload.
The image should be uploaded to my firebase storage while Price,Description and Food name should be uploaded to the firebase database
StorageReference filePath = storageReference.child(uri.getLastPathSegment()); causes an error so the image is not displayed on the image button nor uploaded to firebase storage.
public class AddFood extends AppCompatActivity {
private ImageButton foodImage;
private static final int GALLREQ=1;
private EditText name,desc,price;
private Uri uri = null;
private StorageReference storageReference = null;
private DatabaseReference mRef;
private FirebaseDatabase firebaseDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_food);
name = (EditText) findViewById(R.id.ItemName);
desc = (EditText) findViewById(R.id.ItemDesc);
price = (EditText) findViewById(R.id.ItemPrice);
storageReference= FirebaseStorage.getInstance().getReference();
mRef= FirebaseDatabase.getInstance().getReference("Item");
}
public void ImageButtonclicked(View view){
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GALLREQ);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==GALLREQ&& resultCode==RESULT_OK) {
uri = data.getData();
foodImage = (ImageButton) findViewById(R.id.FoodImageButton);
foodImage.setImageURI(uri);
}
}
public void uploadClicked(View view){
final String name_text = name.getText().toString().trim();
final String desc_text = desc.getText().toString().trim();
String price_text = price.getText().toString().trim();
if (!TextUtils.isEmpty(name_text)&&!TextUtils.isEmpty(desc_text)&&!TextUtils.isEmpty(price_text)){
StorageReference filePath = storageReference.child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri downloaduri = taskSnapshot.getDownloadUrl();
Toast.makeText(AddFood.this,"uploaded",Toast.LENGTH_LONG).show();
}
});
final DatabaseReference newPost = mRef.push();
newPost.child("name").setValue(name_text);
newPost.child("desc").setValue(desc);
newPost.child("price").setValue(price_text);
}
}
}
Sorry guys, I'm very new to android and now need to create a simple camera in my android studio.
When I choose an image from gallery or take a picture, it will crashed.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.camera_main, container, false);
b=(Button)claims.findViewById(R.id.btnSelectPhoto);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
return claims;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Claims.this.getActivity());
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();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity. RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
LogCat Error
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=2, result=-1, data=Intent { dat=content://com.sec.android.gallery3d.provider/picasa/item/5843197728949359042 (has extras) }} to activity {com.example.project.project/com.example.project.project.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3752)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3795)
Can someone explain to me why would this happen and how to fix it?
Thanks a lot :)
you can using this method
public class MainActivity extends AppCompatActivity {
private static final int IMAGE_REQUEST_CODE = 1;
private static final int CAMERA_REQUEST_CODE = 2;
private static final String IMG_FILE_NAME = "tempImg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// From Gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), IMAGE_REQUEST_CODE);
// Take a Picture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Uri.fromFile(GetOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public static File GetOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory() + "/" + HConstants.IMG_FILE_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ IMG_FILE_NAME + ".jpg");
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == IMAGE_REQUEST_CODE){
fileUri = data.getData();
Log.i(getClass().getName(), "fileUri" + fileUri);
}else{
Log.i(getClass().getName(), fileUri);
}
}
}
}
Getting Image from Gallery.
Try the following code.Hopefully it will work
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
Taking Picture
public class CameraDemoActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
Also add the permissions in Manifest File:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>