How to download an audio from from Firebase storeage? - java

I am developing an android app to upload and download audios from Firebase and I have successfully uploaded three audio files (A.mp3,B.mp3 and C.mp3) to Firebase storage.Now what I want is to choose which file to download say B.mp3 and this is where I am stuck.How do I choose which audio to download and then download it?
I have 3 buttons,one for choosing a file to upload,upload button and download button.
Here is my code...
package com.hussainapplications.firebasestorageexample;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
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.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
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.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Button buttonChoose,buttonUpload,buttonDownload;
TextView fileselected;
private StorageReference storageReference;
private static final int PICK_IMAGE_REQUEST = 234;
private Uri filePath;
public static int fileCount=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose=findViewById(R.id.buttonChoose);
buttonUpload=findViewById(R.id.buttonUpload);
buttonDownload=findViewById(R.id.buttonDownload);
fileselected=findViewById(R.id.fileselected);
storageReference = FirebaseStorage.getInstance().getReference();
final ProgressDialog progressDialog = new ProgressDialog(this);
buttonChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("Audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Audio"), PICK_IMAGE_REQUEST);
}
});
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fileCount++;
if (filePath != null) {
//displaying a progress dialog while upload is going on
progressDialog.setTitle("Uploading");
progressDialog.show();
StorageReference riversRef = storageReference.child("Audio/audio" + fileCount);
riversRef.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successfull
//hiding the progress dialog
progressDialog.dismiss();
//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("Uploading....");
//progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
}
});
}
//if there is not any file
else {
//you can display an error toast
}
}
});
buttonDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fileCount++;
try {
StorageReference riversRef = storageReference.child("Audio").child("New_Audio.mp3");
//download
riversRef = storageReference.child("Audio").child("New_Audio.mp3"+fileCount);
File localFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "New_Audio.mp3");
localFile .createNewFile();
riversRef.getFile(localFile);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#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 bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
fileselected.setText("File Selected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/buttonChoose"
android:text="Choose File"/>
<Button
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/buttonUpload"
android:layout_below="#+id/buttonChoose"
android:text="Upload"/>
<Button
android:layout_width="200dp"
android:layout_height="50dp"
android:id="#+id/buttonDownload"
android:layout_below="#+id/buttonUpload"
android:text="Download"/>
<TextView
android:id="#+id/fileselected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/buttonChoose"
android:layout_marginStart="7dp"
android:textColor="#000"
android:textStyle="bold"
android:layout_toEndOf="#id/buttonChoose"
android:textSize="20sp" />
</RelativeLayout>

Related

Null image on firebase storage. How to save it original?

I have tried to solve an issue on my app but I couldn't find a solution. I want the app to upload the images on Firebase Storage after the post is clicked. The problem is that when I click post the images are uploaded as .null and I can't add them as posts on my app here is a photo of Firebase Storage:
Here is the code of PostsActivity:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.selfcial.R;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
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.StorageTask;
import com.theartofdev.edmodo.cropper.CropImage;
import java.util.HashMap;
public class PostActivity extends AppCompatActivity {
Uri imageUri;
String myUrl;
StorageTask uploadTask;
StorageReference storageReference;
ImageView close, image_added;
TextView post;
EditText description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
close = findViewById(R.id.close);
image_added = findViewById(R.id.image_added);
post = findViewById(R.id.postPhoto);
description = findViewById(R.id.description);
storageReference = FirebaseStorage.getInstance().getReference("posts");
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PostActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
CropImage.activity()
.setAspectRatio(1, 1)
.start(PostActivity.this);
}
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = this.getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void uploadImage() {
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Posting please wait..");
progressDialog.show();
if (imageUri != null) {
StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
uploadTask = fileReference.putFile(imageUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (task.isSuccessful()) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
myUrl = downloadUri.toString();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("posts");
String postId = reference.push().getKey();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("postId", postId);
hashMap.put("postImage", myUrl);
hashMap.put("description", description.getText().toString());
hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.child(postId).setValue(hashMap);
progressDialog.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
finish();
}else {
Toast.makeText(PostActivity.this, "Failed.", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PostActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(this, "No image selected.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUri = result.getUri();
image_added.setImageURI(imageUri);
}else {
Toast.makeText(this, "Something gone wrong", Toast.LENGTH_SHORT).show();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
}
I thought that I have to initialize Uri inside onCreate method but nothing changed. What should it be?
I found the solution for anyone else who has the same issue, the solution is that I should have added a ! into this if, like this:
if (!task.isSuccessful()) {
throw task.getException();
}
It has been noticed that the method you are using to retrieve the file mime type doesn't work on some devices. You could try some other alternatives like using apache commonsIO lib or alternatively try this code :
public String getMimeType(Uri uri) {
String mimeType = null;
if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
ContentResolver cr = getAppContext().getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase());
}
return mimeType;
}

Breaking my neck with ProgressDialog and dismiss method issues

I've made a recipe app, i've been fixing a few issues because i couldn't get the app running but it seems that everytime a fix an error another one shows up, my project can't resolve method dismiss() i don't know what to do, i've made this app accordingly to an Youtube channel but it's giving me lots of issues, i don't know if i missed some code or if it's something else, i've also noticed that there are many things in my Dialog.java that cannot be resolved, such as setDefaultIcon, WindowDecorActionBar, #UnsupportedAppUsage, isDestroyed, setShowHideAnimationEnabled, IdRes among lots of other things, i don't even know where all of that comes from i'm a bit lost here.
This is my Upload_Recipe activity:
package com.example.recipeapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
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.text.DateFormat;
import java.util.Calendar;
public class Upload_Recipe extends AppCompatActivity {
ImageView recipeImage;
Uri uri;
EditText txt_name, txt_description, txt_price;
String imageUrl;
Object progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload__recipe);
recipeImage = (ImageView) findViewById(R.id.iv_foodImage);
txt_name = (EditText) findViewById(R.id.txt_recipe_name);
txt_description = (EditText) findViewById(R.id.text_description);
txt_price = (EditText) findViewById(R.id.text_price);
}
public void btnSelectImage(View view) {
Intent photoPicker = new Intent(Intent.ACTION_PICK);
photoPicker.setType("image/*");
startActivityForResult(photoPicker, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
uri = data.getData();
recipeImage.setImageURI(uri);
} else Toast.makeText(this, "Você não selecionou uma imagem", Toast.LENGTH_SHORT).show();
}
public void uploadImage() {
StorageReference storageReference = FirebaseStorage.getInstance()
.getReference()
.child("RecipeImage")
.child(uri.getLastPathSegment());
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isComplete()) ;
Uri urlImage = uriTask.getResult();
if (urlImage != null) {
imageUrl = urlImage.toString();
}
uploadRecipe();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
}
});
}
public void btnUploadRecipe(View view) {
uploadImage();
}
public void uploadRecipe() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Enviando Receita...");
progressDialog.show();
progressDialog.dismiss();
finish();
FoodData foodData = new FoodData(txt_name.getText().toString()
, txt_description.getText().toString(), txt_price.getText().toString()
, imageUrl);
String myCurrentDateTime = DateFormat.getDateTimeInstance()
.format(Calendar.getInstance().getTime());
FirebaseDatabase.getInstance()
.getReference("Recipe")
.child(myCurrentDateTime).setValue(foodData).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Upload_Recipe.this, "Receita Enviada", Toast.LENGTH_SHORT).show();
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Upload_Recipe.this, "Falha ao Enviar", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
private void ProgressDialog(Object progressDialog) {
this.progressDialog = progressDialog;
ProgressDialog(progressDialog);
}
}
You write progressDialog.dismiss(); this line into uploadRecipe method.
uploadRecipe();
progressDialog.dismiss(); //Remove this line

How do I upload multiple images to Firebase's realtime database?

enter image description here
I want to upload multiple images to Firebase's realtime database. It is working with a single image, but not multiple.
I know I have to give a different path for every individual image, but I don't understand how to do this.
Could anyone help me to make changes to my code or at least guide me to solving my issue? I scoured online resources for the answer but have yet to find the answer. Thanks in advance!
How can I upload multiple images to Firebase's realtime database, based on my code what do I have to integrate/implement to do this?
package com.amazoneindia.amazone_india;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
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.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import static android.app.Activity.RESULT_OK;
/**
* A simple {#link Fragment} subclass.
*/
public class Upload_apk extends Fragment {
Button bt1,bt2;
TextView tv;
Button btnss1,btnss2,btnss3,btnss4,btnss5;
TextView tvss1,tvss2,tvss3,tvss4,tvss5;
private EditText Name, Email, Pass, Ph, AppTitle, Appdescript;
private FirebaseAuth mAuth;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private ImageView imageView;
private ImageView imagess1,imagess2,imagess3,imagess4,imagess5;
private Uri imageUri;
public static final String FB_STORAGE_PATH = "image/";
public static final String FB_DATABASE_PATH = "image";
public static final int REQUEST_CODE=1234;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_upload_apk, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
mDatabaseRef = FirebaseDatabase.getInstance().getReference(FB_DATABASE_PATH);
imageView = view.findViewById(R.id.etimage);
imagess1=view.findViewById(R.id.imagess1);
imagess2=view.findViewById(R.id.imagess2);
imagess3=view.findViewById(R.id.imagess3);
imagess4=view.findViewById(R.id.imagess4);
imagess5=view.findViewById(R.id.imagess5);
Name = view.findViewById(R.id.etname);
Email = view.findViewById(R.id.etemail);
Pass = view.findViewById(R.id.etpassword);
Ph = view.findViewById(R.id.etphone);
AppTitle=view.findViewById(R.id.ettitle);
Appdescript=view.findViewById(R.id.etdescrip);
tv=view.findViewById(R.id.upload_tv);
tvss1=view.findViewById(R.id.tvss1);
tvss2=view.findViewById(R.id.tvss2);
tvss3=view.findViewById(R.id.tvss3);
tvss4=view.findViewById(R.id.tvss4);
tvss5=view.findViewById(R.id.tvss5);
bt1=view.findViewById(R.id.browsebtn);
btnss1=view.findViewById(R.id.btnss1);
btnss2=view.findViewById(R.id.btnss2);
btnss3=view.findViewById(R.id.btnss3);
btnss4=view.findViewById(R.id.btnss4);
btnss5=view.findViewById(R.id.btnss5);
bt2=view.findViewById(R.id.upload_btn);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
btnss5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Image"), REQUEST_CODE);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (imageUri!=null){
final ProgressDialog dialog=new ProgressDialog(getContext());
dialog.setTitle("Uploading Image....");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.show();
bt1.setVisibility(View.GONE);
tv.setVisibility(View.GONE);
btnss1.setVisibility(View.GONE);
tvss1.setVisibility(View.GONE);
btnss2.setVisibility(View.GONE);
tvss2.setVisibility(View.GONE);
btnss3.setVisibility(View.GONE);
tvss3.setVisibility(View.GONE);
btnss4.setVisibility(View.GONE);
tvss4.setVisibility(View.GONE);
btnss5.setVisibility(View.GONE);
tvss5.setVisibility(View.GONE);
StorageReference ref =mStorageRef.child(FB_STORAGE_PATH + System.currentTimeMillis() +"."+getImageExt(imageUri));
ref.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
dialog.dismiss();
Toast.makeText(getActivity(),"Image Uploaded",Toast.LENGTH_SHORT).show();
ImageUpload imageUpload=new ImageUpload(Name.getText().toString(),Email.getText().toString(),Pass.getText().toString(),Ph.getText().toString(),AppTitle.getText().toString(),Appdescript.getText().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploaded=mDatabaseRef.push().getKey();
mDatabaseRef.child(uploaded).setValue(imageUpload);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
dialog.dismiss();
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress=(int)(100 * taskSnapshot.getBytesTransferred()/ taskSnapshot.getTotalByteCount());
dialog.setProgress(progress);
}
});
}else {
Toast.makeText(getActivity(),"Please select image",Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE && resultCode == RESULT_OK && data !=null && data.getData() != null){
imageUri=data.getData();
try{
Bitmap bm= MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),imageUri);
imageView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getImageExt(Uri uri){
ContentResolver contentResolver=getActivity().getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
}
Save the picked images in a bitmap list
bitmaps[i] = MediaStore.Images.Media.getBitmap(getContentResolver(), fileList[i]);
Method for uploading multiple images to the firebase
private void uploadImages() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.setCancelable(false);
progressDialog.show();
uri = new Uri[bitmaps.length];
for (int i = 0; i < bitmaps.length; i++) {
if (bitmaps[i] == null) {
break;
} else {
uri[i] = getImageUri(this, bitmaps[i]);
Log.e("ImageUploadActivity", "---///" + i + "--" +
uri[i].toString());
mStorageReferenceImages = storageReference.child("images");
StorageReference ref =
mStorageReferenceImages.child(uri[i].getLastPathSegment());
ref.putFile(uri[i])
.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot
taskSnapshot)
{
progressDialog.dismiss();
Toast.makeText(ImageUploadActivity.this, "Uploaded",
Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ImageUploadActivity.this, "Failed " +
e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new
OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot
taskSnapshot) {
double progress = (100.0 *
taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int)
progress + "%");
}
});
}
}
}
}
Method to convert bitmap into uri
/*--convert bitmap to uri--*/
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),
inImage, "Title", null);
return Uri.parse(path);
}
you can add check boxes for all the image_screenshots and then when you press opload button
make a logic to findout which checkbox is selected and according to that u can upload screenshots, like logic -> when btn upload pressed add if statement to check the conditions of the checkboxes , add 3 seperate if stetments for 3 screen shots
on Button pressed{
if(checkbox1.isChecked()) { uploadimage}
if(checkbox2.isChecked()) { uploadimage}
if(checkbox3.isChecked()) { uploadimage}
}

'Continue' button won't go to the next activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a button with buttonID "more_button", and after clicking on the button, I want to go to 'Home Activity'.
But when I click the button, the app stops and gives me a message:
App has stopped
Here is the code in question:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
FloatingActionButton first_button = (FloatingActionButton) findViewById(R.id.first_button);
FloatingActionButton second_button = (FloatingActionButton) findViewById(R.id.second_button);
FloatingActionButton third_button = (FloatingActionButton) findViewById(R.id.third_button);
Button more_button = (Button) findViewById(R.id.more_button);
second_button.setEnabled(false);
final ArrayList<String> contacts = getIntent().getStringArrayListExtra("CONTACTS");
more_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gotohome = new Intent(FirstActivity.this, HomeActivity.class);
FirstActivity.this.startActivity(gotohome);
}
});
This is the HomeActivity I want to go to...it has various features of camera and audio- If I cannot access the Home Activity and nothing seems to be wrong with my onClickListener, is it because of code in the Home Activity?
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.Image;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
// this is the one FR
public class HomeActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
Button buttonStart, buttonStop, buttonPlayLastRecordAudio,
buttonStopPlayingRecording ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final ArrayList<String> contacts = getIntent().getStringArrayListExtra("CONTACTSLIST");
Button location_button = (Button) this.findViewById(R.id.button5);
/* location_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendSMS("CONTACTSLIST", message);
}
}); */
location_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermissionText(Manifest.permission.SEND_SMS)) {
// TODO GET THIS INTENT RECIEVER TO WORK
//String[] contacts = getIntent().getExtras().getStringArray("CONTACTS");
//String[] contacts = new String[] {"3345", "5554", "5556"};
for(int i = 0; i < contacts.size(); i++) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(contacts.get(i), null, message, null, null);
}
} else {
Toast.makeText(HomeActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
});
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, new LocationListener() {
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
double longitude = myLocation.getLongitude();
double latitude = myLocation.getLatitude();
message += "This is my location: " + "https://www.google.co.id/maps/#" + latitude + "," + longitude;
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
buttonStart = (Button) findViewById(R.id.button);
buttonStop = (Button) findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
buttonStopPlayingRecording = (Button)findViewById(R.id.button4);
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
random = new Random();
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(HomeActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
Toast.makeText(HomeActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
buttonStop.setEnabled(false);
buttonStart.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(HomeActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});
Button button6= (Button) findViewById(R.id.button6);
button6.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.wix.com"));
startActivity(intent);
}});
}
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(HomeActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO,ACCESS_FINE_LOCATION}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
boolean LocationPermission= grantResults[2] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission && LocationPermission) {
Toast.makeText(HomeActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(HomeActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(),
ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED &&
result2 == PackageManager.PERMISSION_GRANTED;
}
private boolean checkPermissionText(String permission) {
int checkPermission = ContextCompat.checkSelfPermission(this, permission);
return (checkPermission == PackageManager.PERMISSION_GRANTED);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Lastly, this is the xml for Home:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/button1"
android:layout_width="100dp"
android:layout_height="90dp"
android:text="Take Photo"
app:srcCompat="#android:drawable/ic_menu_camera"
android:layout_above="#+id/button3"
android:layout_toRightOf="#+id/imageView1"
android:layout_toEndOf="#+id/imageView1"></Button>
<ImageView android:id="#+id/imageView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"></ImageView>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/button"
android:layout_width="90dp"
android:layout_height="48dp"
android:layout_above="#+id/button3"
android:layout_marginBottom="17dp"
android:layout_toEndOf="#+id/imageView"
android:layout_toRightOf="#+id/imageView"
android:tint="#android:color/holo_red_dark"
android:drawableTop="#android:drawable/ic_btn_speak_now" />
<Button
android:id="#+id/button2"
android:layout_width="90dp"
android:layout_height="48dp"
android:text="STOP"
android:layout_alignTop="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/button3"
android:layout_width="90dp"
android:layout_height="48dp"
android:layout_alignLeft="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/button"
android:layout_alignTop="#+id/button4"
android:drawableTop="#android:drawable/ic_media_play"
android:stateListAnimator="#null" />
<Button
android:id="#+id/button4"
android:layout_width="90dp"
android:layout_height="48dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:drawableTop="#android:drawable/ic_media_pause" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send my Location"
android:layout_alignBaseline="#+id/button6"
android:layout_alignBottom="#+id/button6"
android:layout_toRightOf="#+id/imageView1"
android:layout_toEndOf="#+id/imageView1" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/imageView"
android:layout_marginEnd="27dp"
android:layout_marginRight="27dp"
android:layout_marginTop="19dp"
android:text="resources" />
</RelativeLayout>
And (full) crash log:
04-10 20:33:31.533 941-941/com.example.android.vigilant E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.vigilant, PID: 941
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.vigilant/com.example.android.vigilant.HomeActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.android.vigilant.HomeActivity.onCreate(HomeActivity.java:134)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
How should I implement additional changes/ what changes specific to my code should be added and/or removed so that the button will continue to the next activity?
Check your code:
You have
setContentView(R.layout.activity_home);
You need to change this
setContentView(R.layout.activity_first);
You have
Button location_button = (Button) this.findViewById(R.id.button5);
You need to change this
Button location_button = (Button)findViewById(R.id.button5);
Check your xml code i think button id is not correct in java file
And make sure your activity is define in manifest
Problem in your xml code not your java code please match your all id's
Your requestPermission() is in buttonStart's onclick and your are trying to get location in oncreate() method , enable the permissions before asking for location
Where did you pass bundle when starting new activity.
Change this line
final ArrayList<String> contacts = getIntent().getStringArrayListExtra("CONTACTSLIST");
to this
ArrayList<String> contacts = new ArrayList<>();
if (getIntent()!=null && getIntent().hasExtra("CONTACTSLIST"))
contacts = getIntent().getStringArrayListExtra("CONTACTSLIST");
Also put some list when starting activity ,
which you want get in next activity.
let me know if this resolves issue.
I think in xml R.layout.activity_first you have not given id to the button or it is not 'more_button' post that xml and your query can be solved

How to fetch username from facebook for android studio

I have been trying to fetch username from facebook by learning from this stackoverflow link
I am a new developer ,I really couldn't find a solution please check the code I have been working on,I new beginner please help
Please do not give me links I have tried everthing already, I request you to edit the code to help
public class MainActivity extends AppCompatActivity {
private TextView mTextDetails;
private CallbackManager mCallbackManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
mCallbackManager=CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
//instantiate callbacks manager
mCallbackManager = CallbackManager.Factory.create();
}
private FacebookCallback <LoginResult> mcallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails = (TextView)findViewById(R.id.text_details);
mTextDetails.setText("Welcome "+ profile.getName());
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}}
Below is my XML file
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Welcome"
android:id="#+id/text_details"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_above="#+id/login_button"/>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
android:layout_centerInParent="true"/>
I want the user name to be displayed in Textview in in the place of android:id="#+id/text_details"
You can check this particular method called - UserinfoChangedCallback
https://developers.facebook.com/docs/reference/android/3.23.1/interface/LoginButton.UserInfoChangedCallback/
loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
} else {
userName.setText("You are not logged");
}
}
});
userName is the TextView that I have in my app. On successful login, user name is displayed.
The complete code is,
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
import com.natarajan.drapjabdulkalam.R;
public class ShareHelper extends Activity{
private LoginButton loginBtn;
//private Button postImageBtn;
private Button updateStatusBtn;
private TextView fbquote;
private TextView userName;
private UiLifecycleHelper uiHelper;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private String message;
//private static String message = "Sample status posted from android app";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
Intent intent = getIntent();
message = intent.getStringExtra("quote");
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.sharehelper_activity);
fbquote = (TextView)findViewById(R.id.FbTextView);
fbquote.setText(message);
userName = (TextView) findViewById(R.id.user_name);
loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
} else {
userName.setText("You are not logged");
}
}
});
/* postImageBtn = (Button) findViewById(R.id.post_image);
postImageBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
postImage();
}
});*/
updateStatusBtn = (Button) findViewById(R.id.update_status);
updateStatusBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
postStatusMessage();
}
});
buttonsEnabled(false);
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
buttonsEnabled(true);
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
buttonsEnabled(false);
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
public void buttonsEnabled(boolean isEnabled) {
// postImageBtn.setEnabled(isEnabled);
updateStatusBtn.setEnabled(isEnabled);
}
/* public void postImage() {
if (checkPermissions()) {
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), img, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(ShareHelper.this,
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
}
});
uploadRequest.executeAsync();
} else {
requestPermissions();
}
} */
public void postStatusMessage() {
if (checkPermissions()) {
Request request = Request.newStatusUpdateRequest(
Session.getActiveSession(), message,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
if (response.getError() == null)
Toast.makeText(ShareHelper.this,
"Quote Shared successfully",
Toast.LENGTH_LONG).show();
}
});
request.executeAsync();
} else {
requestPermissions();
}
}
public boolean checkPermissions() {
Session s = Session.getActiveSession();
if (s != null) {
return s.getPermissions().contains("publish_actions");
} else
return false;
}
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
buttonsEnabled(Session.getActiveSession().isOpened());
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
}
and the XML is,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_facebook"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:background="#drawable/bg1"
android:orientation="vertical"
android:padding="20dp" >
<com.facebook.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
android:background="#color/com_facebook_blue"
android:textStyle="bold"
facebook:fetch_user_info="true" />
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textStyle="bold"
android:textSize="18sp" />
<Button
android:id="#+id/update_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#color/com_facebook_loginview_text_color"
android:background="#color/com_facebook_blue"
android:text="#string/update_status" />
<TextView
android:id="#+id/FbTextView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#FFFFFF"
android:text="#string/welcometext"
android:textSize="20sp"
android:gravity="left|center"
android:textColor="#0B0A0A"
android:padding="10dp"
android:textStyle="bold"
/>
<!-- <Button
android:id="#+id/post_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/post_image" /> -->
</LinearLayout>

Categories

Resources