Passing parameters in firebase dynamic link not working - java

I am new to firebase. I was using an old version code where the parameters i put were atleast working for the url. but now when link is clicked, the browser opens and its a 400 error that requested url was not found. it works with only the dynamic link
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri BASE_URI = Uri.parse("http://example.com/");
Uri APP_URI = BASE_URI.buildUpon().
appendQueryParameter("extra1", "value").build();
String encodedUri = null;
try {
encodedUri = URLEncoder.encode(APP_URI.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.v("ENCODED URI: ", encodedUri);
Uri deepLink = Uri.parse("https://eh62u.app.goo.gl/y6N7/?link="+encodedUri);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, "");
intent.putExtra(Intent.EXTRA_SUBJECT, "GET TICKETS" );
intent.putExtra(Intent.EXTRA_TEXT, "Click here to get the booked tickets: " + deepLink);
startActivity(Intent.createChooser(intent, "Send Email"));
}
});
}
Main Activity OnCreate code:
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent())
.addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData data) {
if (data == null) {
Log.d("NULL DATA ", "getInvitation: no data");
return;
}
// Get the deep link
Uri deepLink = data.getLink();
String requestId2 = deepLink.getQueryParameter("extra1");
// Handle the deep link
// [START_EXCLUDE]
Log.d("DEEP LINK URL ", "deepLink:" + deepLink);
if (deepLink != null) {
if(requestId2 == "value") {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(intent);
}
}
// [END_EXCLUDE]
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("onFailure: ", "getDynamicLink:onFailure", e);
}
});
Android Manifest Code:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter> <action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="example.com"
android:scheme="https"/>
</intent-filter>
</activity>
<activity android:name=".Main2Activity">
</activity>
</application>
how do i put the parameter and then get it in the onSuccess? Thanks

The problem that i finally figured out by trial and error was the encoding part of the code. When i removed the :
encodedUri = URLEncoder.encode(APP_URI.toString(), "UTF-8");
part and just passed APP_URI to the deep link like
Uri deepLink = Uri.parse("https://eh62u.app.goo.gl/y6N7/?link="+APP_URI);
or even constructing the link using builder as:
Uri.Builder URLbuilder = new Uri.Builder()
.scheme("https")
.authority(Constants.DOMAIN)
.path("/")
.appendQueryParameter("link", getBaseUri(value))
.appendQueryParameter("apn", context.getPackageName());
It worked. No Problems. Retrieving the parameter was the usual.

Related

No auth token firebase storage android

I am sending images to firebase. but when my upload pictures method starts running, I get no auth token printed into my logcat couple of times. I tried using both camera and gallery, but they both make the same output even though my firebase storage rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my code is:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plantss = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plantss.setPlname(pname);
plantss.setPldate(pdate);
plantss.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plantss);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
System.out.println("IMAGE IS THIS MY MAN: "+ getimage.getString(0));
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
if (bm == null){
return;
}else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
System.out.println("FAILED:::: "+exception);
}
});
}
}
}
}
Mainfest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.varroxsystems.plant">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/plant"
android:label="#string/app_name"
android:roundIcon="#drawable/plant"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/AppTheme">
<activity android:name=".Donenewplant"></activity>
<activity android:name=".newPlant" />
<activity android:name=".MainActivity" />
<activity android:name=".Splash_screen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.varroxsystems.plant.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
So does anyone know a solution for that, or is it just a bug, because I use the same exact code in another app and it works just fine.
EDIT: The other app I use uses a different database, not the same one.

How to read multiple payload from nfc tags and store the payloads into an arraylist?

Hi Stackers I still new in coding and need some help. Now I have two NFC tags and both tags is storing with different Geo coordinates(longitude, latitude). Currently, I able to read the payload from the NFC tags. What I want is to store the payloads from both of the NFC tags into an arraylist. When I read the first tag it does stored the payload into arraylist, but when read second tag the payload will overwritten the previous payload.
Android Manifest:
<uses-permission android:name="android.permission.NFC" />
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".arraylist"></activity>
<activity
android:name=".MainActivity"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data
android:host="*"
android:scheme="geo" />
</intent-filter>
</activity>
</application>
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "nfc not supported", Toast.LENGTH_SHORT).show();
finish();
return;
}
if (!nfcAdapter.isEnabled()) {
startActivity(new Intent("android.settings.NFC_SETTINGS"));
Toast.makeText(this, "nfc not yet open", Toast.LENGTH_SHORT).show();
}
mPendingIntent = PendingIntent.getActivity(this,0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );
}
private void readIntent(Intent intent){
list = new ArrayList<>();
Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
for(int i=0; i<parcelables.length; i ++){
NdefMessage message =(NdefMessage)parcelables[i];
NdefRecord[] records = message.getRecords();
for(int j=0; j<records.length; j++){
NdefRecord record = records[j];
byte[] original = record.getPayload();
byte[] value = Arrays.copyOfRange(original,0,original.length);
String payload = new String(value);
if(list != null){
list.add(payload);
System.out.println(list);
}
}
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
readIntent(intent);
}
#Override
protected void onResume() {
super.onResume();
nfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
#Override
protected void onPause() {
super.onPause();
nfcAdapter.disableForegroundDispatch(this);
}
Here is my output:
I/System.out: [geo:1.523534,103.633690]
But my expectation output is:
[geo:1.523534, 103.633690, geo:1.5364496, 103.656321]
So how can achieve that second tag payload will not overwritten the previous payload?
The problem this time is that you are not creating a new instance of a Fragment like your were in your previous similar question, you are creating a new arraylist every time a card is read and thus de-referencing the first list object for it to be deleted by the garbage collection.
This is a classic variable initialisation issue.
readIntent is called every time a card is read.
So remove the first line of `readIntent where you create a new list.
e.g.
private void readIntent(Intent intent){
Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
....
Then in your class definition initialise the arraylist once only.
e.g.
public class MainActivity extends AppCompatActivity {
private ArrayList<String> list = new ArrayList();

Android.ConnectionService Incoming call UI not showing onShowIncomingCallUi

I am building basic calling app using TelecomManager, ConnectionService and Connection. But, When an there is an incoming call, my incomingActivity UI is not showing up. Below is the sample code so far.
In my MainActivity.java
Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, getPackageName());
startActivity(intent);
// ================================================================
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
// new ComponentName(getPackageName(), CallHandler.TAG), "myCallHandlerId");
PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(
new ComponentName(getApplicationContext(), CallHandler.TAG), "myCallHandlerId");
PhoneAccount phoneAccount = PhoneAccount
.builder(phoneAccountHandle, "myCallHandlerId")
.setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
.build();
manager.registerPhoneAccount(phoneAccount);
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle));
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle).isEnabled());
Log.i("Phone Account", "" + manager.getPhoneAccount(phoneAccountHandle).getClass());
Log.i("Phone Account isEnabled", "" + phoneAccount.isEnabled());
Bundle bundle = new Bundle();
Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, "555555555", null);
bundle.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS, uri);
bundle.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle);
// manager.addNewIncomingCall(phoneAccountHandle, bundle);
Log.i("Permitted", "" + manager.isIncomingCallPermitted(phoneAccountHandle));
if(manager.isIncomingCallPermitted(phoneAccountHandle)){
Log.i("Call", "Incoming");
manager.addNewIncomingCall(phoneAccountHandle, bundle);
}
}
In my CallHandler.java
#RequiresApi(api = Build.VERSION_CODES.M)
public class CallHandler extends ConnectionService{
public static final String TAG = CallHandler.class.getName();
#RequiresApi(api = Build.VERSION_CODES.N_MR1)
#Override
public Connection onCreateIncomingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i("CallHandler","onCreateIncomingConnection");
// return super.onCreateIncomingConnection(connectionManagerPhoneAccount, request);
Context context = getApplicationContext();
Log.i("Context","" + context);
Log.i("Context","" + context.getPackageName());
Log.i("Context","" + getBaseContext());
Log.i("Context","" + context.getClass().getName());
Log.i("Context","" + context.getClass().getSimpleName());
CallConnection callConnection = new CallConnection(context);
callConnection.setInitializing();
callConnection.setActive();
callConnection.setCallerDisplayName("Manik", TelecomManager.PRESENTATION_ALLOWED);
// callConnection.setConnectionProperties(Connection.PROPERTY_SELF_MANAGED);
// callConnection.setConnectionCapabilities(Connection.CAPABILITY_HOLD & Connection.CAPABILITY_SUPPORT_HOLD);
return callConnection;
}
#Override
public void onCreateIncomingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
super.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public void onCreateOutgoingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
return super.onCreateOutgoingConnection(connectionManagerPhoneAccount, request);
}
}
In my CallConnection.java
#RequiresApi(api = Build.VERSION_CODES.M)
public class CallConnection extends Connection {
private Context context;
#RequiresApi(api = Build.VERSION_CODES.N_MR1)
public CallConnection(Context con) {
context = con;
setConnectionProperties(PROPERTY_SELF_MANAGED);
setAudioModeIsVoip(true);
}
#Override
public void onAnswer(int videoState) {
super.onAnswer(videoState);
Log.i("Call","Answered");
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onShowIncomingCallUi() {
Log.i("Call","Incoming Call");
super.onShowIncomingCallUi();
// MainActivity con = new MainActivity();
// Context context = con.getApplicationContext();
NotificationChannel channel = new NotificationChannel("channel", "Incoming Calls",
NotificationManager.IMPORTANCE_HIGH);
channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
// other channel setup stuff goes here.
// We'll use the default system ringtone for our incoming call notification channel. You can
// use your own audio resource here.
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
channel.setSound(ringtoneUri, new AudioAttributes.Builder()
// Setting the AudioAttributes is important as it identifies the purpose of your
// notification sound.
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
// NotificationManager mgr = context.getSystemService(NotificationManager.class);
// mgr.createNotificationChannel(channel);
// Create an intent which triggers your fullscreen incoming call user interface.
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(context, IncomingCallScreenActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, 0);
Log.i("Intent1","" + intent);
Log.i("Intent2","" + intent.getPackage());
Log.i("Intent3","" + intent.getType());
Log.i("Intent4","" + intent.getData());
Log.i("Intent5","" + intent.getDataString());
Log.i("Intent6","" + intent.getAction());
Log.i("Intent7","" + intent.getCategories());
Log.i("Intent8","" + intent.getExtras());
Log.i("Pending Intent","" + pendingIntent);
Log.i("Pending Intent","" + pendingIntent.getCreatorPackage());
// Build the notification as an ongoing high priority item; this ensures it will show as
// a heads up notification which slides down over top of the current content.
final Notification.Builder builder = new Notification.Builder(context);
builder.setOngoing(true);
builder.setPriority(Notification.PRIORITY_HIGH);
// Set notification content intent to take user to fullscreen UI if user taps on the
// notification body.
builder.setContentIntent(pendingIntent);
// Set full screen intent to trigger display of the fullscreen UI when the notification
// manager deems it appropriate.
builder.setFullScreenIntent(pendingIntent, true);
// Setup notification content.
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Your notification title");
builder.setContentText("Your notification content.");
// Set notification as insistent to cause your ringtone to loop.
Notification notification = builder.build();
notification.flags |= Notification.FLAG_INSISTENT;
// Use builder.addAction(..) to add buttons to answer or reject the call.
NotificationManager notificationManager = context.getSystemService(
NotificationManager.class);
notificationManager.notify("Call Notification", 37, notification);
// context.startActivity(intent);
}
}
All the log messages inside onCreateIncomingConnection() and onShowIncomingCallUi() are showing up when the app launches, and not when there is an incoming call.
All the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />
<!--
Needed only if your calling app reads numbers from the `PHONE_STATE`
intent action.
-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".IncomingCallScreenActivity"></activity>
<activity android:name=".CallScreenActivity" />
<activity android:name=".ContactsActivity" />
<activity android:name=".LogsActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="tel" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.DIAL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".CallHandler"
android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.ConnectionService" />
</intent-filter>
</service>
</application>
Any help would be appreciated. Thanks

App login using Facebook is not working in development! It just loading and Closed- Android Studio

I have implemented an app and I have used facebook login to it. Application is running without crashing but facebook login is not working. When I open up the app and click the facebook login button it will show a progress bar and it will be disappeared immediately without doing anything. I have got the following error in the logcat.
2019-08-29 12:45:24.290 19304-19328/com.appic.testfbauth
E/GraphResponse:
{
HttpStatus: 400,
errorCode: 100,
subErrorCode: 33,
errorType: GraphMethodException,
errorMessage: Unsupported get request. Object with ID '742177629556035' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api
}
refer below for work I have done.
public class MainActivity extends AppCompatActivity {
private LoginButton loginButton;
private CircleImageView circleImageView;
private TextView txtName, txtEmail;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
loginButton = findViewById(R.id.login_button);
circleImageView = findViewById(R.id.profile_pic);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
checkLoginStatus();
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null) {
txtEmail.setText("");
txtName.setText("");
circleImageView.setImageResource(0);
Toast.makeText(MainActivity.this, "User Logged Out!", Toast.LENGTH_SHORT).show();
}
else loadUser(currentAccessToken);
}
};
private void loadUser(AccessToken newAccessToken) {
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+ id +"/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+ last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(MainActivity.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,last_name,email,id");
request.setParameters(parameters);
request.executeAsync();
}
private void checkLoginStatus() {
if(AccessToken.getCurrentAccessToken() != null) {
loadUser(AccessToken.getCurrentAccessToken());
}
}
}
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ApplicationName"
android:value="#string/app_name"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
I just want to integrate the facebook login and get email, name, image url, id.
I have no enough replication for comment so i paste answer. You just give me answers to my below questions.
You test your app in real device or emulator.?
Get the permission for image?
Please check your browser any facebook account already login there?
If you not getting email and name please try below code:
JSONObject res;
res = new JSONObject(json_object.toString());
String id = res.getString("id");
String name = res.getString("name");
String email = res.getString("email");
Update:
Please Uninstalled FB app from your device and try to login with FB in your app it's working fine.
Update 25/11/209
Also please update your hash key - Please follow this answer
After that convert hash key into base 64 - tomeko.net

How to open a PDF file from in-app browser?

I have a basic File Browser inside my app and I want it to be able to open PDF files, but for some reason, even though I can tap on the PDF files and they open for a second, they go away and my phone gives a Toast message with an error, and this Toast I haven't programmed anywhere in my code. This is weird because the same PDF file opens from my other activities without any issues. (See the OpenPDF() Method which works from my PDFManager class) I researched a lot about how to fix this but couldn't find a clear answer. Thanks for helping!
The toast error: Cannot display PDF (filename.pdf cannot be opened)
OnListItemClick function from AndroidFileBrowser:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String filename = (String) getListAdapter().getItem(position);
if (path.endsWith(File.separator)) {
filename = path + filename;
} else {
filename = path + File.separator + filename;
}
pdf = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/PATH/" + filename);
Uri path = Uri.fromFile(pdf);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.faraz.pdfreader"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".SimpleScannerActivity"
android:label="#string/simple_scanner_activity"
android:theme="#style/AppOverlayTheme">
</activity>
<activity android:name=".PDFManager"/>
<activity android:name=".AndroidFileBrowser"/>
<!--android:screenOrientation="portrait"-->
</application>
</manifest>
OpenPDF() method from my PDFManager class
public void openPDF() {
File pdf = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/PATH/" + pdfname + ".pdf");
if (pdf.exists()) {
Uri path = Uri.fromFile(pdf);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(PDFManager.this,
"No application available to view PDF!",
Toast.LENGTH_SHORT).show();
/* Intent intent = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("http://docs.google.com/gview?embedded=true&url=" + url));
startActivity(intent);
}
*/
}
}
}
}
In your OnItemClick():
if (path.endsWith(File.separator))
{
filename = path + filename;
}
else
{
filename = path + File.separator + filename;
}
pdf = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/PATH/" + filename);
Uri path = Uri.fromFile(pdf);
You use "path" before you initialize it, so depending on your intentions either change the name of one or the other, or declare it before your if-statement not after.

Categories

Resources