i'm using facebook runner to apply some facebook api tesk.
i want to check if i got a JSON object with data or and error message so i'm checking the "message" field to check if it's null.
if it is not null and i have a massage, i want to display the message and exit the application.
this is my code in my activity:
public class Loader extends Activity implements FacebookConnectionListener, ServerDataListener {
private TextView loaderStatus;
private Facebook facebook;
private AsyncFacebookRunner facebookRunner;
private FacebookConnection facebookConnection;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loader);
facebook = new Facebook(facebookAppId);
facebookRunner = new AsyncFacebookRunner(facebook);
facebookConnection = new FacebookConnection(this, 1);
facebookRunner.request("me",facebookConnection);
}
#Override
public void onFacebookResponse(final String response , int step) {
final JSONObject facebookResults = convertToJSON(response);
final Context thisContext = (Context) getBaseContext();
String id = "", name = "", gender = "", homeTown = "";
Drawable profilePicture = null;
if (step == 1) {
if (facebookResults.isNull("message")) {
try {
id = facebookResults.getString("id");
name = facebookResults.getString("name");
gender = facebookResults.getString("gender");
JSONObject homeTownObject = (JSONObject) facebookResults.get("hometown");
homeTown = homeTownObject.getString("name");
profilePicture = getProfilePicture(id);
} catch (JSONException e) {
alert("Facebook", e.toString(), "Ok", thisContext);
}
facebookCurrentUser = new FacebookCurrentUser(id, name, gender);
facebookCurrentUser.setHomeTown(homeTown);
facebookCurrentUser.setProfilePicture(profilePicture);
app.setFacebookCurrentUser(facebookCurrentUser);
facebookConnection = new FacebookConnection(this, 2);
this.runOnUiThread(new Runnable() {
public void run() {
loaderStatus.setText("Getting friends details");
}
});
}
else {
this.runOnUiThread(new Runnable() {
public void run() {
alert("Facebook", "Can't get user details! Please try again", "Ok", thisContext);
}
});
}
}
public void alert (String title, String message, String ok, Context listener)
{
AlertDialog.Builder alert = new AlertDialog.Builder(listener);
alert.setMessage(message);
alert.setTitle(title);
alert.setPositiveButton(ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
this is FacebookConnection class:
public class FacebookConnection implements RequestListener {
private FacebookConnectionListener listener;
private int step;
public FacebookConnection (FacebookConnectionListener listener, int step) {
this.listener = listener;
this.step = step;
}
public void updateFacebookListener(String response) {
listener.onFacebookResponse(response, step);
}
#Override
public void onComplete(String response, Object state) {
updateFacebookListener(response);
}
#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) { }
}
the FacebookConnectionListener interface:
public interface FacebookConnectionListener {
public void onFacebookResponse(String response, int step);
}
my alerts keep giving me the :
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
and i can't understand why.. help ?
Well, try this:
public void alert (String title, String message, String ok) {
this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog alert = new AlertDialog.Builder(Loader.this).create();
alert.setMessage(message);
alert.setTitle(title);
alert.setPositiveButton(ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
});
}
Instead of what you have now, and when you call it, just call it like any other method:
this.alert("Facebook", "Can't get user details! Please try again", "Ok")
I'm not exactly sure where it goes wrong, it even might have to do with you forgetting the create() part when constructing the dialog.
Hope this will sort things for you.
The reason it is appearing is because you are trying to update Ui from a different thread. As this is a partial code, I can suggest you changing your code to
MyActivity.this.runOnUiThread(new Runnable() {
public void run() {
loaderStatus.setText("Getting friends details");
}
});
where MyActivity is your Activity's name.
the easy way:
u can publishProgress(something)
and process the publishing, to show your alert :D
Related
I'm new on android development, so decided to learn simple login using MVP architectural pattern, in general everything is working fine, as checking user credentials, calling repository...etc.
However, only the implementations of showProgress() & hideProgress() that works in a weird way, for me at least.
Note that the showProgress() only works if the user inter valid credentials.
Thanks.
// Presenter Class
package com.example.mvp.login;
import android.util.Log;
import com.example.mvp.login.LoginContract;
import com.example.mvp.utils.SharedPrefManager;
public class LoginPresenterImpl implements LoginContract.Presenter{
SharedPrefManager sharedPrefManager;
private LoginContract.View view;
private LoginContract.Service service;
public LoginPresenterImpl(LoginContract.View view, LoginContract.Service service) {
this.view = view;
this.service = service;
sharedPrefManager = SharedPrefManager.getInstance(view.getContext());
}
#Override
public void onLoginClicked() {
String username = view.getUsername();
if (username.isEmpty()){
view.showUsernameError();
view.hideProgress();
return;
}
String password = view.getPassword();
if (password.isEmpty()){
view.showPasswordError();
view.hideProgress();
return;
}
view.showProgress(); // this method is called, but doesn't show in the UI Thread
boolean loginSucceeded = service.login(username, password);
if (loginSucceeded){
sharedPrefManager.userLogin(username);
view.navigateHome();
return;
}
view.hideProgress();
view.showLoginError();
}
#Override
public void isUserLoggedIn() {
if(sharedPrefManager.isLoggedIn())
view.navigateHome();
}
}
// View Class
public class LoginActivity extends AppCompatActivity implements LoginContract.View{
private EditText ed_username, ed_password;
private Button login;
private TextView signUp;
private ProgressBar progressBar;
LoginContract.Presenter presenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView(this);
presenter = new LoginPresenterImpl(this, new LoignServiceImpl());
presenter.isUserLoggedIn();
login.setOnClickListener(click);
}
View.OnClickListener click = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.login:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
presenter.onLoginClicked();
}
}, 1200);
}
}
};
public void initView(LoginActivity view){
ed_username = view.findViewById(R.id.username);
ed_password = view.findViewById(R.id.password);
login = view.findViewById(R.id.login);
signUp = view.findViewById(R.id.sign_up);
progressBar = view.findViewById(R.id.progressBar);
}
#Override
public String getUsername() {
return ed_username.getText().toString();
}
#Override
public String getPassword() {
return ed_password.getText().toString();
}
#Override
public void showProgress() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void hideProgress() {
progressBar.setVisibility(View.GONE);
}
#Override
public void showUsernameError() {
ed_username.setError("Must not be empty");
}
#Override
public void showPasswordError() {
ed_password.setError("Must not be empty");
}
#Override
public void navigateHome() {
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
finish();
}
#Override
public void showLoginError() {
Toast.makeText(this,
"User not Found",
Toast.LENGTH_SHORT).show();
}
#Override
public Context getContext() {
return this;
}
}
Thanks to h4rd4r7c0r3 and Ionut J. Bejan, for highlighting several aspects i wasn't a ware of, in particular Working Thread(UI THREAD) and Another Thread(Background Thread).
Although i don't know yet how to implement them very well, i found way after searching the internet.
The main scenario are:
When the user enter username and password, UI should show indication
(Progress Bar) checking credentialiy of the user, implementing
showProgress().
When the checking is finished, UI should stop the indication.
implementing hideProgress().
An action to be taken based on the result, for example: Navigate to
new Activity or Toast "Wrong Username/Passowrd".
//LoginActivity
#Override
public void showProgress() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void hideProgress() {
progressBar.setVisibility(View.GONE);
}
// LoginPresenter
public void onLoginClicked() {
String username = view.getUsername();
if (username.isEmpty()){
view.showUsernameError();
view.hideProgress();
return;
}
String password = view.getPassword();
if (password.isEmpty()){
view.showPasswordError();
view.hideProgress();
return;
}
view.showProgress();
service.login(username,password, this);
}
#Override
public void isUserLoggedIn() {
if(sharedPrefManager.isLoggedIn())
view.navigateHome();
}
// implementing onFinished from FinishedListiner interface, to capture the result
#Override
public void onFinished(boolean bool) {
view.hideProgress();
if (bool){
sharedPrefManager.userLogin(view.getUsername());
view.navigateHome();
return;
}
view.showLoginError();
}
// Service, which will connect to the datasource
public class LoginServiceImpl implements LoginContract.Service {
UserRepository userRepository;
#Override
public void login(final String username, final String password, final FinishedListiner listener) {
userRepository = UserRepositoryImpl.getInstance();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// The method which will be used in the presenter class.
listener.onFinished(userRepository.checkUser(username, password));
}
}, 1200);
}
Try this below snippet :
Step 1:- Create BaseActivity extend to AppCompactActivity
Step 2:-Setting BaseActivity as per your requirement
Step 3:-Create Instance of your Progress Dialog
Step 4:-Create function showProgress()
Like:-
private fun showProgress(){
if(!progress.isShowing){
progress.show()
}
}
Step 5:- Create function HideProgress()
Like:-
private fun hideProgress(){
if(progress.isShowing){
progress.dismiss()
}
}
And use as per your requirement.
Your View just run presenter on another thread. See your Handler. Then it update the view and can not access to the UI. To fix this, just make sure your showProgress() is doing work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
//show your proress here.
}
});
I take reference from official website https://quickblox.com/developers/Android#Download_Android_SDK
gradle compile succeed:
repositories {
maven {
url "https://github.com/QuickBlox/quickblox-android-sdk-releases/raw/master/"
}
}
dependencies {
compile "com.quickblox:quickblox-android-sdk-core:2.5.1#aar"
compile("com.quickblox:quickblox-android-sdk-chat:2.5.1#aar") {
transitive=true
}
}
then i use the code first:
I had the APP_ID...etc
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
Second step :
I reference Guide: Getting Started with Chat API https://quickblox.com/developers/Android_XMPP_Chat_Sample#Guide:_Getting_Started_with_Chat_API
//Prepare chat service
QBChatService.setDebugEnabled(true); // enable chat logging
QBChatService.setDefaultPacketReplyTimeout(10000);//set reply timeout in milliseconds for connection's packet.
//Can be used for events like login, join to dialog to increase waiting response time from server if network is slow.
//configure chat socket
QBChatService.ConfigurationBuilder chatServiceConfigurationBuilder = new QBChatService.ConfigurationBuilder();
chatServiceConfigurationBuilder.setSocketTimeout(60); //Sets chat socket's read timeout in seconds
chatServiceConfigurationBuilder.setKeepAlive(true); //Sets connection socket's keepAlive option.
chatServiceConfigurationBuilder.setUseTls(true); //Sets the TLS security mode used when making the connection. By default TLS is disabled.
QBChatService.setConfigurationBuilder(chatServiceConfigurationBuilder);
It has a issue that i can't import QBChatService.ConfigurationBuilder
so i try to change gradle to compile("com.quickblox:quickblox-android-sdk-chat:2.6.1")
now QBChatService.ConfigurationBuilder can be import
Third step:
I take the official step use the code:
// Initialise Chat service
final QBChatService chatService = QBChatService.getInstance();
final QBUser user = new QBUser("garrysantos", "garrysantospass");
QBAuth.createSession(user, new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession qbSession, Bundle bundle) {
// success, login to chat
user.setId(qbSession.getUserId());
chatService.login(user, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
}
#Override
public void onError(QBResponseException e) {
}
});
}
#Override
public void onError(QBResponseException e) {
}
});
//To handle different connection states use ConnectionListener:
ConnectionListener connectionListener = new ConnectionListener() {
#Override
public void connected(XMPPConnection xmppConnection) {
}
#Override
public void authenticated(XMPPConnection xmppConnection, boolean b) {
}
#Override
public void connectionClosed() {
}
#Override
public void connectionClosedOnError(Exception e) {
// connection closed on error. It will be established soon
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int i) {
}
#Override
public void reconnectionFailed(Exception e) {
}
};
QBChatService.getInstance().addConnectionListener(connectionListener);
//logOut
boolean isLoggedIn = chatService.isLoggedIn();
if (!isLoggedIn) {
return;
}
chatService.logout(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
//success
chatService.destroy();
}
#Override
public void onError(QBResponseException e) {
}
});
//By default Android SDK reconnects automatically when connection to server is lost.
//But there is a way to disable this and then manage this manually:
QBChatService.getInstance().setReconnectionAllowed(false);
when i use the step about QBChatDialog , it can't be import again....
ArrayList<Integer> occupantIdsList = new ArrayList<Integer>();
occupantIdsList.add(34);
occupantIdsList.add(17);
QBChatDialog dialog = new QBChatDialog();
dialog.setName("Chat with Garry and John");
dialog.setPhoto("1786");
dialog.setType(QBDialogType.GROUP);
dialog.setOccupantsIds(occupantIdsList);
//or just use DialogUtils
//for creating PRIVATE dialog
//QBChatDialog dialog = DialogUtils.buildPrivateDialog(recipientId);
//for creating GROUP dialog
QBChatDialog dialog = DialogUtils.buildDialog("Chat with Garry and John", QBDialogType.GROUP, occupantIdsList);
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle params) {
}
#Override
public void onError(QBResponseException responseException) {
}
});
so i try to change gradle compile compile("com.quickblox:quickblox-android-sdk-chat:3.3.0")
now QBChatDialog can be imported.
but it has another issues...
Can't not resolve symbol 'QBSettings' and 'QBSession'
I'm angry now , are you kidding me ?
Why the official step cheat me step by step ?
I'm tired... what should i do ?
Somebody can save me please , any help would be appreciated !
According #Jagapathi kindly responding , i update my code , the next issue is that i can't log in
My toast shows Login error when i click the login button:
private void setupQuickBlox() {
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
QBSettings.getInstance().setAutoCreateSession(true);
//login to quickblox
String enterAccount = editAccount.getText().toString();
String enterPassword = editPassword.getText().toString();
Log.d(TAG,enterAccount);
Log.d(TAG,enterPassword);
final QBUser user = new QBUser(enterAccount, enterPassword);
//login
QBUsers.signIn(user).performAsync(new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser qbUser, Bundle bundle) {
SharedPreferences.Editor s = getSharedPreferences("QBid", 0).edit();
s.putString("id", user.getId().toString());
s.apply();
Log.d(TAG,user.getId().toString());
Toast.makeText(MainActivity.this, "Login success with quickblox", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(MainActivity.this, "Login error", Toast.LENGTH_SHORT).show();
}
});
}
the code is under my onCreat , so it shows Login error when i satrt the app of course , but when i enter account and password , it still shows Login error , why? I check the log , i can see the account and password that i typed , but i can't see user.getId().toString() on my log , what step is wrong ?
i check the account is correct:
Here is my key:
static final String APP_ID = "50427";
static final String AUTH_KEY = "naMGFKMshdLC3s4";
static final String AUTH_SECRET = "GP8ey4GsQXt2TGu";
static final String ACCOUNT_KEY = "dHYgix3we3bxxsvMqyuR";
Here is my test Account key:
My button onClcik:
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setupQuickBlox();
}
});
Here is my log:
I can guide you with Quickblox I am in same position when I started using quickblox.
step 1:-
compile 'com.quickblox:quickblox-android-sdk-core:3.3.0#aar'
compile("com.quickblox:quickblox-android-sdk-chat:3.3.0#aar") {
transitive = true
}
This is for latest version of quickblox. So don't use old versions .
step 2:-
This is my SetUp Quickblox function you don't forgot to use app_id Auth_key auth_secret and account_key
private void SetupQuickBlox() {
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
QBSettings.getInstance().setAutoCreateSession(true);
//login to quickblog for
final QBUser user=new QBUser("USER_NAME OF USER","PASSWORD OF USER");
// Login
QBUsers.signIn(user).performAsync(new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser user, Bundle args) {
// success
SharedPreferences.Editor s=getSharedPreferences("QBid",0).edit();
s.putString("id",user.getId().toString());
s.apply();
Toast.makeText(HomeActivity.this, "Login succes with quickblox", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(QBResponseException error) {
// error
}
});
}
step:- 3
You are all done Login with quickblox is successful so you can now request DIALOGS or CREATE DIALOg Sessions are automatically created in latest version.
Create New Dialog
private void NewMessage() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
QBChatDialog dialog = DialogUtils.buildPrivateDialog("USER_ID of other user");
dialog.setName("tester1");
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle params) {
}
#Override
public void onError(QBResponseException responseException) {
}
});
}
});
}
Request List Of Dialog Of Logged In User
I Used ListView And Dialogs result will be in array list which contains LIST of QBCHATDIALOG
private void receiveChatList() {
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.setLimit(100);
QBRestChatService.getChatDialogs(null, requestBuilder).performAsync(
new QBEntityCallback<ArrayList<QBChatDialog>>() {
#Override
public void onSuccess(final ArrayList<QBChatDialog> result, Bundle params) {
int totalEntries = params.getInt("total_entries");
Log.wtf("chat",""+result);
TrumeMsgAdapter adapter=new TrumeMsgAdapter(TrueMeMessagesActivity.this,result);
chatlistView.setAdapter(adapter);
chatlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(TrueMeMessagesActivity.this,ChatingActivity.class).putExtra("dialog",result.get(position)));
}
});
}
#Override
public void onError(QBResponseException responseException) {
}
});
}
My Adapter Code
public class TrumeMsgAdapter extends BaseAdapter {
private ArrayList<QBChatDialog> chatlist;
private Context context;
public TrumeMsgAdapter(Context c,ArrayList<QBChatDialog> chatlist){
this.chatlist=chatlist;
this.context=c;
}
#Override
public int getCount() {
return chatlist.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View List;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
List = inflater.inflate(R.layout.trume_msg_adapter, null);
TextView username=(TextView) List.findViewById(R.id.UserName);
TextView lastmessage=(TextView)List.findViewById(R.id.lastmessage);
username.setText(chatlist.get(position).getName());
lastmessage.setText(chatlist.get(position).getLastMessage());
} else {
List = convertView;
TextView username=(TextView) List.findViewById(R.id.UserName);
TextView lastmessage=(TextView)List.findViewById(R.id.lastmessage);
username.setText(chatlist.get(position).getName());
lastmessage.setText(chatlist.get(position).getLastMessage());
}
return List;
}
}
i working facebook api in android. i successfully can sing in in facebook and try to check facebook user name
i wrote some code but i have
only the original thread that created a view hierarchy
exception
this is a my code:
public void LoginFacebook() {
mFacebook.authorize(this, mPermissions, new LoginDialogListener());
}
private final class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
SessionStore.save(mFacebook, getApplicationContext());
getProfileInformation();
}
public void onCancel() {
SessionEvents.onLoginError("Action Canceled");
}
#Override
public void onFacebookError(FacebookError error) {
SessionEvents.onLoginError(error.getMessage());
}
#Override
public void onError(DialogError error) {
SessionEvents.onLoginError(error.getMessage());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
#SuppressLint("SdCardPath")
public void getProfileInformation() {
mAsyncRunner.request("me", new BaseRequestListener() {
#SuppressLint("CommitPrefEdits")
#Override
public void onComplete(String response, Object state) {
Log.e("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
facebook_userid = profile.getString("id");
facebook_username = profile.getString("name");
facebook_username = facebook_username.replace("%20", " ");
fb_name.setText(facebook_username);
} catch (JSONException e) {
e.printStackTrace();
}
}
#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) {
}
});
}
what am i doing wrong. i can sing in but i can't to show username in textview.
if anyone knows solution please help me
thanks
In your onComplete method you're trying to set the text of a UI element. Your onComplete method is getting called from a background(non main/UI thread). Any time you make a UI change, it must be on the UI thread. Try inserting a runOnUIThread call in your onComplete like this:
runOnUiThread(new Runnable() {
public void run() {
fb_name.setText(facebook_username);
}
});
Note: you will need to make variables declared outside the runnable final (ex: facebook_username)
Also note: most (if not all) web based calls will return on a background thread so you might need to use runOnUIThread frequently.
i want to integrate flurry in my app. in the following code i am integrate flurry but that was not working properly in android. flurry listener call its method two times. how it working please help me.
LoginActivity.java
public class LoginActivity extends Activity implements OnClickListener,
AsyncTaskCompleteListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
setContentView(R.layout.login_activity);
Map<String, String> map = new HashMap<String, String>();
map.put("url", NFLConstanants.LOGIN_URL);
map.put("username", strUser);
map.put("passwd", strPassword);
new ParseController(LoginActivity.this, map,
NFLConstanants.SERVICE_CODE0, 1);
}
#Override
protected void onStart() {
super.onStart();
System.out.println("call on start method");
FlurryAgent.onStartSession(this, MACUtils.APIKEY_FLURRY);
FlurryAgent.enableTestAds(true);
FlurryAgent.initializeAds(this);
FlurryAgent.setLogEnabled(true);
}
#Override
protected void onStop() {
super.onStop();
System.out.println("call on stop method");
FlurryAgent.onEndSession(this);
}
#Override
public void onTaskCompleted(String responce, int sc) {
if (FlurryAgent.isAdAvailable(LoginActivity.this,
MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
final String msgv = "To help keep this app free please watch this short video. Thanks";
AlertDialog.Builder dlg = new AlertDialog.Builder(
LoginActivity.this);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msgv);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
try {
MyAdListener myAdListener = new MyAdListener(
LoginActivity.this,
LoginActivity.this, "3");
FlurryAgent
.setAdListener(myAdListener);
FrameLayout container = new FrameLayout(
LoginActivity.this);
FlurryAgent
.getAd(LoginActivity.this,
MACUtils.myAdSpaceName,
container,
FlurryAdSize.FULLSCREEN,
MACUtils.timeout);
} catch (Exception e) {
e.printStackTrace();
}
}
});
AlertDialog alert = dlg.create();
alert.show();
}
}
}
MyAdListener.java
public class MyAdListener implements FlurryAdListener {
public Activity activity;
public Context ctx;
String pagePosition;
boolean isDialogLaunch = false;
public MyAdListener(Activity act, Context ctx, String page) {
this.activity = act;
this.pagePosition = page;
this.ctx = ctx;
this.isDialogLaunch = false;
}
#Override
public boolean shouldDisplayAd(String myAdSpaceName, FlurryAdType type) {
System.out.println("shouldDisplayAd:: " + type);
return true;
}
#Override
public void onAdClosed(String myAdSpaceName) {
System.out.println("onAdClosed::: " + myAdSpaceName);
if (pagePosition.equals("1") || pagePosition.equals("2")) {
actionOnFlurryVideo();
} else {
if (!FlurryAgent.isAdAvailable(activity, MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
#Override
public void onApplicationExit(String myAdSpaceName) {
System.out.println("onApplicationExit:: " + myAdSpaceName);
actionOnFlurryVideo();
}
#Override
public void onRenderFailed(String adSpace) {
System.out.println("onRenderFailed:: " + adSpace);
actionOnFlurryVideo();
}
#Override
public void spaceDidReceiveAd(String adSpace) {
System.out.println("spaceDidReceiveAd:: " + adSpace);
}
#Override
public void spaceDidFailToReceiveAd(String adSpace) {
System.out.println("spaceDidFailToReceiveAd:: " + adSpace);
}
#Override
public void onAdClicked(String id) {
System.out.println("onAdClicked:: " + id);
}
#Override
public void onAdOpened(String id) {
System.out.println("onAdOpened::: " + id);
}
public void actionOnFlurryVideo() {
System.out.println("call actionOnflurryvideo");
if (pagePosition.equals("1") || pagePosition.equals("2")) {
if (!isDialogLaunch) {
isDialogLaunch = true;
final String msg = "Thanks for supporting our free website. Your bet has now been confirmed.";
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msg);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
NavigationGroupActivity parent = ((NavigationGroupActivity) activity
.getParent());
parent.backToFirst();
}
});
AlertDialog alert = dlg.create();
alert.show();
}
} else {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
This issue will be fixed in our next release which is expected to come out very soon.
(Full disclosure: I work in the Support team at Flurry)
I want to get the id from the Facebook User but what I've tried so far doesn't work...
public class fbLogin extends Activity {
public static final int LOGIN = Menu.FIRST;
public static final int GET_EVENTS = Menu.FIRST + 1;
public static final int GET_ID = Menu.FIRST + 2;
public static final String APP_ID = "361579407254212";
public static final String TAG = "FACEBOOK CONNECT";
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
private Handler mHandler = new Handler();
private static final String[] PERMS = new String[] { "user_events","email" };
private TextView mText;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
// setup the content view
initLayout();
// setup the facebook session
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
if (mFacebook.isSessionValid()) {
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
asyncRunner.logout(this, new LogoutRequestListener());
} else {
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
mAsyncRunner.request("me", new IDRequestListener());
}
protected void initLayout() {
LinearLayout rootView = new LinearLayout(this.getApplicationContext());
rootView.setOrientation(LinearLayout.VERTICAL);
this.mText = new TextView(this.getApplicationContext());
this.mText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
rootView.addView(this.mText);
this.setContentView(rootView);
}
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {}
public void onFacebookError(FacebookError e) {}
public void onError(DialogError e) {}
public void onCancel() {}
}
private class LogoutRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
mText.setText("Logged out");
}
});
}
public void onIOException(IOException e, Object state) {}
public void onFileNotFoundException(FileNotFoundException e, Object state) {}
public void onMalformedURLException(MalformedURLException e, Object state) {}
public void onFacebookError(FacebookError e, Object state) {}
}
private class IDRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
try {
// process the response here: executed in background thread
Log.d(TAG, "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String id = json.getString("id");
fbLogin.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + id + "!");
}
});
} catch (JSONException e) {
Log.w(TAG, "JSON Error in response");
mText.setText("catch1...");
} catch (FacebookError e) {
mText.setText("catch2");
}
}
public void onIOException(IOException e, Object state) {mText.setText("Logging out...1");}
public void onFileNotFoundException(FileNotFoundException e, Object state) {mText.setText("Logging out...2");}
public void onMalformedURLException(MalformedURLException e,Object state) {mText.setText("Logging out...3");}
public void onFacebookError(FacebookError e, Object state) {mText.setText("Logging out...4");}
}
}
It gives a Facebook Error when I go to the OnComplete method from the IDRequestListener class...
How can I fix it? Can anyone help me, please?
You can use socialauth android sdk. Can get user profile, post messages , gets friends list
http://code.google.com/p/socialauth-android/
authorize() is not synchronous and will return immediately. You'll need to wait for the authorization request to complete before submitting requests requiring an access token. Basically, fire the me request only when onComplete() has been called in the authorize() listener.
Also your activity seems to be missing the onActivityResult() implementation that feeds the Facebook object with authorization results, i.e.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}