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>
Related
When submitting to Firebase, only photos are sent, without text and database as such.
I do according to the guide, but I don’t understand what is the reason.
The guide probably uses the deprecated getDownloadUrl() method, but the photo does not suffer from this. I do not understand the reason for this, since I am still new in this area, please help, I no longer understand what to do. To understand something, look at Maineenter image description here
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowUploads;
private EditText mEditTextFileName;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_im);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_LONG).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, 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());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
}
Класс Upload
public class Upload {
private String mName;
private String mImageUrl;
public Upload(){
}
public Upload(String name, String imageUrl) {
this.mName = name;
this.mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = mName;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
this.mImageUrl = mImageUrl;
}
}
activity_main
<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:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="#+id/button_choose_im"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose" />
<EditText
android:id="#+id/edit_text_file_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/button_choose_im"
android:hint="Enter"
android:minHeight="48dp" />
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/progress_bar"
android:layout_below="#id/edit_text_file_name"
android:layout_marginTop="16dp" />
<ProgressBar
android:id="#+id/progress_bar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_upload"
android:layout_alignParentStart="true"
android:layout_marginBottom="16dp" />
<Button
android:id="#+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:text="Upload" />
<TextView
android:id="#+id/text_view_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button_upload"
android:layout_alignBottom="#+id/button_upload"
android:layout_marginStart="25dp"
android:layout_toEndOf="#+id/button_upload"
android:gravity="center"
android:text="Show"
android:textSize="16sp" />
</RelativeLayout>
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>
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
Login Activity
Please Help I just wanted to Remember Login in App in background, so that when he reopen the app automatically next activity open rather than sign in activity.
package xxx.xxxxx.xxxxxx;
/**
* Created by Yoyo on 12/21/2015.
*/
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
public class Login extends AppCompatActivity implements OnConnectionFailedListener, View.OnClickListener, ConnectionCallbacks {
GoogleApiClient mGoogleApiClient;
GoogleSignInOptions gso;
SignInButton signIn_btn;
private static final int RC_SIGN_IN = 0;
ProgressDialog progress_dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buidNewGoogleApiClient();
setContentView(R.layout.login);
customizeSignBtn();
setBtnClickListeners();
progress_dialog = new ProgressDialog(this);
progress_dialog.setMessage("Signing in....");
}
/*
Configure sign-in to request the user's ID, email address, and basic profile.
User's ID and basic profile are included in DEFAULT_SIGN_IN.
create and initialize GoogleApiClient object to use Google Sign-In API and the options specified by gso..
*/
private void buidNewGoogleApiClient(){
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this )
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
/*
Customize sign-in button. The sign-in button can be displayed in
multiple sizes and color schemes. It can also be contextually
rendered based on the requested scopes. For example. a red button may
be displayed when Google+ scopes are requested, but a white button
may be displayed when only basic profile is requested. Try adding the
Plus.SCOPE_PLUS_LOGIN scope to see the difference.
*/
private void customizeSignBtn(){
signIn_btn = (SignInButton) findViewById(R.id.sign_in_button);
signIn_btn.setSize(SignInButton.SIZE_STANDARD);
signIn_btn.setScopes(gso.getScopeArray());
}
/*
Set on click Listeners on the sign-in sign-out and disconnect buttons
*/
private void setBtnClickListeners(){
// Button listeners
signIn_btn.setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
findViewById(R.id.disconnect_button).setOnClickListener(this);
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
progress_dialog.dismiss();
}
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
getSignInResult(result);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
Toast.makeText(this, "start sign process", Toast.LENGTH_SHORT).show();
gSignIn();
break;
case R.id.sign_out_button:
Toast.makeText(this, "Google Sign Out", Toast.LENGTH_SHORT).show();
gSignOut();
break;
case R.id.disconnect_button:
Toast.makeText(this, "Google Access Revoked", Toast.LENGTH_SHORT).show();
gRevokeAccess();
break;
}
}
private void gSignIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
progress_dialog.show();
}
private void gSignOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void gRevokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void getSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
TextView user_name= (TextView)findViewById(R.id.userName);
TextView email_id= (TextView)findViewById(R.id.emailId);
user_name.setText("UserName: "+ acct.getDisplayName());
email_id.setText("Email Id: " + acct.getEmail());
updateUI(true);
SharedPreferences sharedPreferences = getSharedPreferences("APP", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLogin", true);
editor.putString("name", //Name),
editor.putString("e_mail",
editor.putString("ID", //ID);
editor.commit());
progress_dialog.dismiss();
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
private void updateUI(boolean signedIn) {
if (signedIn) {
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Login xml file for the Activity login xml
<?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:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="num.app.xxx.xxxx.xxxx.Login"
tools:showIn="#layout/Login">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone"
tools:visibility="visible"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true">
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" user name:"
android:layout_marginTop="15dp"
android:layout_marginLeft="10dp"
android:textColor="#android:color/black"
android:textSize="14sp"
/>
<TextView
android:id="#+id/emailId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email id:"
android:textColor="#android:color/black"
android:layout_below="#+id/userName"
android:layout_marginTop="15dp"
android:layout_marginLeft="10dp"
android:textSize="14sp"
/>
<Button
android:id="#+id/sign_out_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Google Sign out"/>
<Button
android:id="#+id/disconnect_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="revoke Google Access"/>
</LinearLayout>
</RelativeLayout>
//Splash activity before the above activity
Thread timer = new Thread(){
public void run(){
try{
sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openStartingPoint = new Intent("android.intent.action.Login");
startActivity(openStartingPoint);
finish();
}
}
};
timer.start();
I would avoid saving the token in the shared preferences and rather try to perform a Silent Sign In as described here: http://android-developers.blogspot.de/2015/12/api-updates-for-sign-in-with-google.html
This has the advantage to let you verify if the user is still logged in and eventually let you prompt him to request to re-login.
here some code (basically adapted from the example in the link):
public void silentLogin() {
OptionalPendingResult<GoogleSignInResult> pendingResult = Auth.GoogleSignInApi.silentSignIn(googleApiClient);
if (pendingResult != null) {
handleGooglePendingResult(pendingResult);
} else {
//no result from silent login. Possibly display the login page again
}
}
private void handleGooglePendingResult(OptionalPendingResult<GoogleSignInResult> pendingResult) {
if (pendingResult.isDone()) {
// There's immediate result available.
GoogleSignInResult signInResult = pendingResult.get();
onSilentSignInCompleted(signInResult);
} else {
// There's no immediate result ready, waits for the async callback.
pendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult signInResult) {
onSilentSignInCompleted(signInResult, callback);
}
});
}
}
private void onSilentSignInCompleted(GoogleSignInResult signInResult) {
GoogleSignInAccount signInAccount = signInResult.getSignInAccount();
if (signInAccount != null) {
// you have a valid sign in account. Skip the login.
} else {
// you don't have a valid sign in account. Eventually display the login page again
}
}
You can try this:
After user login success then you can save id token to SharedPreferences by call method getIdToken() of GoogleSignInAccount. And when user reopen you can check id token is exiting then ignore login screen.
private void getSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
String id_token = acct.getIdToken(); //add this code here to save it by use SharedPreferences
TextView user_name= (TextView)findViewById(R.id.userName);
TextView email_id= (TextView)findViewById(R.id.emailId);
user_name.setText("UserName: "+ acct.getDisplayName());
email_id.setText("Email Id: " + acct.getEmail());
updateUI(true);
progress_dialog.dismiss();
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
//save user login state id_token
private void saveLoginState(String id_token){
SharedPreferences sharedpreferences = getSharedPreferences("YOUR_PREFERENCE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("GG_LOGED", id_token);
editor.commit();
}
After the user login you can use this code to store the data in SharedPreference
SharedPreferences sharedPreferences = getSharedPreferences("APP", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLogin", true);
editor.putString("name", //Name);
editor.putString("e_mail",//Email);
editor.putString("ID", //ID);
editor.commit();
And in the splash screen you can do like this
boolean isLoggedIn = sharedPreferences.getBoolean("isLogin", false);
Here isLoggedIn is the value whether the user is logged in or not status. You need to handle this in SplashScreen and proceed according to that.
After searching in life cycle I have found that my application needs to use the destroy(); method. However, when I implement this the application doesn't close. I am trying to apply this to the button exitButton. If someone could direct me in the right direction then that would be great.
MainActivity.java
package com.webcraftbd.radio;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
static String radioTitle = "Android Live Radio";
static String radioStreamURL = "http://stream.infowars.com:80";
Button playButton;
Button pauseButton;
Button stopButton;
Button exitbutton;
TextView statusTextView, bufferValueTextView;
NotificationCompat.Builder notifyBuilder;
private RadioUpdateReceiver radioUpdateReceiver;
private RadioService radioServiceBinder;
//Notification
private static final int NOTIFY_ME_ID=12345;
private NotificationManager notifyMgr=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView titleTextView = (TextView) this.findViewById(R.id.titleTextView);
titleTextView.setText(radioTitle);
playButton = (Button) this.findViewById(R.id.PlayButton);
pauseButton = (Button) this.findViewById(R.id.PauseButton);
stopButton = (Button) this.findViewById(R.id.StopButton);
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
pauseButton.setVisibility(View.INVISIBLE);
statusTextView = (TextView) this.findViewById(R.id.StatusDisplayTextView);
notifyMgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
// Bind to the service
Intent bindIntent = new Intent(this, RadioService.class);
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
startService(new Intent(this, RadioService.class));
}
public void onClickPlayButton(View view) {
radioServiceBinder.play();
}
public void onClickPauseButton(View view) {
radioServiceBinder.pause();
}
public void onClickStopButton(View view) {
radioServiceBinder.stop();
}
public void onClicexitbutton(View view) {
super.finish();
super.onDestroy();
radioServiceBinder.onDestroy();
radioServiceBinder.stop();
radioServiceBinder.stopService(getParentActivityIntent());
}
#Override
protected void onPause() {
super.onPause();
if (radioUpdateReceiver != null)
unregisterReceiver(radioUpdateReceiver);
}
#Override
protected void onResume() {
super.onResume();
/* Register for receiving broadcast messages */
if (radioUpdateReceiver == null) radioUpdateReceiver = new RadioUpdateReceiver();
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_CREATED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_DESTROYED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_STARTED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PREPARED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PLAYING));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PAUSED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_STOPPED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_COMPLETED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_ERROR));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_BUFFERING_START));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_BUFFERING_END));
}
protected void onDestroy(){
super.onDestroy();
}
/* Receive Broadcast Messages from RadioService */
private class RadioUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RadioService.MODE_CREATED)) {
showNotification();
}
else if (intent.getAction().equals(RadioService.MODE_DESTROYED)) {
clearNotification();
}
else if (intent.getAction().equals(RadioService.MODE_STARTED)) {
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Buffering...");
}
else if (intent.getAction().equals(RadioService.MODE_PREPARED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Rady");
}
else if (intent.getAction().equals(RadioService.MODE_BUFFERING_START)) {
updateStatus("Buffering...");
}
else if (intent.getAction().equals(RadioService.MODE_BUFFERING_END)) {
updateStatus("Playing");
}
else if (intent.getAction().equals(RadioService.MODE_PLAYING)) {
playButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
playButton.setVisibility(View.INVISIBLE);
pauseButton.setVisibility(View.VISIBLE);
showNotification();
updateStatus("Playing");
}
else if(intent.getAction().equals(RadioService.MODE_PAUSED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Paused");
}
else if(intent.getAction().equals(RadioService.MODE_STOPPED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Stopped");
clearNotification();
}
else if(intent.getAction().equals(RadioService.MODE_COMPLETED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Stopped");
}
else if(intent.getAction().equals(RadioService.MODE_ERROR)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus("Error");
}
}
}
public void updateStatus(String status) {
try {
if(notifyBuilder!=null && notifyMgr!=null) {
notifyBuilder.setContentText(status).setWhen(0);
notifyMgr.notify(NOTIFY_ME_ID,notifyBuilder.build());
}
statusTextView.setText(status);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void showNotification() {
notifyBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(radioTitle).setContentText("");
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notifyBuilder.setContentIntent(resultPendingIntent);
notifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyMgr.notify(NOTIFY_ME_ID, notifyBuilder.build());
}
public void clearNotification() {
notifyMgr.cancel(NOTIFY_ME_ID);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
// Handles the connection between the service and activity
private ServiceConnection radioConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
radioServiceBinder = ((RadioService.RadioBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
radioServiceBinder = null;
}
};
}
enter code here
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4a4a4a"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/player_header_bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:gravity="center"
android:text="Classic Christmas Radio"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#c0413b"
android:textSize="40sp" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:layout_marginBottom="120dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="110dp"
android:src="#drawable/cover" />
<TextView
android:id="#+id/StatusDisplayTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/PauseButton"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignRight="#+id/imageView1"
android:gravity="center"
android:text="Unknown" />
<Button
android:id="#+id/PauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/StatusDisplayTextView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0.0dip"
android:background="#drawable/btn_pause"
android:onClick="onClickPauseButton" />
<Button
android:id="#+id/PlayButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/StatusDisplayTextView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="0.0dip"
android:background="#drawable/btn_play"
android:onClick="onClickPlayButton" />
<Button
android:id="#+id/StopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#id/StatusDisplayTextView"
android:layout_marginBottom="0.0dip"
android:background="#drawable/btn_stop"
android:onClick="onClickStopButton" />
<Button
android:id="#+id/exitbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/StatusDisplayTextView"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
RadioService.java
package com.webcraftbd.radio;
import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class RadioService extends Service implements OnErrorListener, OnCompletionListener, OnPreparedListener, OnInfoListener {
private MediaPlayer mediaPlayer;
private String radioStreamURL = MainActivity.radioStreamURL;
public static final String MODE_CREATED = "CREATED";
public static final String MODE_DESTROYED = "DESTROYED";
public static final String MODE_PREPARED = "PREPARED";
public static final String MODE_STARTED = "STARTED";
public static final String MODE_PLAYING = "PLAYING";
public static final String MODE_PAUSED = "PAUSED";
public static final String MODE_STOPPED = "STOPPED";
public static final String MODE_COMPLETED = "COMPLETED";
public static final String MODE_ERROR = "ERROR";
public static final String MODE_BUFFERING_START = "BUFFERING_START";
public static final String MODE_BUFFERING_END = "BUFFERING_END";
private boolean isPrepared = false;
private final IBinder binder = new RadioBinder();
#Override
public void onCreate() {
/* Create MediaPlayer when it starts for first time */
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnInfoListener(this);
sendBroadcast(new Intent(MODE_CREATED));
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.reset();
isPrepared = false;
sendBroadcast(new Intent(MODE_DESTROYED));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sendBroadcast(new Intent(MODE_STARTED));
/* Starts playback at first time or resumes if it is restarted */
if(mediaPlayer.isPlaying())
sendBroadcast(new Intent(MODE_PLAYING));
else if(isPrepared) {
sendBroadcast(new Intent(MODE_PAUSED));
}
else
prepare();
return Service.START_STICKY;
}
#Override
public void onPrepared(MediaPlayer _mediaPlayer) {
/* If radio is prepared then start playback */
sendBroadcast(new Intent(MODE_PREPARED));
isPrepared = true;
play();
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
/* When no stream found then complete the playback */
mediaPlayer.stop();
mediaPlayer.reset();
isPrepared = false;
sendBroadcast(new Intent(MODE_COMPLETED));
}
public void prepare() {
/* Prepare Async Task - starts buffering */
try {
mediaPlayer.setDataSource(radioStreamURL);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void play() {
if(isPrepared) {
mediaPlayer.start();
System.out.println("RadioService: play");
sendBroadcast(new Intent(MODE_PLAYING));
}
else
{
sendBroadcast(new Intent(MODE_STARTED));
prepare();
}
}
public void pause() {
mediaPlayer.pause();
System.out.println("RadioService: pause");
sendBroadcast(new Intent(MODE_PAUSED));
}
public void stop() {
mediaPlayer.stop();
mediaPlayer.reset();
isPrepared = false;
System.out.println("RadioService: stop");
sendBroadcast(new Intent(MODE_STOPPED));
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
/* Check when buffering is started or ended */
if(what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
sendBroadcast(new Intent(MODE_BUFFERING_START));
}
else if(what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
sendBroadcast(new Intent(MODE_BUFFERING_END));
}
return false;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
sendBroadcast(new Intent(MODE_ERROR));
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.v("ERROR","MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.v("ERROR","MEDIA ERROR SERVER DIED " + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.v("ERROR","MEDIA ERROR UNKNOWN " + extra);
break;
}
return false;
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
/* Allowing activity to access all methods of RadioService */
public class RadioBinder extends Binder {
RadioService getService() {
return RadioService.this;
}
}
}
Ok, after developing some pseudo and some logic, I have noticed that Andorid doesn't have an exit method in the way that you're hoping. When first reading the question I didn't realise that it was Android as I was multi-tasking. As you may notice, almost every android application doesn't have an exit button, and there is a reason for this. The reason being that Android is supposedly meant to load and unload applications through the OS, hence why you don't do it. If the user wanted to exit the application, they would do what they do with every other, enter the multi-tasking menu and swipe it off. Please read the following for more information: http://android.nextapp.com/site/fx/doc/exit