Facebook friendliest is not retrieving - android

I am using the scrumptious documentation to show to those friends who are using my application. I have followed the tutorials here
https://developers.facebook.com/docs/android/scrumptious/show-friends?locale=en_GB
I have tried every combination but it is not retrieving the friends who are using my application
I have used three class
scrumptious.java
public class ScrumptiousApplication extends Application {
private List<GraphUser> selectedUsers;
public List<GraphUser> getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(List<GraphUser> selectedUsers) {
this.selectedUsers = selectedUsers;
}
}
Selectionfragment.java
package com.example.facebooknew;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.internal.SessionTracker;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class SelectionFragment extends Fragment{
/* In this fragment the data from the user profile is returned like profile , name etc
* (non-Javadoc)
* #see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
private static final String TAG = "SelectionFragment";
private static final List<String> PERMISSIONS = Arrays.asList(
"email","user_location");
private static final int REAUTH_ACTIVITY_CODE = 100;
private ProfilePictureView profilePictureView;
private TextView userNameView;
private TextView firstName;
private TextView lastName;
private TextView Location;
private UiLifecycleHelper uiHelper;
private List<GraphUser> selectedUsers;
private ListView listView;
private List<BaseListElement> listElements;
private static final String FRIENDS_KEY = "friends";
private TextView userInfoTextView;
private Button sendRequestButton;
private String requestId;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Check for an incoming notification. Save the info
Uri intentUri = getActivity().getIntent().getData();
if (intentUri != null) {
String requestIdParam = intentUri.getQueryParameter("request_ids");
if (requestIdParam != null) {
String array[] = requestIdParam.split(",");
requestId = array[0];
Log.i(TAG, "Request id: "+requestId);
Toast.makeText(getActivity().getApplicationContext(),requestId, Toast.LENGTH_LONG).show();
}
}
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection, container, false);
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
firstName= (TextView) view.findViewById(R.id.selection_first_name);
//lastName = (TextView) view.findViewById(R.id.selection_last_name);
//Location = (TextView) view.findViewById(R.id.selection_location);
//userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
sendRequestButton=(Button) view.findViewById(R.id.sendRequestButton);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
sendRequestButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendRequestDialog();
}
});
// Find the list view
listView = (ListView) view.findViewById(R.id.selection_list);
// Set up the list view items, based on a list of
// BaseListElement items
listElements = new ArrayList<BaseListElement>();
// Add an item for the friend picker
listElements.add(new PeopleListElement(0));
// Set the list view adapter
listView.setAdapter(new ActionListAdapter(getActivity(),
R.id.selection_list, listElements));
if (savedInstanceState != null) {
// Restore the state for each list element
for (BaseListElement listElement : listElements) {
listElement.restoreState(savedInstanceState);
}
}
return view;
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
//firstName.setText(user.getFirstName());
//lastName.setText(user.getLastName());
//Location.setText(user.getProperty("email").toString());
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
} else if (resultCode == Activity.RESULT_OK) {
// Do nothing for now
}else if (resultCode == Activity.RESULT_OK &&
requestCode >= 0 && requestCode < listElements.size()) {
listElements.get(requestCode).onActivityResult(data);
}
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
if (state.isOpened() && requestId != null) {
getRequestData(requestId);
}
if (state.isOpened()) {
sendRequestButton.setVisibility(View.VISIBLE);
} else if (state.isClosed()) {
sendRequestButton.setVisibility(View.INVISIBLE);
}
makeMeRequest(session);
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
for (BaseListElement listElement : listElements) {
listElement.onSaveInstanceState(bundle);
}
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private interface MyGraphLanguage extends GraphObject {
// Getter for the ID field
String getId();
// Getter for the Name field
String getName();
}
private class ActionListAdapter extends ArrayAdapter<BaseListElement> {
private List<BaseListElement> listElements;
public ActionListAdapter(Context context, int resourceId,
List<BaseListElement> listElements) {
super(context, resourceId, listElements);
this.listElements = listElements;
// Set up as an observer for list item changes to
// refresh the view.
for (int i = 0; i < listElements.size(); i++) {
listElements.get(i).setAdapter(this);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater =
(LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listitem, null);
}
BaseListElement listElement = listElements.get(position);
if (listElement != null) {
view.setOnClickListener(listElement.getOnClickListener());
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text2);
if (icon != null) {
icon.setImageDrawable(listElement.getIcon());
}
if (text1 != null) {
text1.setText(listElement.getText1());
}
if (text2 != null) {
text2.setText(listElement.getText2());
}
else{
Toast.makeText(getActivity().getApplicationContext(),"No data received " ,Toast.LENGTH_LONG).show();
}
}
return view;
}
}
/* It is private class used to populate the friend and bring up the friends list*/
private class PeopleListElement extends BaseListElement {
public PeopleListElement(int requestCode) {
super(getActivity().getResources().getDrawable(R.drawable.add_friends),
getActivity().getResources().getString(R.string.action_people),
getActivity().getResources().getString(R.string.action_people_default),
requestCode);
}
/* this event will trigger the picker activity*/
#Override
protected View.OnClickListener getOnClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do nothing for now
startPickerActivity(PickerActivity.FRIEND_PICKER, getRequestCode());
}
};
}
private void setUsersText() {
String text = null;
if (selectedUsers != null) {
// If there is one friend
if (selectedUsers.size() == 1) {
text = String.format(getResources()
.getString(R.string.single_user_selected),
selectedUsers.get(0).getName());
} else if (selectedUsers.size() == 2) {
// If there are two friends
text = String.format(getResources()
.getString(R.string.two_users_selected),
selectedUsers.get(0).getName(),
selectedUsers.get(1).getName());
} else if (selectedUsers.size() > 2) {
// If there are more than two friends
text = String.format(getResources()
.getString(R.string.multiple_users_selected),
selectedUsers.get(0).getName(),
(selectedUsers.size() - 1));
}
}
if (text == null) {
// If no text, use the placeholder text
text = getResources()
.getString(R.string.action_people_default);
}
// Set the text in list element. This will notify the
// adapter that the data has changed to
// refresh the list view.
setText2(text);
}
#Override
protected void onActivityResult(Intent data) {
selectedUsers = ((ScrumptiousApplication) getActivity()
.getApplication())
.getSelectedUsers();
setUsersText();
notifyDataChanged();
}
#Override
protected void onSaveInstanceState(Bundle bundle) {
if (selectedUsers != null) {
bundle.putByteArray(FRIENDS_KEY,
getByteArray(selectedUsers));
}
}
private byte[] getByteArray(List<GraphUser> users) {
// convert the list of GraphUsers to a list of String
// where each element is the JSON representation of the
// GraphUser so it can be stored in a Bundle
List<String> usersAsString = new ArrayList<String>(users.size());
for (GraphUser user : users) {
usersAsString.add(user.getInnerJSONObject().toString());
}
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
new ObjectOutputStream(outputStream).writeObject(usersAsString);
return outputStream.toByteArray();
} catch (IOException e) {
Log.e(TAG, "Unable to serialize users.", e);
}
return null;
}
private List<GraphUser> restoreByteArray(byte[] bytes) {
try {
#SuppressWarnings("unchecked")
List<String> usersAsString =
(List<String>) (new ObjectInputStream
(new ByteArrayInputStream(bytes)))
.readObject();
if (usersAsString != null) {
List<GraphUser> users = new ArrayList<GraphUser>
(usersAsString.size());
for (String user : usersAsString) {
GraphUser graphUser = GraphObject.Factory
.create(new JSONObject(user),
GraphUser.class);
users.add(graphUser);
}
return users;
}
} catch (ClassNotFoundException e) {
Log.e(TAG, "Unable to deserialize users.", e);
} catch (IOException e) {
Log.e(TAG, "Unable to deserialize users.", e);
} catch (JSONException e) {
Log.e(TAG, "Unable to deserialize users.", e);
}
return null;
}
#Override
protected boolean restoreState(Bundle savedState) {
byte[] bytes = savedState.getByteArray(FRIENDS_KEY);
if (bytes != null) {
selectedUsers = restoreByteArray(bytes);
setUsersText();
return true;
}
return false;
}
}
/* This function is responsible for launching the freind picker activity*/
private void startPickerActivity(Uri data, int requestCode) {
Intent intent = new Intent();
intent.setData(data);
intent.setClass(getActivity(), PickerActivity.class);
startActivityForResult(intent, requestCode);
}
public void facebookSession(Session session){
//session= Session.getActiveSession();
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("basic_info","email","location"));
request.setCallback( new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Toast.makeText(SelectionFragment.this.getActivity(), "User email is:"+user.getProperty("email"), Toast.LENGTH_SHORT).show(); }
else {
Toast.makeText(SelectionFragment.this.getActivity(), "Error User Null", Toast.LENGTH_SHORT).show();
}
}
}).executeAsync();
}
}
}); //end of call;
session.openForRead(request); //now do the request above
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message", "Learn how to make your Android apps social");
params.putString("data",
"https://play.google.com/store/apps/details?id=de.j4velin.mapsmeasure&hl=en");
WebDialog requestsDialog = (
new WebDialog.RequestsDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
Toast.makeText(getActivity().getApplicationContext(),
"Request cancelled",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Network Error",
Toast.LENGTH_SHORT).show();
}
} else {
final String requestId = values.getString("request");
if (requestId != null) {
Toast.makeText(getActivity().getApplicationContext(),
"Request sent",
Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity().getApplicationContext(), requestId, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Request cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
})
.build();
requestsDialog.show();
}
private void getRequestData(final String inRequestId) {
// Create a new request for an HTTP GET with the
// request ID as the Graph path.
Request request = new Request(Session.getActiveSession(),
inRequestId, null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Process the returned response
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
// Default message
String message = "Incoming request";
if (graphObject != null) {
// Check if there is extra data
if (graphObject.getProperty("data") != null) {
try {
// Get the data, parse info to get the key/value info
JSONObject dataObject =
new JSONObject((String)graphObject.getProperty("data"));
// Get the value for the key - badge_of_awesomeness
String badge =
dataObject.getString("badge_of_awesomeness");
// Get the value for the key - social_karma
String karma =
dataObject.getString("social_karma");
// Get the sender's name
JSONObject fromObject =
(JSONObject) graphObject.getProperty("from");
String sender = fromObject.getString("name");
String title = sender+" sent you a gift";
// Create the text for the alert based on the sender
// and the data
message = title + "\n\n" +
"Badge: " + badge +
" Karma: " + karma;
} catch (JSONException e) {
message = "Error getting request info";
}
} else if (error != null) {
message = "Error getting request info";
}
}
Toast.makeText(getActivity().getApplicationContext(),
message,
Toast.LENGTH_LONG).show();
}
});
// Execute the request asynchronously.
Request.executeBatchAsync(request);
}
}
And I have an abstarct baselist element class

Related

ArrayList shows only single item in RecyclerView

I'm trying to get all the user chats (created in my database) using an ArrayList and Recyclerview.Adapter but only first item from my ArrayList is being shown on my emulator screen.
Here's the corresponding code:
MainActivity:
package com.wipro.chat.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.wipro.chat.R;
import com.wipro.chat.adapter.ChatRoomsAdapter;
import com.wipro.chat.app.Config;
import com.wipro.chat.app.EndPoints;
import com.wipro.chat.app.MyApplication;
import com.wipro.chat.gcm.GcmIntentService;
import com.wipro.chat.gcm.NotificationUtils;
import com.wipro.chat.helper.SimpleDividerItemDecoration;
import com.wipro.chat.model.ChatRoom;
import com.wipro.chat.model.Message;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private ArrayList<ChatRoom> chatRoomArrayList;
private ChatRoomsAdapter mAdapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Check for login session. If not logged in launch
* login activity
* */
if (MyApplication.getInstance().getPrefManager().getUser() == null) {
launchLoginActivity();
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
/**
* Broadcast receiver calls in two scenarios
* 1. gcm registration is completed
* 2. when new push notification is received
* */
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
// gcm successfully registered
// now subscribe to `global` topic to receive app wide notifications
subscribeToGlobalTopic();
} else if (intent.getAction().equals(Config.SENT_TOKEN_TO_SERVER)) {
// gcm registration id is stored in our server's MySQL
Log.e(TAG, "GCM registration id is sent to our server");
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
handlePushNotification(intent);
}
}
};
chatRoomArrayList = new ArrayList<>();
mAdapter = new ChatRoomsAdapter(this, chatRoomArrayList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
getApplicationContext()
));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new ChatRoomsAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new ChatRoomsAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
// when chat is clicked, launch full chat thread activity
ChatRoom userChatRoom = chatRoomArrayList.get(position);
Intent intent = new Intent(MainActivity.this, ChatRoomActivity.class);
intent.putExtra("user_id", userChatRoom.getId());
intent.putExtra("name", userChatRoom.getName());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
/**
* Always check for google play services availability before
* proceeding further with GCM
* */
if (checkPlayServices()) {
registerGCM();
fetchChatRooms();
}
}
/**
* Handles new push notification
*/
private void handlePushNotification(Intent intent) {
/*int type = intent.getIntExtra("type", -1);
// if the push is of chat room message
// simply update the UI unread messages count
if (type == Config.PUSH_TYPE_CHATROOM) {
Message message = (Message) intent.getSerializableExtra("message");
String chatRoomId = intent.getStringExtra("chat_room_id");
if (message != null && chatRoomId != null) {
updateRow(chatRoomId, message);
}
} else if (type == Config.PUSH_TYPE_USER) {
// push belongs to user alone
// just showing the message in a toast
Message message = (Message) intent.getSerializableExtra("message");
Toast.makeText(getApplicationContext(), "New push: " + message.getMessage(), Toast.LENGTH_LONG).show();
}*/
Message message = (Message) intent.getSerializableExtra("message");
String userChatRoomId = intent.getStringExtra("user_id");
if (message != null && userChatRoomId != null) {
updateRow(userChatRoomId, message);
}
}
/**
* Updates the chat list unread count and the last message
*/
private void updateRow(String chatRoomId, Message message) {
for (ChatRoom cr : chatRoomArrayList) {
if (cr.getId().equals(chatRoomId)) {
int index = chatRoomArrayList.indexOf(cr);
cr.setLastMessage(message.getMessage());
cr.setUnreadCount(cr.getUnreadCount() + 1);
chatRoomArrayList.remove(index);
chatRoomArrayList.add(index, cr);
break;
}
}
mAdapter.notifyDataSetChanged();
}
/**
* fetching the chat rooms by making http call
*/
private void fetchChatRooms() {
StringRequest strReq = new StringRequest(Request.Method.GET,
EndPoints.CHAT_ROOMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error flag
if (obj.getBoolean("error") == false) {
JSONArray chatRoomsArray = obj.getJSONArray("chat_rooms");
for (int i = 0; i < chatRoomsArray.length(); i++) {
JSONObject chatRoomsObj = (JSONObject) chatRoomsArray.get(i);
ChatRoom cr = new ChatRoom();
cr.setId(chatRoomsObj.getString("user_id"));
cr.setName(chatRoomsObj.getString("name"));
cr.setLastMessage("");
cr.setUnreadCount(0);
cr.setTimestamp(chatRoomsObj.getString("created_at"));
chatRoomArrayList.add(cr);
}
} else {
// error in fetching chat rooms
Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
mAdapter.notifyDataSetChanged();
// subscribing to all chat room topics
//subscribeToAllTopics();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
// subscribing to global topic
private void subscribeToGlobalTopic() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, Config.TOPIC_GLOBAL);
startService(intent);
}
// Subscribing to all chat room topics
// each topic name starts with `topic_` followed by the ID of the chat room
// Ex: topic_1, topic_2
/*private void subscribeToAllTopics() {
for (ChatRoom cr : chatRoomArrayList) {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, "topic_" + cr.getId());
startService(intent);
}
}*/
private void launchLoginActivity() {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
#Override
protected void onResume() {
super.onResume();
// register GCM registration complete receiver
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
// register new push message receiver
// by doing this, the activity will be notified each time a new message arrives
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
// clearing the notification tray
NotificationUtils.clearNotifications();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
// starting the service to register with GCM
private void registerGCM() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra("key", "register");
startService(intent);
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.i(TAG, "This device is not supported. Google Play Services not installed!");
Toast.makeText(getApplicationContext(), "This device is not supported. Google Play Services not installed!", Toast.LENGTH_LONG).show();
finish();
}
return false;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_logout:
MyApplication.getInstance().logout();
break;
}
return super.onOptionsItemSelected(menuItem);
}
}
ChatRoomsAdapter:
package com.wipro.chat.adapter;
/**
* Created by COMP on 16-06-2016.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import com.wipro.chat.R;
import com.wipro.chat.model.ChatRoom;
public class ChatRoomsAdapter extends RecyclerView.Adapter<ChatRoomsAdapter.ViewHolder> {
private Context mContext;
private ArrayList<ChatRoom> chatRoomArrayList;
private static String today;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name, message, timestamp, count;
public ViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
message = (TextView) view.findViewById(R.id.message);
timestamp = (TextView) view.findViewById(R.id.timestamp);
count = (TextView) view.findViewById(R.id.count);
}
}
public ChatRoomsAdapter(Context mContext, ArrayList<ChatRoom> chatRoomArrayList) {
this.mContext = mContext;
this.chatRoomArrayList = chatRoomArrayList;
Calendar calendar = Calendar.getInstance();
today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_rooms_list_row, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ChatRoom chatRoom = chatRoomArrayList.get(position);
holder.name.setText(chatRoom.getName());
holder.message.setText(chatRoom.getLastMessage());
if (chatRoom.getUnreadCount() > 0) {
holder.count.setText(String.valueOf(chatRoom.getUnreadCount()));
holder.count.setVisibility(View.VISIBLE);
} else {
holder.count.setVisibility(View.GONE);
}
holder.timestamp.setText(getTimeStamp(chatRoom.getTimestamp()));
}
#Override
public int getItemCount() {
return chatRoomArrayList.size();
}
public static String getTimeStamp(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "";
today = today.length() < 2 ? "0" + today : today;
try {
Date date = format.parse(dateStr);
SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
String dateToday = todayFormat.format(date);
format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
String date1 = format.format(date);
timestamp = date1.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return timestamp;
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ChatRoomsAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ChatRoomsAdapter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
PHP code which is retrieving the chatroom is like:
/* * *
* fetching all chat rooms
*/
$app->get('/chat_rooms', function() {
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllChats();
$response["error"] = false;
$response["chat_rooms"] = array();
// pushing single chat room into array
while ($chat_room = $result->fetch_assoc()) {
$tmp = array();
$tmp["user_id"] = $chat_room["user_id"];
$tmp["name"] = $chat_room["name"];
$tmp["created_at"] = $chat_room["created_at"];
array_push($response["chat_rooms"], $tmp);
}
echoRespnse(200, $response);
});
public function getAllChats() {
$stmt = $this->conn->prepare("SELECT user_id, name, created_at FROM users");
$stmt->execute();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
There are two user chats in my database, namely Messaging, Chat and I'm getting the both from database into ArrayList but it is only showing Messaging.
Adapter display:
Response from database:
Check recycler_view in your main layout. The height should be set to "wrap_content".

an attempt was made to open a session that has a pending request

i made login and signup with Facebook functionality in my app,the problem is that once user clicks log in with Facebook button and dialog appears for login if user cancel that dialog it is redirected to login and from that if it again clicks on log in with Facebook white screen appears..Log cat shows error as "an attempt was made to open a session that has a pending request" below is my code..i am confused about this error any help is appriciated
FaceBookIntegration.java
/**
*
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
;
/**
* Facebook integration class ccontains login with fb and share activity
*
* #author Admin
*/
public class FacebookIntegration extends GlobalActivity implements ResponseListener {
private ProgressDialog progressDialog;
private Session session;
private boolean share;
private UserHistory userHistory = null;
Preferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = HWUtil.getPreferences(this);
share = getIntent().getBooleanExtra(HWUtil.SHARE, false);
if (share) {
userHistory = preferences.getShareUserHistory();
if (Validator.isNull(userHistory)) {
finish();
}
}
Session.StatusCallback statusCallback = new SessionStatusCallback();
session = Session.getActiveSession();
if (session == null) {
session = new Session(this);
Session.setActiveSession(session);
}
if (!session.isOpened() && !session.isClosed()) {
session.openForPublish(new Session.OpenRequest(this).setPermissions(Arrays.asList("public_profile", "email", "publish_actions", "user_actions.fitness")).setCallback(statusCallback));
} else {
if (share) {
shareOnFacebook();
} else {
getProfileDetail(session);
}
}
}
/**
* Share activity records on facebook
*/
private void shareOnFacebook() {
if (Validator.isNotNull(userHistory)) {
String apiUrl;
if ("Running".equals(userHistory.getSportName())) {
apiUrl = "fitness.runs";
} else if ("Walking".equals(userHistory.getSportName())) {
apiUrl = "fitness.walks";
} else if ("Cycling".equals(userHistory.getSportName())) {
apiUrl = "fitness.bikes";
} else {
apiUrl = "*:sport";
}
Bundle params = new Bundle();
params.putString("course", com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId());
params.putBoolean("fb:explicitly_shared", true);
/* make the API call */
new Request(Session.getActiveSession(), "/me/" + apiUrl, params, HttpMethod.POST, new Request.Callback() {
public void onCompleted(Response response) {
if (response.getError() == null) {
com.aimdek.healthwel.network.Request.getRequest().sendRequest(com.aimdek.healthwel.network.Request.SHARE_USER_HISTORY, FacebookIntegration.this, FacebookIntegration.this, RequestParameterBuilder.buildMapForShareUserHistory(userHistory.getId(), FacebookIntegration.this));
} else {
finish();
Log.d("Facebook error", response.getError().toString());
}
}
}).executeAsync();
if (Validator.isNotNull(userHistory.getHistoryPictures()) && userHistory.getHistoryPictures().length > 0) {
for (int i = 0; i < userHistory.getHistoryPictures().length; i++) {
HistoryPictures pictures = userHistory.getHistoryPictures()[i];
String message = getString(R.string.facebook_status, HWUtil.getFullName(preferences.getUserInfo().getFirstName(), preferences.getUserInfo().getLastName()), userHistory.getSportName());
params.putString("message", message);
if (Validator.isNotNull(pictures.getPictureUrl())) {
params.putString("url", pictures.getPictureUrl());
} else {
params.putByteArray("picture", Base64.decode(pictures.getData(), Base64.DEFAULT));
// params.putString("method", "photos.upload");
}
new Request(Session.getActiveSession(), "/me/photos", params, HttpMethod.POST, new Request.Callback() {
public void onCompleted(Response response) {
if (response.getError() == null) {
} else {
}
}
}).executeAsync();
}
}
}
}
#Override
public void onResponse(int type, Object... result) {
if (type == Request.SHARE_USER_HISTORY) {
preferences.setShareOnFacebook(false);
if (preferences.isShareOnGoogle()) {
Intent intent = new Intent(FacebookIntegration.this, GooglePlusIntegration.class);
intent.putExtra(HWUtil.SHARE, true);
startActivity(intent);
} else {
preferences.setShareUserHistory(null);
}
} else {
if (Validator.isNotNull(result) && result.length > 0 && Validator.isNotNull(result[0])) {
String response = (String) result[0];
HWUtil.loadMainActivity(response, FacebookIntegration.this);
}
}
finish();
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
if (share) {
shareOnFacebook();
} else {
getProfileDetail(session);
}
}
}
}
/**
* get facebook profile detail
*
* #param session - pass facebook session
*/
private void getProfileDetail(Session session) {
showProgressDialog();
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (Validator.isNotNull(user)) {
UserInfo userInfoDto = new UserInfo();
String id = user.getId();
userInfoDto.setFirstName(user.getFirstName());
userInfoDto.setLastName(user.getLastName());
String email = Validator.isNotNull(user.asMap().get("email")) ? user.asMap().get("email").toString() : HWUtil.BLANK;
if (Validator.isNotNull(email)) {
userInfoDto.setEmail(email);
String gender = Validator.isNotNull(user.asMap().get("gender")) ? user.asMap().get("gender").toString() : HWUtil.BLANK;
if ("male".equals(gender)) {
userInfoDto.setGender(1);
} else {
userInfoDto.setGender(2);
}
userInfoDto.setUniqueId(HWUtil.getDeviceId(FacebookIntegration.this));
userInfoDto.setMeasureUnit(HWUtil.getMeasureUnit(FacebookIntegration.this));
userInfoDto.setPassword(HWUtil.BLANK);
String imageURL = "https://graph.facebook.com/" + id + "/picture?type=large";
userInfoDto.setProfilePictureUrl(imageURL);
Request.getRequest().sendJsonRequest(Request.UPDATE_USER, FacebookIntegration.this, FacebookIntegration.this, RequestParameterBuilder.buildJsonObjectFromUserInfo(userInfoDto));
dismissProgressDialog();
} else {
HWUtil.showToast(FacebookIntegration.this, getString(R.string.allow_read_email));
dismissProgressDialog();
finish();
return;
}
}
}
}).executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (session != null && !session.isOpened()) {
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
} else {
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void showProgressDialog() {
if(!isFinishing() && progressDialog==null) {
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.show();
}
}
/**
* dismiss Progress Dialog.
*/
private void dismissProgressDialog() {
if (!isFinishing() &&progressDialog!=null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}

Null Pointer Exception in Android using List

I have following activities to load products from backend. Its a online food ordering with integration of paypal. I tried it in another app its working fine.
I am getting Error on onCreate Method.
There are three activities Item list , Product and product list adapter. I am getting error while loading view. When i commented the lines of adapter its not crashing but after adding the adapters its crashing . Its driving me crazy.
import com.flavorbaba.AppController;
import com.flavorbaba.Config;
import com.flavorbaba.Product;
import com.flavorbaba.ProductListAdapter;
import com.flavorbaba.ProductListAdapter.ProductListAdapterListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalItem;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalPaymentDetails;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
public class ItemsList extends Activity implements ProductListAdapterListener {
private static final String TAG = ItemsList.class.getSimpleName();
private ListView listView;
private Button btnCheckout;
// To store all the products
private List<Product> productsList;
// To store the products those are added to cart
private List<PayPalItem> productsInCart = new ArrayList<PayPalItem>();
private ProductListAdapter adapter;
// Progress dialog
private ProgressDialog pDialog;
private static final int REQUEST_CODE_PAYMENT = 1;
// PayPal configuration
private static PayPalConfiguration paypalConfig = new PayPalConfiguration()
.environment(Config.PAYPAL_ENVIRONMENT).clientId(
Config.PAYPAL_CLIENT_ID);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_menu);
listView = (ListView) findViewById(R.id.list);
btnCheckout = (Button) findViewById(R.id.checkout);
productsList = new ArrayList<Product>();
adapter = new ProductListAdapter(ItemsList.this, productsList, this);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Starting PayPal service
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
startService(intent);
// Checkout button click listener
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check for empty cart
if (productsInCart.size() > 0) {
launchPayPalPayment();
} else {
Toast.makeText(getApplicationContext(),
"Cart is empty! Please add few products to cart.",
Toast.LENGTH_SHORT).show();
}
}
});
// Fetching products from server
fetchProducts();
}
/**
* Fetching the products from our server
* */
private void fetchProducts() {
// Showing progress dialog before making request
pDialog.setMessage("Fetching products...");
showpDialog();
// Making json object request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Config.URL_PRODUCTS, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray products = response
.getJSONArray("products");
// looping through all product nodes and storing
// them in array list
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("p_id");
String name = product.getString("p_name");
String description = product
.getString("p_desc");
String image = product.getString("p_image");
BigDecimal price = new BigDecimal(product
.getString("p_price"));
String sku = product.getString("p_status");
Product p = new Product(id, name, description,
image, price, sku);
productsList.add(p);
}
listView.setAdapter(adapter);
// notifying adapter about data changes, so that the
// list renders with new data
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
// hiding the progress dialog
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Verifying the mobile payment on the server to avoid fraudulent payment
* */
private void verifyPaymentOnServer(final String paymentId,
final String payment_client) {
// Showing progress dialog before making request
pDialog.setMessage("Verifying payment...");
showpDialog();
StringRequest verifyReq = new StringRequest(Method.POST,
Config.URL_VERIFY_PAYMENT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "verify payment: " + response.toString());
try {
JSONObject res = new JSONObject(response);
boolean error = res.getBoolean("error");
String message = res.getString("message");
// user error boolean flag to check for errors
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
if (!error) {
// empty the cart
productsInCart.clear();
}
} catch (JSONException e) {
e.printStackTrace();
}
// hiding the progress dialog
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Verify Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hiding the progress dialog
hidepDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("paymentId", paymentId);
params.put("paymentClientJson", payment_client);
return params;
}
};
// Setting timeout to volley request as verification request takes
// sometime
int socketTimeout = 60000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
verifyReq.setRetryPolicy(policy);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(verifyReq);
}
/**
* Preparing final cart amount that needs to be sent to PayPal for payment
* */
private PayPalPayment prepareFinalCart() {
PayPalItem[] items = new PayPalItem[productsInCart.size()];
items = productsInCart.toArray(items);
// Total amount
BigDecimal subtotal = PayPalItem.getItemTotal(items);
// If you have shipping cost, add it here
BigDecimal shipping = new BigDecimal("0.0");
// If you have tax, add it here
BigDecimal tax = new BigDecimal("0.0");
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(
shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(
amount,
Config.DEFAULT_CURRENCY,
"Description about transaction. This will be displayed to the user.",
Config.PAYMENT_INTENT);
payment.items(items).paymentDetails(paymentDetails);
// Custom field like invoice_number etc.,
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
/**
* Launching PalPay payment activity to complete the payment
* */
private void launchPayPalPayment() {
PayPalPayment thingsToBuy = prepareFinalCart();
Intent intent = new Intent(ItemsList.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingsToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
/**
* Receiving the PalPay payment response
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.e(TAG, confirm.toJSONObject().toString(4));
Log.e(TAG, confirm.getPayment().toJSONObject()
.toString(4));
String paymentId = confirm.toJSONObject()
.getJSONObject("response").getString("id");
String payment_client = confirm.getPayment()
.toJSONObject().toString();
Log.e(TAG, "paymentId: " + paymentId
+ ", payment_json: " + payment_client);
// Now verify the payment on the server side
verifyPaymentOnServer(paymentId, payment_client);
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ",
e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e(TAG, "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.e(TAG,
"An invalid Payment or PayPalConfiguration was submitted.");
}
}
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onAddToCartPressed(Product product) {
PayPalItem item = new PayPalItem(product.getname(), 1,
product.getprice(), Config.DEFAULT_CURRENCY, product.getsku());
productsInCart.add(item);
Toast.makeText(getApplicationContext(),
item.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
--------------------------------------------------------------------------
import java.math.BigDecimal;
public class Product {
private String id, name, description, image, sku;
private BigDecimal price;
public Product() {
}
public Product(String id, String name, String description, String image,
BigDecimal price, String sku) {
this.id = id;
this.name = name;
this.description = description;
this.image = image;
this.price = price;
this.sku = sku;
}
public String getid() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getname() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getdescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getimage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public BigDecimal getprice() {
return price;
}
public String getsku() {
return sku;
}
}
---------------------------------------------------------------
package com.flavorbaba;
import com.flavorbaba.R;
import com.flavorbaba.AppController;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class ProductListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Product> products;
private ProductListAdapterListener listener;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ProductListAdapter(Activity activity, List<Product> feedItems,
ProductListAdapterListener listener) {
this.activity = activity;
this.products = feedItems;
this.listener = listener;
}
#Override
public int getCount() {
return products.size();
}
#Override
public Object getItem(int location) {
return products.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item_product, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.productName);
TextView description = (TextView) convertView
.findViewById(R.id.productDescription);
TextView price = (TextView) convertView.findViewById(R.id.productPrice);
NetworkImageView image = (NetworkImageView) convertView
.findViewById(R.id.productImage);
Button btnAddToCart = (Button) convertView
.findViewById(R.id.btnAddToCart);
final Product product = products.get(position);
name.setText(product.getname());
description.setText(product.getdescription());
price.setText("Price: $" + product.getprice());
// user profile pic
image.setImageUrl(product.getimage(), imageLoader);
btnAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onAddToCartPressed(product);
}
});
return convertView;
}
public interface ProductListAdapterListener {
public void onAddToCartPressed(Product product);
}
}
This is a lot ta code dude...
I Wonder why your Productlistadapter object needs two contexts and why you give the first context as Item activity.this but nevertheless
One big Problem here is that you are trying to make a network connection on the main thread...that's an error when you are in strict mode while debugging...

Facebook login fragment closes application, using Facebook SDK 3.0.1

I'm developing an Android app that should integrate with Facebook. I have gone through official guide and several other guides and I think I have implemented everything correctly with the Facebook login framgent.
However the SDK performs a successful login only the first time. If I log out and try again the application just closes without any exception. The same happens if I kill my app and start it from the application list.
I can reproduce it in both the emulator and on the real device (Nexus 7).
LoginActivity.java:
package com.everporter.everporter;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import com.everporter.everporter.FBLoginFragment.OnFBAccessTokenPass;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginActivity extends FragmentActivity
implements OnFBAccessTokenPass {
/**
* The default email to populate the email field with.
*/
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
private static final String REST_METHOD_NAME = "/login/";
private static final String SOCIAL_REST_METHOD_NAME = "/validation/";
private static final String TAG = "UserLoginTask";
private static final String FB_TAG = "UserFacebookLoginTask";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
private UserFacebookLoginTask mFacebookAuthTask = null;
private String mFacebookAccessToken;
private String mFacebookUserId;
// API URL read from the settings (set in main activity)
private String mRestApiUrl;
private int mConnectionTimeout;
private int mReadTimeout;
private SharedPreferences mPrefs;
// Error message set by the async task, if the error does happen indeed
private String mAsyncTaskErrorMsg;
// Values for email and password at the time of the login attempt.
private String mEmail;
private String mPassword;
private String mSessionCookie; // our session
// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mPrefs = getSharedPreferences("settings", MODE_PRIVATE);
mRestApiUrl = mPrefs.getString("api_url", "");
mConnectionTimeout = mPrefs.getInt("connection_timeout", 3000);
mReadTimeout = mPrefs.getInt("read_timeout", 3000);
// Set up the login form.
mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(mEmail);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Handle Facebook login
*/
#Override
public void onFBAccessTokenPass(String accessToken, String uid) {
// we are passed Facebook access token, successful login
Log.i(TAG, "Facebook access token: " + accessToken);
mFacebookAccessToken = accessToken;
mFacebookUserId = uid;
// Show a progress spinner, and kick off a background task to
// sent the FB token to the server.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mFacebookAuthTask = new UserFacebookLoginTask(this);
mFacebookAuthTask.execute((Void) null);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
mAsyncTaskErrorMsg = "";
// Store values at the time of the login attempt.
mEmail = mEmailView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address or phone number.
if (TextUtils.isEmpty(mEmail)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(mEmail).matches() &&
!PhoneNumberUtils.isGlobalPhoneNumber(mEmail)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask(this);
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private Context mContext;
public UserLoginTask(Context context) {
this.mContext = context;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.i(TAG, "Begin auth...");
HttpURLConnection conn = null;
StringBuilder sb = new StringBuilder();
BufferedOutputStream printout;
boolean signedInOk = false;
try {
URL url = new URL(mRestApiUrl + REST_METHOD_NAME);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(mConnectionTimeout);
conn.setReadTimeout(mReadTimeout);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("password", mPassword);
jsonParam.put("username", mEmail);
// Send POST output.
printout = new BufferedOutputStream(conn.getOutputStream());
printout.write(jsonParam.toString().getBytes("UTF-8"));
printout.flush();
printout.close();
int httpCode = conn.getResponseCode();
if (httpCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
Log.i(TAG, sb.toString());
JSONObject jsonResponse = new JSONObject(sb.toString());
int resultCode = jsonResponse.getInt("code");
if (resultCode == 0) {
// get the session id
String cookie = conn.getHeaderField("Set-Cookie");
if (cookie != null) {
Log.i(TAG, cookie);
signedInOk = true;
mSessionCookie = cookie;
Log.i(TAG, "Authenticated");
}
} else if (resultCode == 2 || resultCode == 3) {
signedInOk = false; // wrong login and password
} else {
// get the error message
if (!jsonResponse.isNull("message")) {
mAsyncTaskErrorMsg = jsonResponse.getString("message");
} else {
mAsyncTaskErrorMsg = getString(R.string.internal_error);
}
}
} else{
Log.e(TAG, conn.getResponseMessage());
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
mAsyncTaskErrorMsg = e.getMessage();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
mAsyncTaskErrorMsg = e.getMessage();
} finally {
if (conn != null)
conn.disconnect();
}
Log.i(TAG, "End auth...");
return signedInOk;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// store the userId
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("session_cookie", mSessionCookie);
ed.putLong("session_cookie_time", System.currentTimeMillis());
ed.apply();
// start main
Intent intent = new Intent(mContext, MainActivity.class);
startActivity(intent);
finish();
} else {
if (!mAsyncTaskErrorMsg.isEmpty()) {
// show the error message
new AlertDialog.Builder(mContext)
.setTitle("Error occured")
.setMessage(mAsyncTaskErrorMsg)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
/**
* Represents an asynchronous login task used to authenticate
* the user via Facebook.
*/
public class UserFacebookLoginTask extends AsyncTask<Void, Void, Boolean> {
private Context mContext;
public UserFacebookLoginTask(Context context) {
this.mContext = context;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.i(FB_TAG, "Begin Facebook validation...");
HttpURLConnection conn = null;
StringBuilder sb = new StringBuilder();
BufferedOutputStream printout;
boolean signedInOk = false;
try {
URL url = new URL(mRestApiUrl + SOCIAL_REST_METHOD_NAME);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(mConnectionTimeout);
conn.setReadTimeout(mReadTimeout);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("provider", "facebook");
jsonParam.put("token", mFacebookAccessToken);
jsonParam.put("uid", mFacebookUserId);
// Send POST output.
printout = new BufferedOutputStream(conn.getOutputStream());
printout.write(jsonParam.toString().getBytes("UTF-8"));
printout.flush();
printout.close();
int httpCode = conn.getResponseCode();
if (httpCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
Log.i(FB_TAG, sb.toString());
JSONObject jsonResponse = new JSONObject(sb.toString());
int resultCode = jsonResponse.getInt("code");
if (resultCode == 0) {
// get the session id
String cookie = conn.getHeaderField("Set-Cookie");
if (cookie != null) {
Log.i(FB_TAG, cookie);
signedInOk = true;
mSessionCookie = cookie;
Log.i(FB_TAG, "Authenticated");
}
} else if (resultCode == 2 || resultCode == 3) {
signedInOk = false; // no such user in the database
mAsyncTaskErrorMsg = "";
} else {
// get the error message
if (!jsonResponse.isNull("message")) {
mAsyncTaskErrorMsg = jsonResponse.getString("message");
} else {
mAsyncTaskErrorMsg = getString(R.string.internal_error);
}
}
} else{
Log.e(FB_TAG, conn.getResponseMessage());
}
} catch (JSONException e) {
Log.e(FB_TAG, e.getMessage());
mAsyncTaskErrorMsg = e.getMessage();
} catch (IOException e) {
Log.e(FB_TAG, e.getMessage());
mAsyncTaskErrorMsg = e.getMessage();
} finally {
if (conn != null)
conn.disconnect();
}
Log.i(FB_TAG, "End auth...");
return signedInOk;
}
#Override
protected void onPostExecute(final Boolean success) {
mFacebookAuthTask = null;
showProgress(false);
if (success) {
// store the userId
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("session_cookie", mSessionCookie);
ed.putLong("session_cookie_time", System.currentTimeMillis());
ed.apply();
// start main
Intent intent = new Intent(mContext, MainActivity.class);
startActivity(intent);
finish();
} else {
if (!mAsyncTaskErrorMsg.isEmpty()) {
// show the error message
new AlertDialog.Builder(mContext)
.setTitle("Error occured")
.setMessage(mAsyncTaskErrorMsg)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}
}
}
#Override
protected void onCancelled() {
mFacebookAuthTask = null;
showProgress(false);
}
}
}
FBLoginFragment.java:
package com.everporter.everporter;
import java.util.Arrays;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class FBLoginFragment extends Fragment {
private static final String TAG = "FBLoginFragment";
private UiLifecycleHelper mUiHelper;
private OnFBAccessTokenPass mTokenPasser;
private String mSessionToken;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
mSessionToken = session.getAccessToken();
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// pass the access token to the activity
// with the user id
mTokenPasser.onFBAccessTokenPass(mSessionToken, user.getId());
}
}
});
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
mSessionToken = "";
}
}
public interface OnFBAccessTokenPass {
public void onFBAccessTokenPass(String accessToken, String uid);
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
mTokenPasser = (OnFBAccessTokenPass) a;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUiHelper = new UiLifecycleHelper(getActivity(), callback);
mUiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fb_login_fragment, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("email"));
return view;
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
mUiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mUiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
mUiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mUiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mUiHelper.onSaveInstanceState(outState);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.everporter.everporter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.everporter.everporter.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.everporter.everporter.LoginActivity"
android:label="#string/title_activity_login"
android:noHistory="true"
android:excludeFromRecents="true"
android:windowSoftInputMode="adjustResize|stateVisible" >
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/fb_app_id"/>
<activity android:name="com.facebook.LoginActivity" android:label="#string/app_name"></activity>
</application>
</manifest>
After spending a day on this issue I have found the reason: my activity had android:noHistory="true" in the manifest which prevented Facebook SDK from launching my activity when the session was opened. Whew!!

Task android sample error

I am download task-android-sample(http://code.google.com/p/google-api-java-client/issues/detail?id=479). But when i run this example on my android device, I m get error
The error appears here in this function
protected void doInBackground() throws IOException {
Log.d(Tag, "doInBackground");
List<String> result = new ArrayList<String>();
List<Task> tasks =
client.tasks().list("#default").setFields("items/title").execute().getItems();
Log.d(Tag, "трассировка");
if (tasks != null) {
for (Task task : tasks) {
result.add(task.getTitle());
}
} else {
result.add("No tasks.");
}
activity.tasksList = result;
}
description client
final com.google.api.services.tasks.Tasks client;
client = activity.service;
in what could be the problem? I am a novice, please help.
04-23 08:55:06.789: E/TasksSample(3778): com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
04-23 08:55:06.789: E/TasksSample(3778): {
04-23 08:55:06.789: E/TasksSample(3778): "code": 403,
04-23 08:55:06.789: E/TasksSample(3778): "errors": [
04-23 08:55:06.789: E/TasksSample(3778): {
04-23 08:55:06.789: E/TasksSample(3778): "domain": "usageLimits",
04-23 08:55:06.789: E/TasksSample(3778): "message": "Access Not Configured",
04-23 08:55:06.789: E/TasksSample(3778): "reason": "accessNotConfigured"
04-23 08:55:06.789: E/TasksSample(3778): }
04-23 08:55:06.789: E/TasksSample(3778): ],
04-23 08:55:06.789: E/TasksSample(3778): "message": "Access Not Configured"
public static final String KEY = null;
make sure that you added key in place of null in ClientCredentials.java
AsyncLoadTasks
package com.google.api.services.samples.tasks.android;
import com.google.api.services.tasks.model.Task;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class AsyncLoadTasks extends CommonAsyncTask {
final String Tag="States";
AsyncLoadTasks(TasksSample tasksSample) {
super(tasksSample);
}
#Override
protected void doInBackground() throws IOException {
Log.d(Tag, "doInBackground");
List<String> result = new ArrayList<String>();
List<Task> tasks =
client.tasks().list("#default").setFields("items/title").execute().getItems();
Log.d(Tag, "трассировка");
if (tasks != null) {
for (Task task : tasks) {
result.add(task.getTitle());
}
} else {
result.add("No tasks.");
}
activity.tasksList = result;
}
static void run(TasksSample tasksSample) {
new AsyncLoadTasks(tasksSample).execute();
}
}
CommonAsyncTask
package com.google.api.services.samples.tasks.android;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityI OException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import java.io.IOException;
abstract class CommonAsyncTask extends AsyncTask<Void, Void, Boolean> {
final String Tag="States";
final TasksSample activity;
final com.google.api.services.tasks.Tasks client;
private final View progressBar;
CommonAsyncTask(TasksSample activity) {
Log.d(Tag, "CommonAsyncTask");
this.activity = activity;
client = activity.service;
progressBar = activity.findViewById(R.id.title_refresh_progress);
}
#Override
protected void onPreExecute() {
Log.d(Tag, "onPreExecute");
super.onPreExecute();
activity.numAsyncTasks++;
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected final Boolean doInBackground(Void... ignored) {
Log.d(Tag, "Boolean doInBackground");
try {
doInBackground();
return true;
} catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
Log.d(Tag, "1");
activity.showGooglePlayServicesAvailabilityErrorDialog(
availabilityException.getConnectionStatusCode());
} catch (UserRecoverableAuthIOException userRecoverableException) {
Log.d(Tag, "2");
activity.startActivityForResult(
userRecoverableException.getIntent(), TasksSample.REQUEST_AUTHORIZATION);
} catch (IOException e) {
Log.d(Tag, "3");
Utils.logAndShow(activity, TasksSample.TAG, e);
}
return false;
}
#Override
protected final void onPostExecute(Boolean success) {
Log.d(Tag, "onPostExecute");
super.onPostExecute(success);
if (0 == --activity.numAsyncTasks) {
progressBar.setVisibility(View.GONE);
}
if (success) {
activity.refreshView();
}
}
abstract protected void doInBackground() throws IOException;
}
TasksSample
package com.google.api.services.samples.tasks.android;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.tasks.TasksScopes;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class TasksSample extends Activity {
private static final Level LOGGING_LEVEL = Level.OFF;
private static final String PREF_ACCOUNT_NAME = "accountName";
static final String TAG = "TasksSample";
static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
static final int REQUEST_AUTHORIZATION = 1;
static final int REQUEST_ACCOUNT_PICKER = 2;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = new GsonFactory();
GoogleAccountCredential credential;
List<String> tasksList;
ArrayAdapter<String> adapter;
com.google.api.services.tasks.Tasks service;
int numAsyncTasks;
private ListView listView;
final String Tag="States";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Tag, "onCreate");
// enable logging
Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
// view and menu
setContentView(R.layout.calendarlist);
listView = (ListView) findViewById(R.id.list);
// Google Accounts
credential = GoogleAccountCredential.usingOAuth2(this, TasksScopes.TASKS);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
// Tasks client
service =
new com.google.api.services.tasks.Tasks.Builder(transport, jsonFactory, credential)
.setApplicationName("Google-TasksAndroidSample/1.0").build();
}
void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
runOnUiThread(new Runnable() {
public void run() {
Log.d(Tag, "run");
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(connectionStatusCode, TasksSample.this,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
void refreshView() {
Log.d(Tag, "refreshView");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tasksList);
listView.setAdapter(adapter);
}
#Override
protected void onResume() {
Log.d(Tag, "onResume");
super.onResume();
if (checkGooglePlayServicesAvailable()) {
haveGooglePlayServices();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(Tag, "onActivityResult");
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
haveGooglePlayServices();
} else {
checkGooglePlayServicesAvailable();
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
AsyncLoadTasks.run(this);
} else {
chooseAccount();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
AsyncLoadTasks.run(this);
}
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(Tag, "onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(Tag, "onOptionsItemSelected");
switch (item.getItemId()) {
case R.id.menu_refresh:
AsyncLoadTasks.run(this);
break;
case R.id.menu_accounts:
chooseAccount();
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean checkGooglePlayServicesAvailable() {
Log.d(Tag, "checkGooglePlayServicesAvailable");
final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
}
return true;
}
private void haveGooglePlayServices() {
Log.d(Tag, "haveGooglePlayServices");
// check if there is already an account selected
if (credential.getSelectedAccountName() == null) {
Log.d(Tag, "user to choose account");
// ask user to choose account
chooseAccount();
} else {
Log.d(Tag, "load calendars");
// load calendars
AsyncLoadTasks.run(this);
}
}
private void chooseAccount() {
Log.d(Tag, "chooseAccount");
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
}
Utils
package com.google.api.services.samples.tasks.android;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import android.app.Activity;
import android.content.res.Resources;
import android.util.Log;
import android.widget.Toast;
public class Utils {
public static void logAndShow(Activity activity, String tag, Throwable t) {
// Log.d(Tag, "onPostExecute");
Log.e(tag, "Error", t);
String message = t.getMessage();
if (t instanceof GoogleJsonResponseException) {
GoogleJsonError details = ((GoogleJsonResponseException) t).getDetails();
if (details != null) {
message = details.getMessage();
}
} else if (t.getCause() instanceof GoogleAuthException) {
message = ((GoogleAuthException) t.getCause()).getMessage();
}
showError(activity, message);
}
/**
public static void logAndShowError(Activity activity, String tag, String message) {
String errorMessage = getErrorMessage(activity, message);
Log.e(tag, errorMessage);
showErrorInternal(activity, errorMessage);
}
public static void showError(Activity activity, String message) {
String errorMessage = getErrorMessage(activity, message);
showErrorInternal(activity, errorMessage);
}
private static void showErrorInternal(final Activity activity, final String errorMessage) {
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG).show();
}
});
}
private static String getErrorMessage(Activity activity, String message) {
Resources resources = activity.getResources();
if (message == null) {
return resources.getString(R.string.error);
}
return resources.getString(R.string.error_format, message);
}
}
It is my code. What I can fix?

Categories

Resources