Android application starts from wrong activity & unable to upload image to firebase - android

First of all, sorry for any misunderstanding, typos since english is not my native language. I'm trying to write my first app in Android Studio.
What my app does: ( at least '' should do '' ) :
1 : User Login Screen as MainActivity
2 : if user credientals is true, user is directed to 2nd screen which is Request form.
3 : User puts his name-surname,subject,and explanation of subject.
4 : User CAN also upload pictures from imagebutton. it's not necessary.
5,6,7.... : this parts will be added to program. for now it's only 4 steps :D
Now my problems,
1 : When i run the app it starts from request form(2nd activity) even i clean project before running.
2 : When user type some input for name-surname,object and explanation and click send button, infos are stored in firebase database. But when i select an image for imagebutton it doesnt get stored in firebase. All authentication are set.
LOGIN SCREEN CODE
package com.example.jalea.requestingform;
import android.content.Intent;
import android.preference.EditTextPreference;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
EditText edt_email,edt_sifre;
Button bt_giris;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener authStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_email = (EditText) findViewById(R.id.et_mail);
edt_sifre = (EditText) findViewById(R.id.et_sifre);
bt_giris = (Button) findViewById(R.id.btn_giris);
mAuth = FirebaseAuth.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() !=null){
Intent intent = new Intent(MainActivity.this,RequestActivity.class);
startActivity(intent);
//finish();
Log.w("1 : ","2.activity'e geçildi");
}
else{
Log.w("1 : ", "onAuthStateChanged:çıkış yaptı");
}
}
};
bt_giris.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SignIn();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(authStateListener);
}
#Override
protected void onStop() {
super.onStop();
if(authStateListener != null) {
mAuth.removeAuthStateListener(authStateListener);
}
}
public void SignIn(){
String email = edt_email.getText().toString();
String sifre = edt_sifre.getText().toString();
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(sifre)){
Toast.makeText(MainActivity.this,"Kullanıcı adı veya şifre alanı boş",Toast.LENGTH_LONG).show();
}
else{
mAuth.signInWithEmailAndPassword(email,sifre).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this,"Kullanıcı adı veya şifre hatası ",Toast.LENGTH_LONG).show();
}
/**if(task.isSuccessful()){
Intent intent = new Intent(MainActivity.this,RequestActivity.class);
startActivity(intent);**/
}
});
}
}
}
REQUEST FORM CODE
package com.example.jalea.requestingform;
import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.net.URI;
public class RequestActivity extends AppCompatActivity {
FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference databaseReference;
FirebaseAuth.AuthStateListener authStateListener;
Button btn_cikis,btn_gonder;
ImageButton imgbutton;
EditText et_isim,et_konu,et_aciklama;
StorageReference storageReference;
Uri uri=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
btn_cikis = (Button) findViewById(R.id.btn_cikis);
storageReference = FirebaseStorage.getInstance().getReference();
et_isim= (EditText) findViewById(R.id.et_isim);
et_konu= (EditText) findViewById(R.id.et_konu);
et_aciklama = (EditText) findViewById(R.id.et_text);
database = FirebaseDatabase.getInstance();
btn_gonder = (Button) findViewById(R.id.btn_Send);
btn_cikis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth = FirebaseAuth.getInstance();
mAuth.signOut();
startActivity(new Intent(RequestActivity.this,MainActivity.class));
}
});
btn_gonder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String isim = et_isim.getText().toString();
String konu = et_konu.getText().toString();
String aciklama = et_aciklama.getText().toString();
Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
databaseReference = database.getReference("Kullanicilar").child(isim);
if (!TextUtils.isEmpty(isim) && !TextUtils.isEmpty(konu) && !TextUtils.isEmpty(aciklama)) {
databaseReference.child("adSoyad").setValue(isim);
databaseReference.child("Konu").setValue(konu);
databaseReference.child("Aciklama").setValue(aciklama);
Toast.makeText(RequestActivity.this, "Talep gönderildi", Toast.LENGTH_LONG).show();
StorageReference filePath = storageReference.child("Resim").child(uri.getLastPathSegment());
filePath.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(RequestActivity.this, "Resim eklendi", Toast.LENGTH_LONG).show();
}
});
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("İmage hata : ", e);
}
});
}
}
});
}
public void imageButtonClicked(View View){
Intent gallery_intent = new Intent(Intent.ACTION_GET_CONTENT);
gallery_intent.setType("image/*");
startActivityForResult(gallery_intent,2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 2 && resultCode == RESULT_OK){
uri = data.getData();
imgbutton = (ImageButton) findViewById(R.id.imageButton);
imgbutton.setImageURI(uri);
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jalea.requestingform">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RequestActivity"></activity>
</application>
</manifest>

Your app bypasses the MainActivity since you have this the following code:
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() !=null){
Intent intent = new Intent(MainActivity.this,RequestActivity.class);
startActivity(intent);
//finish();
Log.w("1 : ","2.activity'e geçildi");
}
else{
Log.w("1 : ", "onAuthStateChanged:çıkış yaptı");
}
}
};
That code checks to see if the user is logged in and then skips the MainActivity and goes straight to RequestActivity. If you want the user to log in every time he/she opens the app then remove that code.
For your second problem, check out this sample code:
private void startPosting() {
mProgress.setMessage("Posting... ");
final String title_val = mPostTitle.getText().toString();
final String desc_val = mPostDesc.getText().toString();
final String cat_val = mPostCat.getSelectedItem().toString();
final String currency_val = mPostCurrency.getSelectedItem().toString();
final String amount_val = mPostAmount.getText().toString();
final String offer_val = mPostOffer.getText().toString();
final String pNumber_val = mPostPNumber.getText().toString();
if(!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && !TextUtils.isEmpty(cat_val)&& !TextUtils.isEmpty(currency_val) && !TextUtils.isEmpty(amount_val) &&!TextUtils.isEmpty(offer_val) && !TextUtils.isEmpty(pNumber_val) && mImageUri != null ){
mProgress.show();
StorageReference filepath = mStorage.child("Classifieds_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = mDatabase.push();
mDatabaseUsers.child(mCurrentUser.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
newPost.child("name").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("category").setValue(cat_val);
newPost.child("currency").setValue(currency_val);
newPost.child("amount").setValue(amount_val);
newPost.child("offer").setValue(offer_val);
newPost.child("phone number").setValue(pNumber_val);
newPost.child("latitude").setValue(mLastKnownLocation.getLatitude());
newPost.child("longitude").setValue(mLastKnownLocation.getLongitude());
newPost.child("timestamp").setValue(ServerValue.TIMESTAMP);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("profileImage").setValue(dataSnapshot.child("profile_image").getValue());
newPost.child("username").setValue(dataSnapshot.child("username").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
});
}
}
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
break;
case 1:
if(resultCode == RESULT_OK){
mImageUri = data.getData();
activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
mSelectImage.setImageURI(mImageUri);
}
break;
}
if (requestCode == CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
ActivityResult result = getActivityResult(data);
if (resultCode == RESULT_OK) {
mImageUri = result.getUri();
mSelectImage.setImageURI(mImageUri);
} else if (resultCode == CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(
PostActivity.this);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePicture.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePicture, 0);}
} else if (items[item].equals("Choose from Library")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
Hope this helps

For first :
It will start from your second activity only since you have written this
if(firebaseAuth.getCurrentUser() !=null){
Intent intent = new Intent(MainActivity.this,RequestActivity.class);
startActivity(intent);
//finish();
Log.w("1 : ","2.activity'e geçildi");
}
For sure reason you might have done sign in and its stores the auth to let the user directly go to next activity
For your second issue I am able to do it like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ConstantsCustomGallery.REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
//The array list has the image paths of the selected images
ArrayList<Image> images = data.getParcelableArrayListExtra(ConstantsCustomGallery.INTENT_EXTRA_IMAGES);
boolean showMinMax = true;
final MaterialDialog dialog = new MaterialDialog.Builder(this)
.title("Please wait")
.content("This won't take too long")
.progress(false, images.size(), showMinMax)
.show();
for (int i = 0; i < images.size(); i++) {
Uri uri = Uri.fromFile(new File(images.get(i).path));
StorageReference storage = FirebaseStorage.getInstance().getReference();
String Fpath = getFileName(uri) ;
//Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storage.child(FirebaseAuth.getInstance().getCurrentUser().getEmail()+"/images/"+Fpath);
riversRef.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
int maxUploading = dialog.getMaxProgress();
dialog.incrementProgress(1);
if(dialog.getCurrentProgress() == dialog.getMaxProgress()){
dialog.dismiss();
new MaterialDialog.Builder(HomePageActivity.this)
.title("DONE")
.content("Congratulations")
.show();
}
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
String key = mDatabase.child("users").push().getKey();
Map<String, Object> postValues = new HashMap<String, Object>();
postValues.put("/user-profile/" + FirebaseAuth.getInstance().getCurrentUser().getEmail()
.substring(0, FirebaseAuth.getInstance().getCurrentUser().getEmail().indexOf("#"))+"/user-images/"+key,downloadUrl.toString());
postValues.put("/user-profile/" + FirebaseAuth.getInstance().getCurrentUser().getEmail()
.substring(0, FirebaseAuth.getInstance().getCurrentUser().getEmail().indexOf("#"))+"/imagesuploaded/",maxUploading);
mDatabase.updateChildren(postValues);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
dialog.setContent("Hurray!!!!");
}
}

For launching the app from the activity you want, enter below code in manifest.xml file for the activity
<activity
android:name="SpinnerActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Related

Android Send Camera Intent Image to Firebase

I have one ImageButton. Whenever We click on ImageButton Camera Intent is open and we take a snap. Everything is working till here is fine. So, How can I upload this camera Intent image to Firebase with authentication? I am not able to find any tutorial video which thought us this but I try to encode the image in a function name called submit. From here I don't know what to do
package com.example.android.besafe;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static com.example.android.besafe.R.id.imageview;
public class CameraActivity extends AppCompatActivity {
private ImageButton mProfileImage;
Bitmap photo;
private static final int CAMERA_REQ = 1;
StorageReference mstorageRef;
String userId;
private FirebaseAuth mAuth;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mProfileImage = (ImageButton) findViewById(R.id.btnselect);
firebaseDatabase = FirebaseDatabase.getInstance();
ref = firebaseDatabase.getReference("ProfileInfo");
mAuth = FirebaseAuth.getInstance();
firebaseUser = mAuth.getCurrentUser();
userId = firebaseUser.getUid();
mProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQ);
}
});
}
public void submit(View v){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] b = stream.toByteArray();
StorageReference storageReference =mstorageRef.child("documentImages").child(userId).child("noplateImg");
//StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profile_images").child(userID);
storageReference.putBytes(b).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CameraActivity.this,"failed",Toast.LENGTH_LONG).show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQ && resultCode ==RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
}
}
}
I found two errors in your code, you're not calling submit() method, so it never executes.
The second you did not make a instance of mstorageRef.
Check code below, i tested and uploaded an image. i am doing it without user authentication, for the sake of simplicity.
public class CameraActivity extends AppCompatActivity {
private ImageButton mProfileImage;
Bitmap photo;
private static final int CAMERA_REQ = 1;
StorageReference mstorageRef;
String userId;
private FirebaseAuth mAuth;
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProfileImage = (ImageButton) findViewById(R.id.image_holder);
firebaseDatabase = FirebaseDatabase.getInstance();
ref = firebaseDatabase.getReference("ProfileInfo");
mAuth = FirebaseAuth.getInstance();
firebaseUser = mAuth.getCurrentUser();
// userId = firebaseUser.getUid();
mProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQ);
}
});
}
public void submit(){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] b = stream.toByteArray();
StorageReference storageReference =FirebaseStorage.getInstance().getReference().child("documentImages").child("noplateImg");
//StorageReference filePath = FirebaseStorage.getInstance().getReference().child("profile_images").child(userID);
storageReference.putBytes(b).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(CameraActivity.this, "uploaded", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CameraActivity.this,"failed",Toast.LENGTH_LONG).show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQ && resultCode ==RESULT_OK) {
photo = (Bitmap) data.getExtras().get("data");
submit();
}
}
}
something to keep in mind
check firebase storage read write permissions are set to allow if not using user authentication.
camera is dangerous permission, you need to ask permission from user to use it. add permission in manifest and code for using camera
make sure your internet/wifi is on
task.getDowloadUrl() not defined. You can use this i check , working perfectly.
private void firebaseUploadBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
StorageReference imageStorage = storage.getReference();
StorageReference imageRef = imageStorage.child("images/" + "imageName");
Task<Uri> urlTask = imageRef.putBytes(data).continueWithTask(task -> {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return imageRef.getDownloadUrl();
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String uri = downloadUri.toString();
sendMessageWithFile(uri);
} else {
// Handle failures
// ...
}
progressBar.setVisibility(View.GONE);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
// Bitmap imageBitmap = data.getData() ;
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (photo != null)
firebaseUploadBitmap(photo);
} else if (requestCode == SELECT_IMAGE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null)
firebaseUploadImage(uri);
}
}

calling another class functions from one class on button click in android

I am making an app with various activities and each activity uses the camera function which is defined in another class. I want that in each activity when the camera button is clicked the camera class is called.
This is my main class:-
package com.example.ishan.complainbox;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.String;
public class Crime extends MainActivity implements View.OnClickListener
{
camera cam=new camera();
EditText str,city,pn,det;
Button save,pic;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
// Get References of Views
str = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pn = (EditText) findViewById(R.id.pin);
det = (EditText) findViewById(R.id.detail);
save = (Button) findViewById(R.id.save);
pic=(Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
}
public void onClick(View view) {
String street = str.getText().toString();
String cty = city.getText().toString();
String pin = pn.getText().toString();
String detail = det.getText().toString();
// check if any of the fields are vaccant
if(str.equals("")||city.equals("")||pn.equals("")||det.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vacant",
Toast.LENGTH_LONG).show();
return;
}
// check if both passwords match
else
{
// Save the Data in Database
dbHandler.insertEntry(street,cty,pin,detail);
Toast.makeText(getApplicationContext(), "Complaint Successfully
Filed ", Toast.LENGTH_LONG).show();
}
}
};
.....and this is the camera class..:-
package com.example.ishan.complainbox;
/**
* Created by ishan on 13/04/2017.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class camera extends MainActivity{
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
btnSelect = (Button) findViewById(R.id.uploadpic);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ivImage = (ImageView) findViewById(R.id.imgView);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED)
{
if(userChosenTask.equals("Take Photo"))
cameraIntent();
else if(userChosenTask.equals("Choose from Library"))
galleryIntent();
} else {
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(camera.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(camera.this);
if (items[item].equals("Take Photo")) {
userChosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new
File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() +
".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap(getApplicationContext().
getContentResolver(),
data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
}
This can be achieved through regular inter-activity communication mechanisms like passing intents or using broadcast receivers. I would suggest using intents - Refer this basic example from Android doc: https://developer.android.com/training/basics/firstapp/starting-activity.html
EDIT
Response to OP's question in comment-
You have to save the image file to FS in your Camera Class and pass the file name as an Extra with the intent to your Crime class. Since you are dealing with storage your Apps's manifest now would need additional permissions. I would recommend you go through this thread: Camera is not saving after taking picture

Starting camera activity, app crashes

I have problem, that I have been searching for whole week. I'm creating app that sends photo and some data to server. The problem is that when I start activity, camera has to start but, for some devices app crashes. I cant describe the error because devices are in other cities. I have LG G3 and HUAWEI P7 on both of them works fine. I think this might be something wrong with permissions but I'm not sure.
package com.fishingtournaments.ZvejysZvejui;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.support.v4.os.EnvironmentCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.Semaphore;
public class SendImageActivity extends AppCompatActivity implements View.OnClickListener {
public static final int CAMERA_PERMISSION_REQUEST_CODE = 8675809;
TextView fish_n, fish_s, points;
public static final int REQUEST_CAPTURE = 1;
public static String path;
public String fish_name, fish_length, fish_points, colleague_id, fish_size, fish_photo, fish_id,
user_id, user_name = "";
//Declaring views
private Button buttonUpload;
private ImageView imageView;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
//Uri to store the image uri
private Uri imageUri; /*, uriSavedImage*/
private File imagesFolder, image;
private String fixedURI;
//----------------------------------//
// Storage for camera image URI components
private final static String CAPTURED_PHOTO_PATH_KEY = "mCurrentPhotoPath";
private final static String CAPTURED_PHOTO_URI_KEY = "uriSavedImage";
// Required for camera operations in order to save the image file on resume.
private String mCurrentPhotoPath = null;
private Uri uriSavedImage = null;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (mCurrentPhotoPath != null) {
savedInstanceState.putString(CAPTURED_PHOTO_PATH_KEY, mCurrentPhotoPath);
}
if (uriSavedImage != null) {
savedInstanceState.putString(CAPTURED_PHOTO_URI_KEY, uriSavedImage.toString());
}
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(CAPTURED_PHOTO_PATH_KEY)) {
mCurrentPhotoPath = savedInstanceState.getString(CAPTURED_PHOTO_PATH_KEY);
}
if (savedInstanceState.containsKey(CAPTURED_PHOTO_URI_KEY)) {
uriSavedImage = Uri.parse(savedInstanceState.getString(CAPTURED_PHOTO_URI_KEY));
}
super.onRestoreInstanceState(savedInstanceState);
}
//-++-+-+-+-+-+-+-+-+-+-+-+-+---//
#Override
protected void onCreate(Bundle savedInstanceState) {
//Requesting storage permission
//TODO INTERFACE,
//TODO CHECK PERMISSIONS
//TODO TEST ON OTHER PHONES
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
setContentView(R.layout.activity_send_image);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload.setOnClickListener(this);
} else {
setContentView(R.layout.activity_send_image);
if (ContextCompat.checkSelfPermission(SendImageActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
imagesFolder = new File(Environment.getExternalStorageDirectory(), "FishingTournament");
image = new File(imagesFolder, "QR_" + timeStamp + ".png");
uriSavedImage = Uri.fromFile(image);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(i, REQUEST_CAPTURE);
} else {
String[] permissionRequest = {Manifest.permission.CAMERA};
ActivityCompat.requestPermissions(SendImageActivity.this, permissionRequest, CAMERA_PERMISSION_REQUEST_CODE);
}
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload.setOnClickListener(this);
}
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", "asd") //Adding text parameter to the request
.addParameter("colleague_id", colleague_id)
.addParameter("fish_length", fish_size)
.addParameter("fish_points", fish_points)
.addParameter("fish_photo", fish_photo)
.addParameter("fish_id", fish_id)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CAPTURE) {
if (data != null) {
fixedURI = String.valueOf(uriSavedImage);
fixedURI = fixedURI.replace("file://", "");
path = fixedURI;
// Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(path);
// imageView.setImageBitmap(bitmap);
} else {
fixedURI = String.valueOf(uriSavedImage);
fixedURI = fixedURI.replace("file://", "");
path = fixedURI;
// Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(path);
// imageView.setImageBitmap(bitmap);
}
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
//Requesting permission
private void requestStorageReadPermission() {
if (ContextCompat.checkSelfPermission(SendImageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(SendImageActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
Toast.makeText(SendImageActivity.this, "Norint siųsti nuotrauką reikalingas leidimas prie failų saugyklos", Toast.LENGTH_SHORT).show();
}
//And finally ask for the permission
ActivityCompat.requestPermissions(SendImageActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
if (v == buttonUpload) {
uploadMultipart();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
onBackPressed();
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
final String user_name = getIntent().getStringExtra("user_name");
final String colleague_id = getIntent().getStringExtra("colleague_id");
final String user_id = getIntent().getStringExtra("user_id");
Intent intent = new Intent(SendImageActivity.this, ChooseFishActivity.class);
intent.putExtra("colleague_id", colleague_id);
intent.putExtra("user_name", user_name);
intent.putExtra("user_id", user_id);
startActivity(intent);
finish();
}
}
It might look dumb why I have if in onCreate() method, it's because in my LG G3 camera is restarting on taking photo. And thats why my onActivityResult() method looks strange.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fishingtournaments.ZvejysZvejui">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/descicon"
android:label="Žvejys žvejui"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ChooseFishActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ResultActivity"
android:configChanges="orientation"
android:parentActivityName=".ChooseFishActivity"
android:screenOrientation="portrait" />
<activity
android:name=".ShowResultsActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
<activity android:name=".SendImageActivity"
android:configChanges="orientation"
android:parentActivityName=".LoginActivity"
android:screenOrientation="portrait" />
</application>
</manifest>
P.S. My code might look unclean, sorry for that, I have been doing everything and testing everything to solve that problem.
BTW I'm requesting permission for storage in my LoginActivity and there I'm creating folder for photos.
LoginActivity
package com.fishingtournaments.ZvejysZvejui;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
public class LoginActivity extends AppCompatActivity {
private static final int STORAGE_PERMISSION_CODE = 123;
EditText qrCode_edit;
Button check_button;
// Button result_button;
public String colleague_id;
public String colleague_name;
public String user_id, user_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if(ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(LoginActivity.this, "Užklausa permissionų", Toast.LENGTH_SHORT).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(LoginActivity.this, "Norint siųsti nuotrauką reikalingas leidimas prie failų saugyklos", Toast.LENGTH_SHORT).show();
}
//And finally ask for the permission
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}else{
Toast.makeText(LoginActivity.this, "Teisės suteiktos", Toast.LENGTH_SHORT).show();
}
File direct = new File(Environment.getExternalStorageDirectory()+"/FishingTournament");
if(!direct.exists()) {
if (direct.mkdir())
Toast.makeText(LoginActivity.this, "Direktorija sukurta", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(LoginActivity.this, "Nesukurta direktorija, nes ji jau egzistuoja", Toast.LENGTH_SHORT).show();
}
// it will create two folder in your internal storage first is specifyfoldername and another one inside the mentioned folder which is nestedfoldername
qrCode_edit = (EditText) findViewById(R.id.qrCode_editText);
check_button = (Button) findViewById(R.id.check_button);
// result_button = (Button) findViewById(R.id.results);
//QR Code
final Activity activity = this;
/**
* Button for scanning QR code
*
*/
check_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check_button.setEnabled(false);
String qrCode = qrCode_edit.getText().toString();
//QR Code
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Užveskite kamerą ant QR kodo");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
check_button.setEnabled(true);
//---
/*Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(LoginActivity.this, ChooseFishActivity.class);
colleague_id = jsonResponse.getString("colleague_id");
colleague_name = jsonResponse.getString("colleague_name");
user_id = jsonResponse.getString("user_id");
intent.putExtra("colleague_id",colleague_id);
intent.putExtra("user_name",colleague_name);
intent.putExtra("user_id",user_id);
startActivity(intent);
// finish();
//startActivity(new Intent(LoginActivity.this, ChooseFishActivity.class));
}else{
String message = jsonResponse.getString("message");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
*//*ats.setText(message);*//*
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(qrCode, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);*/
}
});
/**
* Button for launching ShowResultsActivity
*/
/*result_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, ShowResultsActivity.class);
startActivity(intent);
finish();
}
});*/
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null){
if(result.getContents()==null){
Toast.makeText(this, "Atšaukėte skanavimą", Toast.LENGTH_LONG).show();
}else{
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
/*If correct QR-code*/
if (success){
Intent intent = new Intent(LoginActivity.this, ChooseFishActivity.class);
colleague_id = jsonResponse.getString("colleague_id");
colleague_name = jsonResponse.getString("colleague_name");
user_id = jsonResponse.getString("user_id");
user_name = jsonResponse.getString("user_name");
intent.putExtra("colleague_id",colleague_id);
intent.putExtra("user_name",colleague_name);
intent.putExtra("user_id",user_id);
Toast.makeText(getApplicationContext(),"Sveiki, " + user_name,Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}else{
String message = jsonResponse.getString("message");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(result.getContents(), responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
So I figured out where the problem was.
The error was exposed beyond app through ClipData.Item.getUri() . Basicly the problem was in this line i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);. After searching for this error I found solution in this post

Capturing Image from Camera and Upload to Firebase

I am working on a simple blog app that allows the user to upload photo from phone gallery and descriptions to the Firebase Server. I am trying to modify my current project to allow the user to capture photo from camera and uploading it to the firebase server.
Currently, I am able to display the image that i have captured into imagebutton, however i am unable to post my image to the firebase server (The "submit post" button does not react to my onclick function).
I am suspecting there is some error in my startPosting() function or i did not encode the image correctly? Please help.
package simpleblog2.emily.example.com.simpleblog2;
import android.app.ProgressDialog;
import android.content.ContentProvider;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import java.io.File;
public class PostActivity extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostTitle;
private EditText mPostDesc;
private Button mSubmitBtn;
private ProgressDialog mProgress;
private DatabaseReference mDatabase;
private Uri mImageUri = null;
private static final int GALLERY_REQUEST = 1;
private static final int CAMERA_REQUEST_CODE = 1;
private StorageReference mStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_REQUEST_CODE);
intent1.setType("image/*");
/*
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
*/
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting() {
mProgress.setMessage("Posting to blog...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
/* mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
*/
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
mSelectImage.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
I have found a solution to my question, i realized that i can get my captured data using the function of data.getData() instead of using the Bitmap function:
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
Also, Previously i did not realized that my 'crop' function could not work because i am missing of:
mImageUri = resultUri;
I realized that there is an issue that if i did not crop my captured image, the fire-base could not handle the high resolution (Or storage size? and it will be loading very slow/image did not appear), This can be resolve by the 'cropping' function.
The final code is stated below:
Thanks all for your help.
package simpleblog2.emily.example.com.simpleblog2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
public class PostActivity extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostTitle;
private EditText mPostDesc;
private Button mSubmitBtn;
private ProgressDialog mProgress;
private DatabaseReference mDatabase;
private Uri mImageUri = null;
private static final int GALLERY_REQUEST =1;
private static final int CAMERA_REQUEST_CODE=1;
private StorageReference mStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
//startActivityForResult(intent,CAMERA_REQUEST_CODE);
/*
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
*/
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void startPosting(){
mProgress.setMessage("Posting to blog...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if(!TextUtils.isEmpty(title_val)&&!TextUtils.isEmpty(desc_val) && mImageUri != null){
mProgress.show();
StorageReference filepath = mStorage.child("Blog_Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl =taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(PostActivity.this,MainActivity.class));
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
/* Bitmap mImageUri1 = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri1);
Toast.makeText(this, "Image saved to:\n" +
data.getExtras().get("data"), Toast.LENGTH_LONG).show();
*/
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
mSelectImage.setImageURI(resultUri);
mImageUri = resultUri;
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
Before it was if auth != null but I changed it to if true so the if will always evaluate true.
private void uploadFile() {
//if there is a file to upload
if (filePath != null) {
//displaying a progress dialog while upload is going on
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference riversRef = storageReference.child("Blog_Images.jpg");
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successfull
//and displaying a success toast
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successfull
//hiding the progress dialog
progressDialog.dismiss();
//and displaying error message
Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
//calculating progress percentage
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//displaying percentage in progress dialog
progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
//if there is not any file
else {
//you can display an error toast
}
}
Your class field mImageUri is never initialized. You put received bitmap in local field, called the same as the class field.
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
Therefore, the condition is never true.
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && mImageUri != null)
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
/* mImageUri = data.getData();
mSelectImage.setImageURI(mImageUri);
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
*/
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
mSelectImage.setImageBitmap(mImageUri);
}
There is a chance that your URI is null. I assume, this is the problem.
Unless you do it somewhere else?
The image might be loaded because the requestCode = CAMERA_REQUEST_CODE but NOT CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE.
I am going to post below a code I used to do what you ask, but first few things you need to understand.
From android version 7 using Uri.parseFromFile(file) return a error because google want to restrict your access. From now on if you want to get file uri you should use FileProvider
declare permmisions and FileProvider in your manifest:
//File provider declaration in manifest.
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.hadas.yotam.manchworkers.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
//in new xml file define the location you need permmision to, the code below give you permmision for any external file.
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
so now when you upload use the global Uri variable if onActivityResault is successful, here is the code:
if(Build.VERSION.SDK_INT>=24) {
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
Then in your onActivityResult you do check if your photoURI = null, if its true (its null)
use photoURI = data.getData();
//if phone android version greater or equal to Marshmelo
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M){
//check if have permmission to write to external + permmision to camera
if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
//if its have permission then new intent to capture image
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//if android version >= 24 (Android Nugget)
if(Build.VERSION.SDK_INT>=24) {
//create new String to pictures directory and set the file name to current_time.jpg
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
//set GLOBAL variable Uri from the file using FileProvider
photoURI = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file1);
//add the file location the intent (the picture will be save to this file)
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
}
tagIntent = CAPTURE_RESAULT;
//else - dont have permission, request for permission
}else{
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},CAPTURE_RESAULT);
}
else -
}else{
// same thing only without FileProvider (FileProvider only required since Nugget)
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/" + Calendar.getInstance().getTimeInMillis() + ".jpg";
File file1 = new File(file);
photoURI = Uri.fromFile(file1);
intent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
tagIntent = CAPTURE_RESAULT;
}
//if phone can handle the intent, start the intent for resault.
if(intent.resolveActivity(getPackageManager())!=null) {
startActivityForResult(intent,tagIntent);
}

How to add a picture from local storage to update Firebase user's photo profile using .setPhotoUri in Android?

I have an error while updating user's photo profile in Firebase. I want to upload user's local photo to Firebase user's profile. This is my activity.
package naufal.com.tugasakhir;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.bumptech.glide.util.Util;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import java.text.ParseException;
public class EditProfile extends AppCompatActivity {
private EditText mUsername;
private Button mUpdateProfileBtn;
private ImageButton mImageBtn;
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
private static final int GALLERY_REQUEST = 1;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private Uri imageUri2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mUsername = (EditText) findViewById(R.id.userName);
mUpdateProfileBtn = (Button) findViewById(R.id.updateProfileBtn);
mImageBtn = (ImageButton) findViewById(R.id.imageField);
String username = user.getDisplayName();
mUsername.setText(username);
mUpdateProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//updating user's profile data
String nameUser = mUsername.getText().toString();
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setPhotoUri(Uri.parse(imageUri2))
.setDisplayName(nameUser)
.build();
if(TextUtils.isEmpty(nameUser)){
mUsername.setError("Enter a username");
}
if(imageUri2 == null){
Toast.makeText(EditProfile.this, "Error updating image",
Toast.LENGTH_SHORT).show();
}
//if the field is not null, process continue to update profile
else {
mUser.updateProfile(profileUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) { //success on updating user profile
Toast.makeText(EditProfile.this, "Update Profile Succedeed",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(EditProfile.this, HomePage.class));
} else { //failed on updating user profile
Toast.makeText(EditProfile.this, "Update Profile Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//setting image for user
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
Uri imageUri = data.getData();
mImageBtn.setImageURI(imageUri);
imageUri2 = imageUri;
} else {
Toast.makeText(EditProfile.this, "Failed showing image",
Toast.LENGTH_SHORT).show();
}
}
}
This is how I get the user's profile from Firebase:
String email = user.getEmail();
String username = user.getDisplayName();
Uri uriImage = user.getPhotoUrl();
mUserName.setText(username);
mUserStat.setText(email);
mUriImageProfile.setImageURI(uriImage);
Thanks for the response.
You need to get this image from your device, put the file in firebase and then use it as a link
You can check my github to see it working https://github.com/chrystianmelo/appmodule
The code
**PROFILE_SERVICES**
public void putFile(Bitmap bitmap){
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference mountainsRef = storageRef.child("images/"+getUID()+".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("chrys", "Img not set");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mountainsRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onSuccess(Uri uri) {
setProfilePic(uri);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("chrys", "Img set but whereeee");
// Handle any errors
}
});
}
});
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void setProfilePic(Uri uri){
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(uri)
.build();
user.updateProfile(profileUpdates);
}
**PROFILE_ACTIVITY**
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
Bitmap bitmap;
try {
ProfileServices services = new ProfileServices();
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Objects.requireNonNull(data.getData())));
services.putFile(bitmap);
Log.i("chrys", "GET FROM LOCAL.: OK");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("chrys", "GET FROM LOCAL.: RUIM");
}
}
}
}
#SuppressLint("IntentReset")
public void getImg(){
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
#SuppressLint("IntentReset") Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
}
private static class DownLoadImageTask extends AsyncTask<String,Void,Bitmap> {
#SuppressLint("StaticFieldLeak")
ImageView imageView;
DownLoadImageTask(ImageView imageView){
this.imageView = imageView;
}
/*
doInBackground(Params... params)
Override this method to perform a computation on a background thread.
*/
protected Bitmap doInBackground(String...urls){
String urlOfImage = urls[0];
Bitmap logo = null;
try{
InputStream is = new URL(urlOfImage).openStream();
/*
decodeStream(InputStream is)
Decode an input stream into a bitmap.
*/
logo = BitmapFactory.decodeStream(is);
}catch(Exception e){ // Catch the download exception
e.printStackTrace();
}
return logo;
}
/*
onPostExecute(Result result)
Runs on the UI thread after doInBackground(Params...).
*/
protected void onPostExecute(Bitmap result){
imageView.setImageBitmap(result);
}
}
}
<!-- begin snippet: js hide: false console: true babel: false -->

Categories

Resources