I have a class which extends ListFragment. MyloginToFacebook()method (see below) works. But once I want to logout and call logoutFromFacebook(), I receive the following error:
{"error_code":101,"error_msg":"Invalid application ID.","request_args":[{"key":"method","value":"auth.expireSession"},{"key":"format","value":"json"}]}
Here are my methods:
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
//---------------------------//
public void logoutFromFacebook() {
mAsyncRunner.logout(getActivity(), new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
btnLogout.setVisibility(View.INVISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
I just wonder if the cause of the problem is extends ListFragment, because when I tried with extends Activity, it runs well.
Would someone out there help me out to solve this problem? any helps would be appreciated.
Thank you
Related
I have an admob ad of the "open ad" type.
Which works when the application is started, and unfortunately the application is often rejected because the advertisement is seen before the content of the application ....
So I put Splash_Activity to appear a little and then the ad appears, the method is effective and the application is accepted.
Problem: When the time I set for Splash_Activity expires, the ad disappears with it without the need to press continue for the application, and in this case the ad remains in the background of the application.
Required: The Splash_Activity screen stops when the ad appears and does not disappear unless you close the ad.
AppOpenManager:
public class AppOpenManager implements LifecycleObserver, Application.ActivityLifecycleCallbacks {
private static final String LOG_TAG = "AppOpenManager";
private static final String AD_UNIT_ID = "ca-app-pub-****/****";
private AppOpenAd appOpenAd = null;
private long loadTime = 0;
private AppOpenAd.AppOpenAdLoadCallback loadCallback;
private Activity currentActivity;
private static boolean isShowingAd = false;
private final GlobalVar Splash_Activity;
/**
* Constructor
*/
public AppOpenManager(GlobalVar splash_Activity) {
this.Splash_Activity = splash_Activity;
this.Splash_Activity.registerActivityLifecycleCallbacks(this);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
/** LifecycleObserver methods */
#OnLifecycleEvent(ON_START)
public void onStart() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showAdIfAvailable();
}
}, 1500);
Log.d(LOG_TAG, "onStart");
}
/** Shows the ad if one isn't already showing. */
public void showAdIfAvailable() {
// Only show ad if there is not already an app open ad currently showing
// and an ad is available.
if (!isShowingAd && isAdAvailable()) {
Log.d(LOG_TAG, "Will show ad.");
FullScreenContentCallback fullScreenContentCallback =
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
AppOpenManager.this.appOpenAd = null;
isShowingAd = false;
fetchAd();
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {}
#Override
public void onAdShowedFullScreenContent() {
isShowingAd = true;
}
};
appOpenAd.setFullScreenContentCallback(fullScreenContentCallback);
appOpenAd.show(currentActivity);
} else {
Log.d(LOG_TAG, "Can not show ad.");
fetchAd();
}
}
/**
* Request an ad
*/
public void fetchAd() {
// Have unused ad, no need to fetch another.
if (isAdAvailable()) {
return;
}
loadCallback =
new AppOpenAd.AppOpenAdLoadCallback() {
/**
* Called when an app open ad has loaded.
*
* #param ad the loaded app open ad.
*/
#Override
public void onAdLoaded(AppOpenAd ad) {
AppOpenManager.this.appOpenAd = ad;
AppOpenManager.this.loadTime = (new Date()).getTime();
}
/**
* Called when an app open ad has failed to load.
*
* #param loadAdError the error.
*/
#Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Handle the error.
}
};
AdRequest request = getAdRequest();
AppOpenAd.load(
Splash_Activity, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback);
}
// We will implement this below.
/**
* Creates and returns ad request.
*/
private AdRequest getAdRequest() {
return new AdRequest.Builder().build();
}
/**
* Utility method that checks if ad exists and can be shown.
*/
public boolean isAdAvailable() {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4);
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
currentActivity = activity;
}
#Override
public void onActivityResumed(Activity activity) {
currentActivity = activity;
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
#Override
public void onActivityDestroyed(Activity activity) {
currentActivity = null;
}
/** Utility method to check if ad was loaded more than n hours ago. */
private boolean wasLoadTimeLessThanNHoursAgo(long numHours) {
long dateDifference = (new Date()).getTime() - this.loadTime;
long numMilliSecondsPerHour = 3600000;
return (dateDifference < (numMilliSecondsPerHour * numHours));
}
}
Splash_Activity
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (go) {
startActivity(new Intent(Splash_Activity.this, home_main.class));
finish();
}
}
}, 4200);
}
First, you need to create a callback listener to know when the ad has been dismissed, and stop further code execution until then.
public interface AdListener {
void onCompleted();
}
Change the code of showAdIfAvailable like below with a parameter of listener.
public void showAdIfAvailable(#NonNull AdListener listener) {
// Only show ad if there is not already an app open ad currently showing
// and an ad is available.
if (!isShowingAd && isAdAvailable()) {
Log.d(LOG_TAG, "Will show ad.");
appOpenAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable()
this.appOpenAd = null;
isShowingAd = false;
fetchAd();
// Inform caller that we have done
listener.onCompleted();
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
appOpenAd = null;
// Inform caller that we have done
listener.onCompleted();
}
#Override
public void onAdShowedFullScreenContent() {
isShowingAd = true;
}
});
appOpenAd.show(currentActivity);
} else {
Log.d(LOG_TAG, "Can not show ad.");
// Inform caller that we have done
listener.onCompleted();
// Load new ad
fetchAd();
}
}
Call to show app onen ad like below from SplashActivity:
showAdIfAvailable(SplashActivity.this, new AdListener() {
#Override
public void onCompleted() {
// Start your activity from here
}
});
However, this is a demonstration of the process. Change it as you want to use it.
Hope it will help.
I want setOnUtteranceProgressListener should notify a Toast after the speech is completed.It seems not working.
I have used setOnUtteranceProgressListener and on the speak function i have mentioned the paramaters as follows..
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, MainActivity.this.getPackageName());
I have given a "UniqueId" while calling speak function as follows.
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,params,"UniqueId");
In My program after the text to speech engine finishes speaking it should run a Toast notifying that it has finished speaking.But the setOnUtteranceProgressListner seems not working.
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
Toast.makeText(MainActivity.this,"Finished speaking.",Toast.LENGTH_LONG).show();
}
#Override
public void onError(String utteranceId) {
}
});
The all Code is as follows..
public class MainActivity extends AppCompatActivity {
String message;
private TextToSpeech myTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(myTTS.getEngines().size() == 0){
Toast.makeText(MainActivity.this,"No Engines Installed",Toast.LENGTH_LONG).show();
}else{
myTTS.setLanguage(Locale.US);
if (status == TextToSpeech.SUCCESS){
//Toast.makeText(MainActivity.this,"Status working.",Toast.LENGTH_LONG).show();
message = "How may i help you.";
}
}
}
});
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
Toast.makeText(MainActivity.this,"onDone working.",Toast.LENGTH_LONG).show();
}
#Override
public void onError(String utteranceId) {
}
});
}
Please give a solution for this.
The main problems are:
1) Setting the progress listener before the tts is initialized.
2) Trying to make a Toast from a background thread.
I also have some other suggested changes but they are not required:
public class MainActivity extends AppCompatActivity {
String message = "How may I help you?";
String mostRecentUtteranceID;
private TextToSpeech myTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(myTTS.getEngines().size() == 0){
Toast.makeText(MainActivity.this,"No Engines Installed",Toast.LENGTH_LONG).show();
}else{
if (status == TextToSpeech.SUCCESS){
ttsInitialized();
}
}
}
});
}
private void ttsInitialized() {
// *** set UtteranceProgressListener AFTER tts is initialized ***
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
// this method will always called from a background thread.
public void onDone(String utteranceId) {
// only respond to the most recent utterance
if (!utteranceId.equals(mostRecentUtteranceID)) {
Log.i("XXX", "onDone() blocked: utterance ID mismatch.");
return;
} // else continue...
boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
Log.i("XXX", "was onDone() called on a background thread? : " + wasCalledFromBackgroundThread);
Log.i("XXX", "onDone working.");
// for demonstration only... avoid references to
// MainActivity (unless you use a WeakReference)
// inside the onDone() method, as it
// can cause a memory leak.
runOnUiThread(new Runnable() {
#Override
public void run() {
// *** toast will not work if called from a background thread ***
Toast.makeText(MainActivity.this,"onDone working.",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
// set Language
myTTS.setLanguage(Locale.US);
// set unique utterance ID for each utterance
mostRecentUtteranceID = (new Random().nextInt() % 9999999) + ""; // "" is String force
// set params
// *** this method will work for more devices: API 19+ ***
HashMap<String, String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mostRecentUtteranceID);
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH,params);
}
}
If you want to add the call back OnUtteranceProgressListener you have to implement the speak method like this:
myTTS.speak(message,TextToSpeech.QUEUE_FLUSH, null , TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID);
Then it will call the methods that you've already implemented (onStart, onDone, etc)
I have made an app in that I want to share an image and a text ,I have successfully get the login Dialog of facebook..But after Login it gives me error that Warning: Sessionless Request needs token but missing either application ID or client token.
What should i do to solve it.My code is as below ,Please help needed..
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
Session session = facebook.getSession();
if (access_token != null) {
SessionState st = SessionState.OPENED;
facebook.setAccessToken(access_token);
Exception e = new FacebookError("Error");
System.out.println("::::::::::::::aCEESS TOKEN::::::::;;"
+ access_token);
postToWall();
/*fbImageSubmit(facebook, big_img, "3sMAniquines", "Maniquines",
cat_nem, big_img);*/
onSessionStateChange(session, st, e);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (facebook.isSessionValid()) {
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
* */
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
You have to save the access token of logged user for maintaining Session for further task.
according to your code following code will give you currently logged in user's access token.
String access_token = Const.fb.getAccessToken();
READ THIS : I want to like this.... if user have input name and choose game types. user can click 'OK' button. if user haven't input name and choose game types he can't click 'OK' button.
I create thread to solve this problem...
But when I run this app. I can't go to this UI again..
Something wrong in method 'autoValidation'
And code userConfigOK.setClickable(false); doesn't work. I don't know why..
btw, android is hard. . . .
This is the source code :
public class UserConfig extends Activity {
private String gameType;
private String gameTime;
private String playerName;
private int IDChar = 0;
Thread validation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_config);
userConfigOK.setClickable(false);
inputName();
chooseCharacter();
setGameType();
back();
autoValidation();
OK();
}
public void inputName() {
playerName = userNameTextbox.getText().toString();
}
public void setGameType() {
gameTypes.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View arg1,
int arg2, long arg3) {
gameType = (String) gameTypes.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void OK() {
userConfigOK.setOnClickListener( new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(UserConfig.this, EnemyConfig1.class);
startActivity(intent);
validation.stop();
}
});
}
public void autoValidation() {
validation = new Thread(new Runnable() {
#Override
public void run() {
if( ( !gameType.trim().equals("") ) && ( !playerName.trim().equals("") ) )
{
userConfigOK.setClickable(true);
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
validation.start();
}
}
Try this
userConfigOK.setEnabled(false);
Instead of
userConfigOK.setClickable(false);
You could just have the onClickListener check to see if there is any text entered, and if there is an item selected from the grid. If the user hasn't selected anything, you could make a Toast that prompts the user to enter the values required.
I want to achieve Facebook Integration in my app. At this point of time, I have the login and post to wall functionality, but the wall post I have is only like the simple wall post.
I want to achieve this. Just like in every game, they have this kind of facebook feed..
This is the current code I have..
package com.example.facebooktrial;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
#SuppressWarnings("deprecation")
public class AndroidFacebookConnectActivity extends Activity {
Button btnFbLogin;
Button btnPostToWall;
// Your Facebook APP ID
private static String APP_ID = "593769430655402"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFbLogin = (Button) findViewById(R.id.btnFbLogin);
btnPostToWall = (Button) findViewById(R.id.btnFbPost);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
}
I found the solution. Just make use of a Bundle where you'll store all the necessary information like the picture, name, link and so on.. After that, include that bundle in the Facebook dialog as an argument..
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
Bundle params = new Bundle();
params.putString("name", "Check it out, I am playing FLIP game!");
params.putString("caption", "Come on FLIP with me");
params.putString("description", "FLIP!");
params.putString("picture", "http://www.rawk.com/media/images/uploaded/products/2099/flip-hkd-black-complete-skateboard.3043.full.jpg");
facebook.dialog(this, "feed",params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}