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.
Related
I am new to Agora.io and I am creating an android app for 1 to 1 video calling. Everything is working fine in my app - I can join/leave the channel and even see my own local image through my camera. However, in the call, only the audio is being transmitted and video is not being transmitted.
When I debug the app, I can see that the event 'onFirstRemoteVideoFrame' is not being triggered. I tried changing it to 'onFirstRemoteVideoDecoded'(which I saw in many tutorials but android studio says the method is depreciated) but it is still not working.
Also, please note that when I add the line '-keep class io.agora.**{;}' in my proguard-rules.pro file, it says that it can't find the class. So instead I am using '-keep class io.agora.{*;}'.
Below is the java code for my activity. I am using agora 3.1.3.
package com.guideu.helloagora;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;
public class MainActivity extends AppCompatActivity {
private static final String TAG=MainActivity.class.getSimpleName();
private static final int PERMISSION_REQ_ID=22;
private static final String[] REQUESTED_PERMISSIONS={
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private RtcEngine mRtcEngine; // Agora engine reference
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private SurfaceView mLocalView;
private SurfaceView mRemoteView;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
private boolean mCallEnd;
private boolean mMuted;
//Agora engine event handler
private final IRtcEngineEventHandler mRTCHandler=new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
super.onJoinChannelSuccess(channel, uid, elapsed);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("agora","Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
super.onUserOffline(uid, reason);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("agora","User offline, uid: " + (uid & 0xFFFFFFFFL));
removeRemoteView();
}
});
}
#Override
public void onFirstRemoteVideoFrame(final int uid, int width, int height, int elapsed) {
super.onFirstRemoteVideoFrame(uid, width, height, elapsed);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("agora","First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
if(checkSelfPermission(REQUESTED_PERMISSIONS[0],PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1],PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[2],PERMISSION_REQ_ID)){
//init engine
initEngineAndJoinChannel();
}
}
#Override
protected void onDestroy(){
super.onDestroy();
if(!mCallEnd){
leaveChannel();
}
RtcEngine.destroy();
}
private void initUI(){
mLocalContainer=findViewById(R.id.local_video_view_container);
mRemoteContainer=findViewById(R.id.remote_video_view_container);
mCallBtn=findViewById(R.id.btn_call);
mMuteBtn=findViewById(R.id.btn_mute);
mSwitchCameraBtn=findViewById(R.id.btn_switch_camera);
}
private void initEngineAndJoinChannel(){
//initialize engine
initializeEngine();
//setup video config
setupVideoConfig();
//setup local video
setupLocalVideo();
//join channel
joinChannel();
}
private void initializeEngine(){
try {
mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRTCHandler);
}
catch (Exception e){
Log.e(TAG,Log.getStackTraceString(e));
throw new RuntimeException("Need to check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
}
private void setupVideoConfig(){
mRtcEngine.enableVideo();
mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT
));
}
private void setupLocalVideo(){
mRtcEngine.enableVideo();
mLocalView=RtcEngine.CreateRendererView(getBaseContext());
mLocalView.setZOrderMediaOverlay(true);
mLocalContainer.addView(mLocalView);
VideoCanvas localVideoCanvas=new VideoCanvas(mLocalView,VideoCanvas.RENDER_MODE_HIDDEN,0);
mRtcEngine.setupLocalVideo(localVideoCanvas);
}
private void setupRemoteVideo(int uid){
/*int count=mRemoteContainer.getChildCount();
View view=null;
for(int i=0;i<count;i++){
View v=mRemoteContainer.getChildAt(i);
if(v.getTag() instanceof Integer && ((int) v.getTag())==uid){
view=v;
}
}
if(view!=null){
return;
}*/
mRemoteView=RtcEngine.CreateRendererView(getBaseContext());
mRemoteContainer.addView(mRemoteView);
mRtcEngine.setupRemoteVideo(new VideoCanvas(mRemoteView,VideoCanvas.RENDER_MODE_HIDDEN,uid));
mRemoteView.setTag(uid);
}
private void removeRemoteView(){
if(mRemoteView!=null){
mRemoteContainer.removeView(mRemoteView);
}
mRemoteView=null;
}
private void joinChannel(){
String token=getString(R.string.agora_access_token);
if(TextUtils.isEmpty(token)){
token=null;
}
mRtcEngine.joinChannel(token,"HelloAgora","",0);
}
private void leaveChannel(){
mRtcEngine.leaveChannel();
}
public void onLocalAudioMuteClicked(View view){
mMuted=!mMuted;
mRtcEngine.muteLocalAudioStream(mMuted);
int res=mMuted?R.drawable.btn_mutecall:R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
public void onSwitchCameraClicked(View view){
mRtcEngine.switchCamera();
}
public void onCallClicked(View view){
if(mCallEnd){
startCall();
mCallEnd=false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
}
else{
endCall();
mCallEnd=true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButtons(!mCallEnd);
}
private void startCall(){
setupLocalVideo();
joinChannel();
}
private void endCall(){
removeLocalVideo();
removeRemoteView();
leaveChannel();
}
private void removeLocalVideo(){
if(mLocalView!=null){
mLocalContainer.removeView(mLocalView);
}
mLocalView=null;
}
private void showButtons(boolean show){
int visibility=show?View.VISIBLE:View.GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
private boolean checkSelfPermission(String permission, int requestCode){
if(ContextCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,REQUESTED_PERMISSIONS,requestCode);
Toast.makeText(this,"No Permission",Toast.LENGTH_LONG);
return false;
}
return true;
}
}
'''
You can try "onRemoteVideoStateChanged" callback instead of "onFirstRemoteVideoFrame".
Here is the code snippet:
#Override
public void onRemoteVideoStateChanged(final int uid, int state, int reason, int elapsed) {
super.onRemoteVideoStateChanged(uid, state, reason, elapsed);
if (state == Constants.REMOTE_VIDEO_STATE_STARTING) {
runOnUiThread(new Runnable() {
#Override
public void run() {
setupRemoteVideo(uid);
}
});
}
}
The code is posted here and the app crashes when the login button is clicked with null pointer exception at homefragment on click.im a beginer.please help.logcat http://postimg.org/image/6d1qyszkd/
simple facebook class basically is :
public SimpleFacebook()
{
mSessionStatusCallback = new SessionStatusCallback();
}
public static void initialize(Activity activity)
{
if (mInstance == null)
{
mInstance = new SimpleFacebook();
}
mActivity = activity;
}
public static SimpleFacebook getInstance(Activity activity)
{
if (mInstance == null)
{
mInstance = new SimpleFacebook();
}
mActivity = activity;
return mInstance;
}
public static SimpleFacebook getInstance()
{
return mInstance;
}
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.GetDataCallback;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.Properties;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnFriendsRequestListener;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebook.OnLogoutListener;
import com.sromku.simple.fb.SimpleFacebook.OnProfileRequestListener;
import com.sromku.simple.fb.entities.Profile;
import com.sromku.simple.fb.example.utils.Utils;
import com.sromku.simple.fb.utils.Attributes;
import com.sromku.simple.fb.utils.PictureAttributes;
import com.sromku.simple.fb.utils.PictureAttributes.PictureType;
public class HomeFragment extends Fragment {
protected static final String TAG = HomeFragment.class.getName();
private SimpleFacebook mSimpleFacebook;
ProgressDialog mProgress;
Button mButtonLogin;
Button mButtonLogout;
TextView mTextStatus;
// Login listener
private OnLoginListener mOnLoginListener = new OnLoginListener()
{
#Override
public void onFail(String reason)
{
mTextStatus.setText(reason);
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable)
{
mTextStatus.setText("Exception: " + throwable.getMessage());
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
mTextStatus.setText("Thinking...");
}
#Override
public void onLogin()
{
// change the state of the button or do whatever you want
mTextStatus.setText("Logged in");
loggedInUIState();
toast("You are logged in");
}
#Override
public void onNotAcceptingPermissions()
{
toast("You didn't accept read permissions");
}
};
// Logout listener
private OnLogoutListener mOnLogoutListener = new OnLogoutListener()
{
#Override
public void onFail(String reason)
{
mTextStatus.setText(reason);
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable)
{
mTextStatus.setText("Exception: " + throwable.getMessage());
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
mTextStatus.setText("Thinking...");
}
#Override
public void onLogout()
{
// change the state of the button or do whatever you want
mTextStatus.setText("Logged out");
loggedOutUIState();
toast("You are logged out");
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homend_home_fragment, container, false);
// test local language
Utils.updateLanguage(getActivity(), "en");
Utils.printHashKey(getActivity());
mButtonLogin = (Button)rootView.findViewById(R.id.button_login);
mButtonLogout = (Button)rootView.findViewById(R.id.button_logout);
mTextStatus = (TextView)rootView.findViewById(R.id.text_status);
mButtonLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
mSimpleFacebook.login(mOnLoginListener);
}
});
// 2. Logout example
mButtonLogout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
mSimpleFacebook.logout(mOnLogoutListener);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
mSimpleFacebook.onActivityResult(getActivity(), requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
private void setUIState()
{
if (mSimpleFacebook.isLogin())
{
loggedInUIState();
}
else
{
loggedOutUIState();
}
}
/**
* Show toast
*
* #param message
*/
private void toast(String message)
{
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private void loggedInUIState()
{
mButtonLogin.setEnabled(false);
mButtonLogout.setEnabled(true);
mTextStatus.setText("Logged in");
}
private void loggedOutUIState()
{
mButtonLogin.setEnabled(true);
mButtonLogout.setEnabled(false);
mTextStatus.setText("Logged out");
}
private void showDialog()
{
mProgress = ProgressDialog.show(getActivity(), "Thinking",
"Waiting for Facebook", true);
}
private void hideDialog()
{
mProgress.hide();
}
public class OnProfileRequestAdapter implements OnProfileRequestListener
{
#Override
public void onThinking()
{
}
#Override
public void onException(Throwable throwable)
{
}
#Override
public void onFail(String reason)
{
}
#Override
public void onComplete(Profile profile)
{
}
}
}
I think problem might be here. You have just declared your variable
private SimpleFacebook mSimpleFacebook;
you haven't initialized that variable so you got NPE
So initialized it on onCreateView() method.
mSimpleFacebook = SimpleFacebook.getInstance(getActivity());
And yet you get error then you need to finally change
mSimpleFacebook = SimpleFacebook.getInstance();
Add this line to manifest file..
<activity android:name="com.facebook.LoginActivity" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation">
</activity>
which would be finally works for you.!!
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);
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 trying to get the Android TTS API to read my "utterance" and then call the onUtteranceCompleted() listener unsuccessfully. I've registered my TTS object and it returns SUCCESS, so I can't figure out for the life of me why my callback isn't getting called.
I've tried searching for help, but it seems others have difficulty with this too. Am I missing something simple?
Thanks for any help you can offer.
package com.test.mytts;
import java.util.HashMap;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyTTS extends Activity implements OnInitListener, OnUtteranceCompletedListener
{
TextView tv;
private TextToSpeech _tts;
#Override
public void onCreate(Bundle savedInstanceState)
{
tv = new TextView(this);
tv.setText("MyTTS: ");
super.onCreate(savedInstanceState);
setContentView(tv);
_tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int status)
{
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "test");
if (status == TextToSpeech.SUCCESS)
{
Toast.makeText(this, "Trying to speak...", Toast.LENGTH_SHORT).show();
int result = _tts.setOnUtteranceCompletedListener(this);
tv.append(String.valueOf(result));
_tts.setSpeechRate((float) .5);
_tts.speak("Testing one, two, three", TextToSpeech.QUEUE_ADD, myHashAlarm);
}
else
Toast.makeText(this, "Failed to initialize TTS.", Toast.LENGTH_SHORT).show();
}
#Override
public void onUtteranceCompleted(String utteranceId)
{
Toast.makeText(this, "onUtteranceCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy()
{
super.onDestroy();
_tts.shutdown();
}
}
Call the setOnUtteranceCompletedListener inside the onInit function of the tts object.
If you want to make any changes to the UI on the call of the onUtteranceCompleted function, add the code inside a runOnUIThread method.
And do remember to add the Hashmap param value while calling the speak() function
Example :
TextToSpeech tts= new TextToSpeech(context, new OnInitListener() {
#Override
public void onInit(int status) {
mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
#Override
public void onUtteranceCompleted(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//UI changes
}
});
}
});
}
});
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");
tts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params);
I believe that unless you specify an utterance with an id, like:
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceid);
your utterance completed method will not be called.
in this case, map is the Hashmap you pass to the engine when you speak.
this will work for you on API Level >=15
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnInitListener{
private static final int CHECK_TTS_DATA = 0X123;
protected static final String TAG = MainActivity.class.getSimpleName();
private TextToSpeech textToSpeech;
private Button buttonSayIt;
private EditText editTextTts;
String tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSayIt=(Button) findViewById(R.id.buttonSayIt);
editTextTts=(EditText) findViewById(R.id.editTextTts);
buttonSayIt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts=editTextTts.getText().toString();
Log.d(TAG, tts);
speach(tts,"you_utterance_id");
}
});
//check for TTs data
Intent checkTtsDataIntent=new Intent();
checkTtsDataIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTtsDataIntent, CHECK_TTS_DATA);
}
protected void speach(String tts,String utteranceId) {
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,utteranceId);
textToSpeech.speak(tts,TextToSpeech.QUEUE_FLUSH,params);
}
#Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
if(textToSpeech.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE){
textToSpeech.setLanguage(Locale.US);
}
}else if(status==TextToSpeech.ERROR){
Toast.makeText(this, "Sorry Text To Speach faild", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==CHECK_TTS_DATA){
if(resultCode==TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
textToSpeech=new TextToSpeech(this, this);
textToSpeech.setOnUtteranceProgressListener(utteranceProgressListener);
}else{
Intent installTtsIntent=new Intent();
installTtsIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTtsIntent);
}
}
}
UtteranceProgressListener utteranceProgressListener=new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.d(TAG, "onStart ( utteranceId :"+utteranceId+" ) ");
}
#Override
public void onError(String utteranceId) {
Log.d(TAG, "onError ( utteranceId :"+utteranceId+" ) ");
}
#Override
public void onDone(String utteranceId) {
Log.d(TAG, "onDone ( utteranceId :"+utteranceId+" ) ");
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
in case anybody is still finding it difficult
Code Snippet
textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status==TextToSpeech.SUCCESS){
int result=textToSpeech.setLanguage(Locale.ENGLISH);
if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.i("TextToSpeech","Language Not Supported");
}
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.i("TextToSpeech","On Start");
}
#Override
public void onDone(String utteranceId) {
Log.i("TextToSpeech","On Done");
}
#Override
public void onError(String utteranceId) {
Log.i("TextToSpeech","On Error");
}
});
}else {
Log.i("TextToSpeech","Initialization Failed");
}
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED);
}