MessagesActivity.java
package org.example.fbapp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MessagesActivity extends ListActivity {
// Your Facebook APP ID
private static String APP_ID = "549603678442054";
ListAdapter adapter;
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_MESSAGE = "message";
// data JSONArray
JSONArray data = null;
// Instance of Facebook Class
#SuppressWarnings("deprecation")
private Facebook facebook = new Facebook(APP_ID);
#SuppressWarnings("deprecation")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
// Hashmap for ListView
ArrayList<HashMap<String, String>> messages = new ArrayList<HashMap<String, String>>();
private ListView lv;
ListView mylistview;
ArrayList<String> array_months;
ArrayAdapter<String> listAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.contacts_view);
mAsyncRunner = new AsyncFacebookRunner(facebook);
ListAdapter adapter = createAdapter();
setListAdapter(adapter);
}
/**
* Creates and returns a list adapter for the current list activity
*
* #return
*/
#SuppressWarnings("deprecation")
protected ListAdapter createAdapter()
{
mAsyncRunner.request("203153109726651/feed", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("GET POSTS", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject obj = new JSONObject(json);
JSONArray finalObj = obj.getJSONArray("data");
array_months = new ArrayList<String>();
for (int i = 0; i < finalObj.length(); i++) {
final String message = finalObj.getJSONObject(i)
.getString("message");
array_months.add(message);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + message, Toast.LENGTH_LONG)
.show();
}
});
}
// Create a simple array adapter (of type string) with the test values
//ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, adapter);
adapter = new ArrayAdapter<String>(MessagesActivity.this,
android.R.layout.simple_list_item_1, array_months);
} 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) {
}
});
//setListAdapter(listAdapter);
return adapter;
}
}
FBAppActivity.java
package org.example.fbapp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
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 FBAppActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "549603678442054";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_MESSAGE = "message";
// data JSONArray
JSONArray data = null;
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
// Hashmap for ListView
ArrayList<HashMap<String, String>> messages = new ArrayList<HashMap<String, String>>();
private ListView lv;
// Buttons
Button btnFbLogin;
Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;
Button btnFbLogout;
Button btnGetPost;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fbapp);
// facebook = new Facebook(APP_ID);
btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
btnFbLogout = (Button) findViewById(R.id.btn_logout);
btnGetPost = (Button) findViewById(R.id.btn_group_posts);
mAsyncRunner = new AsyncFacebookRunner(facebook);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
/**
* Logout button Click event
* */
btnFbLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Logout Button", "button Clicked");
logoutFromFacebook();
}
});
/**
* Getting facebook Profile info
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
/**
* Get Posts from Group
* */
btnGetPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getGroupPosts();
//getGPosts();
startActivity(new Intent(FBAppActivity.this, MessagesActivity.class));
}
});
/**
* Showing Access Tokens
* */
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAccessTokens();
}
});
}
/**
* Function to login into facebook
* */
#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);
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);
// Making logout button visible
btnFbLogout.setVisibility(View.VISIBLE);
// Making group posts button visible
btnGetPost.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "publish_stream",
"user_groups" }, 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);
// Making logout button visible
btnFbLogout.setVisibility(View.VISIBLE);
// Making group posts button visible
btnGetPost.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Get Profile information by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
JSONObject birthday = profile.getJSONObject("location");
final String location = birthday.getString("name");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Name: " + name + "\nEmail: " + email
+ "\nLocation: " + location,
Toast.LENGTH_LONG).show();
}
});
} 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) {
}
});
}
/**
* Get Group Posts by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getGPosts() {
mAsyncRunner.request("203153109726651/feed", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("GET POSTS", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject obj = new JSONObject(json);
JSONArray finalObj = obj.getJSONArray("data");
for (int i = 0; i < finalObj.length(); i++) {
final String message = finalObj.getJSONObject(i)
.getString("message");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MESSAGE, message);
// adding HashList to ArrayList
messages.add(map);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + message, Toast.LENGTH_LONG)
.show();
}
});
}
} 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) {
}
});
ListAdapter adapter = new SimpleAdapter(FBAppActivity.this, messages,
R.layout.list_item,
new String[] { TAG_MESSAGE }, new int[] {
R.id.name });
//FBAppActivity.this.setListAdapter(adapter);
}
/**
* Function to post to facebook wall
* */
#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() {
}
});
}
/**
* Function to show Access Tokens
* */
#SuppressWarnings("deprecation")
public void showAccessTokens() {
String access_token = facebook.getAccessToken();
Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
/**
* Function to Logout user from Facebook
* */
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, 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);
btnFbLogout.setVisibility(View.INVISIBLE);
btnGetPost.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) {
}
});
}
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
* menu; this adds items to the action bar if it is present.
* getMenuInflater().inflate(R.menu.fbapp, menu); return true; }
*/
}
When i click on the button, the ListView opens but with no data i.e. Empty set.
Contacts_View.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Empty set"
/>
</LinearLayout>
What i mean here is that both the functions are identical.getGPosts() is called in the FBAppActivity whereas the createAdapter() is called in MessagesActivity.getGPosts() works but createAdapter() does not. Kindly help me understand why is this happening.
Basically i am trying to import posts from a facebook group. My Toast object is working fine from the getGPosts() [it is in the FBAppActivity class] function. This function getGPosts() is called on the button click.I verified that i am getting the data using the Toast object. Now i want to populate the data to a ListView. Which i am unable to do. I have tried various methods, but none has worked out for me.
Because you're calling the setListAdapter(adapter) for implicit (Activity's) ListView in the onCreate(Bundle savedInstanceState) method and in the getGPosts() method you reference the correct (visible) ListView.
Simply change the mentioned call in the onCreate(Bundle savedInstanceState) method to:
myListView = getListView();
myListView.setAdapter(adapter);
And you should be fine! Good luck!
P.S. This solution will work if your ListActivity follows the following requirement:
your own view MUST contain a ListView object with the id "#android:id/list"
from Google's documentation
As I see you are extending ListActivity. So below code must throw a NPE.
lv = (ListView)findViewById(R.id.list);
lv.setAdapter(adapter);
You should use below code at onComplete method instead;
setListAdapter(adapter);
or
getListView().setAdapter(adapter);
Related
I have tried to make a video call with quickblox but it doesn't work, I start the call but on the other device onReceiveNewSession doesn't call.
and this is my code:-
This activity to start the call:-
package com.example.group.travilling.travilling.chat;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.example.group.travilling.travilling.R;
import com.example.group.travilling.travilling.common.Common;
import com.quickblox.auth.QBAuth;
import com.quickblox.auth.session.QBSession;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBSignaling;
import com.quickblox.chat.QBWebRTCSignaling;
import com.quickblox.chat.listeners.QBVideoChatSignalingManagerListener;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.users.model.QBUser;
import com.quickblox.videochat.webrtc.QBRTCClient;
import com.quickblox.videochat.webrtc.QBRTCSession;
import com.quickblox.videochat.webrtc.QBRTCTypes;
import com.quickblox.videochat.webrtc.callbacks.QBRTCClientSessionCallbacks;
import com.quickblox.videochat.webrtc.callbacks.QBRTCClientVideoTracksCallbacks;
import com.quickblox.videochat.webrtc.callbacks.QBRTCSessionConnectionCallbacks;
import com.quickblox.videochat.webrtc.exception.QBRTCException;
import com.quickblox.videochat.webrtc.view.QBRTCSurfaceView;
import com.quickblox.videochat.webrtc.view.QBRTCVideoTrack;
import org.webrtc.RendererCommon;
import org.webrtc.VideoRenderer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.quickblox.videochat.webrtc.QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO;
public class call_activity extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_activity);
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
QBChatService.ConfigurationBuilder chatServiceConfigurationBuilder = new QBChatService.ConfigurationBuilder();
chatServiceConfigurationBuilder.setSocketTimeout(180); //Sets chat socket's read timeout in seconds
chatServiceConfigurationBuilder.setKeepAlive(true); //Sets connection socket's keepAlive option.
QBChatService.setConfigurationBuilder(chatServiceConfigurationBuilder);
// String login = "login";
// String password = "password";
// final QBUser user = new QBUser(login, password);
final QBUser user = new QBUser("u" + prefs.getInt("account_phone_chat", 0) + "", Common.pass);
// CREATE SESSION WITH USER
// If you use create session with user data,
// then the user will be logged in automatically
QBAuth.createSession().performAsync(new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(final QBSession qbSession, Bundle bundle) {
user.setId(Integer.parseInt(prefs.getString("user_id","0")));
// qbUser.setPassword(BaseService.getBaseService().getToken());
if (!QBChatService.getInstance().isLoggedIn()) {
QBChatService.getInstance().login(user, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
call();
}
#Override
public void onError(QBResponseException e) {
call();
Log.e("errorwhyis!", e.getMessage());
}
});
// mDialog.dismiss();
} else {
System.out.println("SFSSFFSFSFSDF");
call();
}
}
#Override
public void onError(QBResponseException e) {
Log.e("error", e.getMessage() + "");
}
});
}
private void call() {
//Add signalling manager
add_signlling_manager();
//Notify RTCClient that you are ready to receive calls
QBRTCClient.getInstance(getBaseContext()).prepareToProcessCalls();
//To listen for the callbacks use the following methods:
QBRTCClient.getInstance(getBaseContext()).addSessionCallbacksListener(new QBRTCClientSessionCallbacks() {
// * Called each time when new session request is received.
public void onReceiveNewSession(QBRTCSession session) {
// obtain received user info
Map<String, String> userInfo = session.getUserInfo();
// .....
// ..... your code
// .....
// Set userInfo
// User can set any string key and value in user info
// Map<String,String> userInfo = new HashMap<String,String>();
// userInfo.put("Key", "Value");
// Accept incoming call
session.acceptCall(userInfo);
// Rejecting call
// session.rejectCall(userInfo);
// session.hangUp(userInfo);
}
/**
* Called in case when user didn't answer in timer expiration period
*/
public void onUserNotAnswer(QBRTCSession session, Integer userID) {
System.out.println("NOOOOOOAAAAAA");
}
/**
* Called in case when opponent has rejected you call
*/
public void onCallRejectByUser(QBRTCSession session, Integer userID, Map<String, String> userInfo) {
System.out.println("NOOOOOOAAAAAA22");
}
/**
* Called in case when opponent has accepted you call
*/
public void onCallAcceptByUser(QBRTCSession session, Integer userID, Map<String, String> userInfo) {
System.out.println("NOOOOOOAAAAAA233");
}
/**
* Called in case when opponent hung up
*/
#Override
public void onReceiveHangUpFromUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
}
/**
* Called in case when user didn't make any actions on received session
*/
public void onUserNoActions(QBRTCSession session, Integer userID) {
System.out.println("NOOOOOOAAAAAA555");
}
/**
* Called in case when session will close
*/
public void onSessionStartClose(QBRTCSession session) {
}
/**
* Called when session is closed.
*/
public void onSessionClosed(QBRTCSession session) {
}
});
// QBRTCClient.getInstance(getBaseContext()).removeSessionsCallbacksListener(this);
//Track connection state
addSessionCallbacksListener(new QBRTCSessionConnectionCallbacks() {
#Override
public void onStartConnectToUser(QBRTCSession qbrtcSession, Integer integer) {
System.out.println("NOOOOOOAAAAAA88");
}
#Override
public void onConnectedToUser(QBRTCSession qbrtcSession, Integer integer) {
System.out.println("NOOOOOOAAAAAA999");
}
#Override
public void onConnectionClosedForUser(QBRTCSession qbrtcSession, Integer integer) {
}
#Override
public void onDisconnectedFromUser(QBRTCSession qbrtcSession, Integer integer) {
}
#Override
public void onDisconnectedTimeoutFromUser(QBRTCSession qbrtcSession, Integer integer) {
}
#Override
public void onConnectionFailedWithUser(QBRTCSession qbrtcSession, Integer integer) {
}
#Override
public void onError(QBRTCSession qbrtcSession, QBRTCException e) {
}
});
//Obtain video tracks via QBRTCClientVideoTracksCallbacks interface
addVideoTrackCallbacksListener(new QBRTCClientVideoTracksCallbacks() {
#Override
public void onLocalVideoTrackReceive(QBRTCSession qbrtcSession, QBRTCVideoTrack qbrtcVideoTrack) {
}
#Override
public void onRemoteVideoTrackReceive(QBRTCSession qbrtcSession, QBRTCVideoTrack qbrtcVideoTrack, Integer integer) {
}
});
start_call();
}
//Render video stream to view
private void fillVideoView(int userId, QBRTCSurfaceView videoView, QBRTCVideoTrack videoTrack,
boolean remoteRenderer) {
videoTrack.addRenderer(new VideoRenderer(videoView));
updateVideoView(videoView, !remoteRenderer, RendererCommon.ScalingType.SCALE_ASPECT_FILL);
}
private void updateVideoView(QBRTCSurfaceView surfaceView, boolean mirror, RendererCommon.ScalingType scalingType) {
surfaceView.setScalingType(scalingType);
surfaceView.setMirror(mirror);
surfaceView.requestLayout();
}
private void add_signlling_manager() {
try {
QBChatService.getInstance().getVideoChatWebRTCSignalingManager()
.addSignalingManagerListener(new QBVideoChatSignalingManagerListener() {
#Override
public void signalingCreated(QBSignaling qbSignaling, boolean createdLocally) {
if (!createdLocally) {
QBRTCClient.getInstance(getBaseContext()).addSignaling((QBWebRTCSignaling) qbSignaling);
}
}
});
} catch (NullPointerException e) {
}
}
//Prepare your activity class to audio/video calls
public void addSessionCallbacksListener(QBRTCSessionConnectionCallbacks callback) {
}
public void addVideoTrackCallbacksListener(QBRTCClientVideoTracksCallbacks callback) {
}
//and next method on QBRTCClient instance:
public void addSessionCallbacksListener(QBRTCClientSessionCallbacks callback) {
}
void start_call() {
//start call
QBRTCTypes.QBConferenceType qbConferenceType = QB_CONFERENCE_TYPE_VIDEO;
//Initiate opponents list
List<Integer> opponents = new ArrayList<Integer>();
opponents.add(Common.admin_id); //12345 - QBUser ID
//Set user information
// User can set any string key and value in user info
// Then retrieve this data from sessions which is returned in callbacks
// and parse them as he wish
Map<String, String> userInfo = new HashMap<>();
userInfo.put("Test", "state");
//Init session
QBRTCSession session =
QBRTCClient.getInstance(this).createNewSessionWithOpponents(opponents, qbConferenceType);
//Start call
System.out.println("SSSSSSSSSSSTTTTTTTTTTTA");
session.startCall(userInfo);
}
}
And this service to receive the call >
package com.example.group.test_calender.traveling_admin.booking.chat;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.example.group.test_calender.traveling_admin.booking.common.Common;
import com.quickblox.auth.QBAuth;
import com.quickblox.auth.session.QBSession;
import com.quickblox.auth.session.QBSettings;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBSignaling;
import com.quickblox.chat.QBWebRTCSignaling;
import com.quickblox.chat.listeners.QBVideoChatSignalingManagerListener;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.users.model.QBUser;
import com.quickblox.videochat.webrtc.QBRTCClient;
import com.quickblox.videochat.webrtc.QBRTCSession;
import com.quickblox.videochat.webrtc.callbacks.QBRTCClientSessionCallbacks;
import java.util.Map;
//import static com.dev.trueme.TrueMeConstants.TRUE_ME_USERNEME;
public class VideoCallService extends Service implements QBRTCClientSessionCallbacks {
public VideoCallService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
QBSettings.getInstance().init(getBaseContext(), Common.APP_ID, Common.AUTH_KEY, Common.AUTH_SECURITY);
QBSettings.getInstance().setAccountKey(Common.ACCOUNT_KEY);
QBChatService.setDebugEnabled(true);
QBChatService.ConfigurationBuilder chatServiceConfigurationBuilder = new QBChatService.ConfigurationBuilder();
chatServiceConfigurationBuilder.setSocketTimeout(180); //Sets chat socket's read timeout in seconds
chatServiceConfigurationBuilder.setKeepAlive(true); //Sets connection socket's keepAlive option.
QBChatService.setConfigurationBuilder(chatServiceConfigurationBuilder);
Log.wtf("service", "start");
LoginChatService();
}catch (Exception e){
Log.wtf("ex",""+e);
}
return START_STICKY;
}
private void InitSignalling() {
QBChatService.getInstance().getVideoChatWebRTCSignalingManager()
.addSignalingManagerListener(new QBVideoChatSignalingManagerListener() {
#Override
public void signalingCreated(QBSignaling qbSignaling, boolean createdLocally) {
if (!createdLocally) {
QBRTCClient.getInstance(VideoCallService.this).addSignaling((QBWebRTCSignaling) qbSignaling);
}
}
});
}
public void LoginChatService()
{
final QBUser user = new QBUser(Common.user, Common.pass);
// SharedPreferences s=getSharedPreferences("QBid",0);
user.setId(30586775);
QBAuth.createSession().performAsync(new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(final QBSession qbSession, Bundle bundle) {
// user.setId(qbSession.getUserId());
// qbUser.setPassword(BaseService.getBaseService().getToken());
if (!QBChatService.getInstance().isLoggedIn()) {
QBChatService.getInstance().login(user, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
ProcessCalls();
InitSignalling();
QBRTCClient.getInstance(getBaseContext()).addSessionCallbacksListener (VideoCallService.this);
}
#Override
public void onError(QBResponseException e) {
Log.e("errorwhyis!", e.getMessage());
ProcessCalls();
InitSignalling();
QBRTCClient.getInstance(getBaseContext()).addSessionCallbacksListener(VideoCallService.this);
}
});
// mDialog.dismiss();
} else {
System.out.println("SFSSFFSFSFSDF");
ProcessCalls();
InitSignalling();
QBRTCClient.getInstance(getBaseContext()).addSessionCallbacksListener(VideoCallService.this);
}
}
#Override
public void onError(QBResponseException e) {
Log.e("error", e.getMessage() + "");
}
});
}
private void ProcessCalls() {
QBRTCClient.getInstance(this).prepareToProcessCalls();
}
#Override
public void onReceiveNewSession(QBRTCSession qbrtcSession) {
System.out.println("oiioikjskdkj");
// DataHolder.getInstance().setServiceData(qbrtcSession,qbrtcSession.getUserInfo());
startActivity(new Intent(this,VideoCallActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("service",true));
}
#Override
public void onUserNoActions(QBRTCSession qbrtcSession, Integer integer) {
}
#Override
public void onSessionStartClose(QBRTCSession qbrtcSession) {
}
#Override
public void onUserNotAnswer(QBRTCSession qbrtcSession, Integer integer) {
}
#Override
public void onCallRejectByUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
}
#Override
public void onCallAcceptByUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
}
#Override
public void onReceiveHangUpFromUser(QBRTCSession qbrtcSession, Integer integer, Map<String, String> map) {
}
#Override
public void onSessionClosed(QBRTCSession qbrtcSession) {
}
}
Please If you have a solution or an example to do it help me.
Thank you.
Make sure you have done below steps for establishing WebRTC peer to peer connection.
Add native libraries - libjingle_peerconnection_so.so files. Put native library for each platform: arm64-v8a, armeabi-v7a, x86, x86_64 under app/src/main/jniLibs folder. You can find native files in sample under /src/main/jniLibs folder.
Check the DOC for screenshots.
This question already has answers here:
RecyclerView Single Item ID
(2 answers)
Closed 5 years ago.
I have put together some code as shown below which gets data from a JSON file hosted on a server and puts it into a RecyclcerView. This has been working fine but any way I try to add a click method it does not work. I am looking to make it so that if I click one of the rows it will tell me the country it is. I have no idea where I am going wrong but I will attach my code below which gets the JSON data and puts it into the RecyclerView.
Thanks
package com.example.curtisboylan.myapplication;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Objects;
public class MainRecycler extends AppCompatActivity {
private ArrayList countries;
private static String url = "http://curtisboylan.me/mygeek/mygeektest.php";
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
countries = new ArrayList<>();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_recycler);
initViews();
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
TextView txtView = (TextView) findViewById(R.id.textView5);
if (Objects.equals(message, "di1")){
txtView.setText("Diagnostics");
}
else if (Objects.equals(message, "screen1")){
txtView.setText("Screen Repair");
}
setTitle("Available Technicians");
}
private void initViews(){
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainRecycler.this);
pDialog.setMessage("Please Wait..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("MyGeek");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
//String email = c.getString("email");
//String address = c.getString("address");
//String gender = c.getString("gender");
// Phone node is JSON Object
// JSONObject phone = c.getJSONObject("phone");
// String mobile = phone.getString("mobile");
// String home = phone.getString("home");
// String office = phone.getString("office");
countries.add(c.getString("name"));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.hide();
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
RecyclerView.Adapter adapter = new DataAdapter(countries);
recyclerView.setAdapter(adapter);
}
}
}
Instead of adding a click listener on the Recycler view, try adding click listener in the adapter class, in the onBindViewHolder method. That is how you will get the exact item on which the click was executed.
#Override
public void onBindViewHolder(Viewholder holder, final int position) {
YourClassObject item = YourClassObjectList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Recycle Click" + position, Toast.LENGTH_SHORT).show();
}
});
Create a interface in your Adapter class
public interface EventsCatalogsAdapter{
void onClickImageCategory(Catalogs catalog);
}
Create a atribute of EventsCatalogsAdapter
private EventsCatalogsAdapter event;
Create constructor
public CatalogsAdapter(EventsCatalogsAdapter event) {
this.event = event;
}
Add setOnClickListener in onBindViewHolder
public void onBindViewHolder(final CatalogsViewHolder holder, final int position){
holder.imageCatalog.setOnClickListener(holder);
}
In you RecyclerView.ViewHolder implements onClickListener event.
class CatalogsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView imageCatalog;
private TextView tvCatalogName;
private View vLegendCatalog;
public CatalogsViewHolder(View itemView) {
super(itemView);
imageCatalog = (ImageView) itemView.findViewById(R.id.i =vCatalogItem);
tvCatalogName = (TextView)itemView.findViewById(R.id.tvCatalogName);
vLegendCatalog = itemView.findViewById(R.id.vLegendCatalog);
}
#Override
public void onClick(View v) {
event.onClickImageCategory(catalogsList.get(getAdapterPosition()));
}
}
I am developing an application in Android to post a message in users Facebook wall.Lots of examples and Links are available but the problem is that.
In My application the user will Login to his/her's Facebook accounts at the time of installation only.Then whenever he/she presses the a particular button customized Message have to be posted in Facebook wall without asking to login again.
In the available examples the login page will appear and user has to login again. help...
EDIT: i am again Clarifying My idea.My application is to post the users location into Facebook wall to get help when the user presses the Button.This is used as security application.So its not fair to login to facebook to post the message at the Time of Usage.
How to do this Please Help..
Thanks.
You should save login and password in SharedPreferences.
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString("access_token",facebook.getAccessToken());
editor.putLong("access_expires",facebook.getAccessExpires());
editor.commit();
See this for SharedPreferences
I am posting the following code, which perform login to facebook,post to facebook wall, showing profile image, showing friends list and logout.... hope you will enjoy :)
// Add this code to your MainActivity
package com.example.abc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "your app id"; // Replace with your App
// ID
ArrayList<String> friends_list;
ListView lv;
// Instance of Facebook Class
public static Facebook facebook = new Facebook(APP_ID);
public static AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
public SharedPreferences mPrefs;
SharedPreferences.Editor editor;
public static String username;
// Buttons
static Button btnFbLogin;
static Button btnFbGetProfile;
static Button btnPostToWall;
static Button btnShowFriends;
static Button btnLogout;
ArrayAdapter<String> adapter;
ImageView user_picture;
URL img_value = null;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_picture= (ImageView)findViewById(R.id.imageView1);
btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowFriends = (Button) findViewById(R.id.btn_show_friends);
btnLogout = (Button) findViewById(R.id.btn_logout);
mAsyncRunner = new AsyncFacebookRunner(facebook);
friends_list = new ArrayList<String>();
lv = (ListView) findViewById(R.id.list);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
}
});
/**
* Getting facebook Profile info
* */
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getFriends();
getProfileInformation();
}
});
/**
* Getting Friends info
* */
btnShowFriends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAsyncRunner
.request("me/friends", new FriendsRequestListener());
}
});
/**
* Posting to Facebook Wall
* */
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getFriends();
logoutFromFacebook();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
/**
* Function to login into facebook
* */
#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);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
btnShowFriends.setVisibility(View.VISIBLE);
// Making photos gallery button visible
btnLogout.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream", "user_photos", "friends_photos" },
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
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);
btnShowFriends.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnLogout.setVisibility(View.VISIBLE);
getprofilepic();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Get Profile information by making request to Facebook Graph API
* */
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
username = profile.getString("username");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + username + "\nEmail: " + email,
Toast.LENGTH_LONG).show();
}
});
} 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) {
}
});
}
/**
* Function to post to facebook wall
* */
#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() {
}
});
}
/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();
Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
public void logout() {
if (mPrefs != null) {
editor.remove("access_token");
editor.remove("access_expires");
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
private class FriendsRequestListener implements RequestListener {
String friendData;
// Method runs when request is complete
public void onComplete(String response, Object state) {
Log.v("", "FriendListRequestONComplete");
// Create a copy of the response so i can be read in the run()
// method.
friendData = response;
Log.v("friendData--", "" + friendData);
// Create method to run on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
// Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
// Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
Log.v("friendArray--", "" + friendArray);
for (int i = 0; i < friendArray.length(); i++) {
JSONObject frnd_obj = friendArray.getJSONObject(i);
friends_list.add("Name:"+frnd_obj.getString("name") + " ID:"
+ frnd_obj.getString("id"));
}
adapter = new ArrayAdapter<String>(
getBaseContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1, friends_list);
lv.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(final String response, Object state) {
Thread timer = new Thread() { //new thread
public void run() {
Boolean b = true;
try {
editor.remove("access_token");
editor.commit();
sleep(500);
Log.d("Logout from Facebook", response);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowFriends.setVisibility(View.INVISIBLE);
btnLogout.setVisibility(View.INVISIBLE);
adapter.clear();
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "You are logged out from Facebook", Toast.LENGTH_LONG).show();
}
});
while (b == true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
};
};
timer.start();
}
#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) {
}
});
}
#SuppressWarnings("deprecation")
public void getprofilepic(){
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
final JSONObject profile = new JSONObject(json);
runOnUiThread(new Runnable() {
#Override
public void run() {
// getting name of the user
try {
username = profile.getString("username");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
img_value = new
URL("https://graph.facebook.com/"+username+"/picture?type=normal");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap mIcon1 = null;
try {
mIcon1 =
BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
user_picture.setImageBitmap(mIcon1);
}
});
} 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) {
}
});
}
}
////
This code to activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn_fblogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Login with Facebook" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_fb_post_to_wall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Post to Wall"
android:visibility="gone" />
<Button
android:id="#+id/btn_get_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Get Profile Data"
android:visibility="gone" />
<Button
android:id="#+id/btn_show_friends"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Show Friends"
android:visibility="gone" />
<Button
android:id="#+id/btn_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Logout"
android:visibility="gone" />
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
/// And add Mainfest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.abc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:name="com.example.abc.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</application>
</manifest>
i want to add profile pictures of friends in a list view along with their names. i am using the code which gives me friends name in list view. but i don't know how to show their profile pictures.i have used a login button and on its click event friends list will open. can anybody please tell.? here is the code that i have used
public class LoginActivity extends Activity{
public static final String APP_ID = "*************";
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private ProgressDialog mProgress;
private Handler mHandler = new Handler();
private ProgressDialog mSpinner;
private Handler mRunOnUi = new Handler();
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public static ArrayList<String> friends ;
String _error;
public byte[] picture;
public Bitmap pictureBitmap;
TextView tv;
Button loginButton;
private UiLifecycleHelper uiHelper;
private ContextWrapper uiActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.login);
friends= new ArrayList<String>();
tv=(TextView)LoginActivity.this.findViewById(R.id.textview1);
loginButton=(Button)findViewById(R.id.button_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (! facebook.isSessionValid()) {
facebook.authorize(LoginActivity.this, PERMISSIONS, new LoginDialogListener());
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FB Demo App", "onActivityResult(): " + requestCode);
facebook.authorizeCallback(requestCode, resultCode, data);
}
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
getAlbumsData task = new getAlbumsData();
task.execute();
mHandler.post(new Runnable() {
public void run() {
mAsyncRunner.request("me/friends", new FriendsRequestListener());
}
});
}
private void saveCredentials(Facebook facebook) {
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
}
}
public void showToast(String string) {
}
public class getAlbumsData {
public void execute() {
} }
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.v("", "FriendListRequestONComplete");
friendData = response;
Log.v("friendData--", ""+friendData);
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
JSONArray friendArray = json.getJSONArray("data");
Log.v("friendArray--", ""+friendArray);
for(int i = 0; i< friendArray.length(); i++) {
JSONObject frnd_obj = friendArray.getJSONObject(i);
friends.add(frnd_obj.getString("name"));
}
Intent ide = new Intent(LoginActivity.this,FrndActivity.class);
ide.putStringArrayListExtra("friends", friends);
startActivity(ide);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
You have to show your friend's profile picture with URL only.
You have to use only URL for showing your frnds profile picture.(This facility is given by Facebook)
you can show your friend's profile picture with Lazy Loading ..
Code::::
package com.facebook.me;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.FacebookError;
import com.facebook.lazylist.Friend_List_Lazy_Loading;
public class Friend_list extends Activity
{
public static final String DATA = "data";
public static final String NAME = "name";
public static final String FB_ID = "id";
public static final String PICTURE = "picture";
public static final String URL = "url";
Friend_List_Bean friendBean;
ArrayList<Friend_List_Bean> aryFriendList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.friend_list);
aryFriendList = new ArrayList<Friend_List_Bean>();
getFriendList();
}
private void getFriendList()
{
Bundle param = new Bundle();
param.putString("fields", "name, picture");
AsyncFacebookRunner async = new AsyncFacebookRunner(MainActivity.facebook);
async.request("me/friends", param, new RequestListener()
{
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
#Override
public void onComplete(String response, Object state)
{
Log.d("response : ", ""+response);
parseContact(response);
}
},null);
}
public void parseContact(String response)
{
try
{
JSONObject objResponse = new JSONObject(response);
JSONArray contact = objResponse.getJSONArray(DATA);
Log.d("Total Friends", " : "+contact.length());
for(int i=0;i<contact.length();i++)
{
friendBean = new Friend_List_Bean();
JSONObject objData = contact.getJSONObject(i);
Log.d("", ""+objData.getString(FB_ID));
Log.d("", ""+objData.getString(NAME));
Log.d("", ""+objData.getString(PICTURE));
JSONObject objJsonPicture = objData.getJSONObject(PICTURE);
JSONObject objJsonPictureData = objJsonPicture.getJSONObject(DATA);
Log.d("", ""+objJsonPictureData.getString(URL));
friendBean.setFbId(objData.getString(FB_ID));
friendBean.setName(objData.getString(NAME));
friendBean.setPictureUrl(objJsonPictureData.getString(URL));
aryFriendList.add(friendBean);
}
Intent i = new Intent(Friend_list.this, Friend_List_Lazy_Loading.class);
i.putExtra("aryFriendList", aryFriendList);
startActivity(i);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
BEAN:::::
package com.facebook.me;
import java.io.Serializable;
public class Friend_List_Bean implements Serializable
{
public String fbId;
public String name;
public String pictureUrl;
public String getFbId()
{
return fbId;
}
public void setFbId(String fbId)
{
this.fbId = fbId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPictureUrl()
{
return pictureUrl;
}
public void setPictureUrl(String pictureUrl)
{
this.pictureUrl = pictureUrl;
}
}
Friend_List_Lazy_Loading.class:::
package com.facebook.lazylist;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;
import com.facebook.me.Friend_List_Bean;
import com.facebook.me.Post_on_Friend;
import com.facebook.me.R;
public class Friend_List_Lazy_Loading extends Activity implements OnItemClickListener {
ListView list;
GridView gv;
LazyAdapter adapter;
GridViewLazyAdapter gridViewLazyAdapter;
ArrayList<Friend_List_Bean> aryFriendList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// aryFriendList = new ArrayList<Friend_List_Bean>();
list=(ListView)findViewById(R.id.list);
Intent intent=getIntent();
aryFriendList=(ArrayList<Friend_List_Bean>)intent.getSerializableExtra("aryFriendList");
adapter=new LazyAdapter(this, aryFriendList);
gridViewLazyAdapter=new GridViewLazyAdapter(this, aryFriendList);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
gv = (GridView) findViewById(R.id.grid_id);
gv.setAdapter(gridViewLazyAdapter);
gv.setOnItemClickListener(this);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
Button btnViewGalary=(Button)findViewById(R.id.btnViewGalary);
btnViewGalary.setOnClickListener(listenerBtnViewGalary);
Button btnThumbnail=(Button)findViewById(R.id.btnThumbnail);
btnThumbnail.setOnClickListener(listenerBtnThumbnail);
list.setVisibility(View.VISIBLE);
}
#Override
public void onDestroy()
{
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0)
{
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public OnClickListener listenerBtnViewGalary=new OnClickListener(){
#Override
public void onClick(View arg0)
{
list.setVisibility(View.GONE);
gv.setVisibility(View.VISIBLE);
}
};
public OnClickListener listenerBtnThumbnail=new OnClickListener(){
#Override
public void onClick(View arg0)
{
gv.setVisibility(View.GONE);
list.setVisibility(View.VISIBLE);
}
};
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
if(arg1 == list)
{
Toast.makeText(this, aryFriendList.get(arg2).getFbId(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(Friend_List_Lazy_Loading.this, Post_on_Friend.class);
i.putExtra("id", ""+aryFriendList.get(arg2).getFbId());
startActivity(i);
}
else
{
Toast.makeText(this, ""+aryFriendList.get(arg2).getFbId(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(Friend_List_Lazy_Loading.this, Post_on_Friend.class);
i.putExtra("id", aryFriendList.get(arg2).getFbId());
startActivity(i);
}
}
}
I am developing a Facebook Android integration using the below code, but once I log-in through this app then it does not logout from facebook even if I logout from Facebook app or browser both from my device. So this android app can still post on my Facebook wall. How do I logout from this app if I logout from my facebook app or facebook on browser.
package com.facebook.androidhive;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
public class AndroidFacebookConnectActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "APP_ID"; // Replace with your App ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAsyncRunner = new AsyncFacebookRunner(facebook);
loginToFacebook();
postToWall();
}
/**
* Function to login into facebook
* */
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);
Log.d("FB Sessions", "" + 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
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Function to post to facebook wall
* */
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() {
}
});
}
/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, 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() {
}
});
}
}
#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) {
}
});
}
}
You can't force a logout from your app if you logout of the Facebook app, at least no API that we support with our SDK.
In theory, you could find a way to attach some sort of uninstall intent or to parse logs for any messages regarding facebook logout, but it generally is not recommended as best practice to force a logout of another app when another app logs out (its not intuitive to the user that this is going to happen).
try remove this code
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}