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".
Related
I am displaying a list of messages in my chat room and I'm using RecycleView to display. I want the view to be set to the recent message(last message, last item in the list) instead of the first item. I used smoothScrollToPosition but I don't want the list to be scrolled from first to last to view the recent message. I want it to be like whatsapp which when clicked on a chat would show the view of the last message. How can I achieve this?
package com.webapp.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.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.webapp.chat.R;
import com.webapp.chat.adapter.ChatRoomThreadAdapter;
import com.webapp.chat.app.Config;
import com.webapp.chat.app.EndPoints;
import com.webapp.chat.app.MyApplication;
import com.webapp.chat.gcm.NotificationUtils;
import com.webapp.chat.model.Message;
import com.webapp.chat.model.User;
public class ChatRoomActivity extends AppCompatActivity {
private String TAG = ChatRoomActivity.class.getSimpleName();
private String userChatRoomId;
private RecyclerView recyclerView;
private ChatRoomThreadAdapter mAdapter;
private ArrayList<Message> messageArrayList;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private EditText inputMessage;
private Button btnSend;
private String selfUserId;
private String selfUserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inputMessage = (EditText) findViewById(R.id.message);
btnSend = (Button) findViewById(R.id.btn_send);
Intent intent = getIntent();
userChatRoomId = intent.getStringExtra("user_id");
String title = intent.getStringExtra("name");
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (userChatRoomId == null) {
Toast.makeText(getApplicationContext(), "User Chat room not found!", Toast.LENGTH_SHORT).show();
finish();
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
messageArrayList = new ArrayList<>();
// self user id is to identify the message owner
selfUserId = MyApplication.getInstance().getPrefManager().getUser().getId();
selfUserName = MyApplication.getInstance().getPrefManager().getUser().getName();
mAdapter = new ChatRoomThreadAdapter(this, messageArrayList, selfUserId);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push message is received
handlePushNotification(intent);
}
}
};
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
fetchChatThread();
}
#Override
protected void onResume() {
super.onResume();
// registering the receiver for new notification
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
NotificationUtils.clearNotifications();
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
/**
* Handling new push message, will add the message to
* recycler view and scroll it to bottom
* */
private void handlePushNotification(Intent intent) {
Message message = (Message) intent.getSerializableExtra("message");
String userChatRoomId = intent.getStringExtra("user_id");
if (message != null && userChatRoomId != null) {
messageArrayList.add(message);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}
}
}
/**
* Posting a new message in chat room
* will make an http call to our server. Our server again sends the message
* to all the devices as push notification
* */
private void sendMessage() {
final String message = this.inputMessage.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
Toast.makeText(getApplicationContext(), "Enter a message", Toast.LENGTH_SHORT).show();
return;
}
/** Create chatroom with the other user after sending the message**/
String endPointInsert = EndPoints.CHAT_ROOM.replace("_ID_", selfUserId) + "/" + userChatRoomId;
Log.e(TAG, "endpointInsert: " + endPointInsert);
StringRequest strReque = new StringRequest(Request.Method.GET,
endPointInsert, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
}
}, 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();
}
});
Date date = new Date();
String createdAt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
Log.e(TAG, "TIMESTAMP:" + createdAt);
User user = new User(selfUserId, selfUserName);
final Message msg = new Message();
msg.setId("");
msg.setMessage(message);
msg.setCreatedAt(createdAt);
msg.setUser(user);
messageArrayList.add(msg);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
// scrolling to bottom of the recycler view
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}
//Log.e(TAG,msg.getId());
String endPoint = EndPoints.USER_MESSAGE.replace("_ID_", userChatRoomId);
Log.e(TAG, "endpoint: " + endPoint);
this.inputMessage.setText("");
StringRequest strReq = new StringRequest(Request.Method.POST,
endPoint, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error
if (obj.getBoolean("error") == false) {
JSONObject commentObj = obj.getJSONObject("message");
String commentId = commentObj.getString("message_id");
String commentText = commentObj.getString("message");
String createdAt = commentObj.getString("created_at");
JSONObject userObj = obj.getJSONObject("user");
String userId = commentObj.getString("from_user_id");
String userName = userObj.getString("name");
User user = new User(userId, userName);
Log.e(TAG, commentId);
msg.setId(commentId);
/*Message message = new Message();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createdAt);
message.setUser(user);*/
/*messageArrayList.add(msg);
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
// scrolling to bottom of the recycler view
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
}*/
} else {
Toast.makeText(getApplicationContext(), "" + obj.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_SHORT).show();
}
}
}, 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();
inputMessage.setText(message);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", MyApplication.getInstance().getPrefManager().getUser().getId());
params.put("message", message);
Log.e(TAG, "Params: " + params.toString());
return params;
};
};
// disabling retry policy so that it won't make
// multiple http calls
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
strReq.setRetryPolicy(policy);
//Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReque);
MyApplication.getInstance().addToRequestQueue(strReq);
Log.i(TAG,msg.getId());
}
/**
* Fetching all the messages of a single chat room
* */
private void fetchChatThread() {
String endPointi = EndPoints.CHAT_USER_THREAD.replace("_ID_", userChatRoomId);
String endPoint = endPointi + "/" + selfUserId;
Log.e(TAG, "endPoint: " + endPoint);
StringRequest strReq = new StringRequest(Request.Method.GET,
endPoint, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error
if (obj.getBoolean("error") == false) {
JSONArray commentsObj = obj.getJSONArray("messages");
for (int i = 0; i < commentsObj.length(); i++) {
JSONObject commentObj = (JSONObject) commentsObj.get(i);
String commentId = commentObj.getString("message_id");
String commentText = commentObj.getString("message");
String createdAt = commentObj.getString("created_at");
JSONObject userObj = commentObj.getJSONObject("user");
String userId = userObj.getString("user_id");
String userName = userObj.getString("username");
User user = new User(userId, userName);
Message message = new Message();
message.setId(commentId);
message.setMessage(commentText);
message.setCreatedAt(createdAt);
message.setUser(user);
messageArrayList.add(message);
}
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, 1);
}
} else {
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_SHORT).show();
}
}
}, 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);
}
}
package com.webapp.chat.adapter;
/**
* Created by COMP on 17-06-2016.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
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.webapp.chat.R;
import com.webapp.chat.model.Message;
public class ChatRoomThreadAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static String TAG = ChatRoomThreadAdapter.class.getSimpleName();
private String userId;
private int SELF = 100;
private static String today;
private Context mContext;
private ArrayList<Message> messageArrayList;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView message, timestamp;
public ViewHolder(View view) {
super(view);
message = (TextView) itemView.findViewById(R.id.message);
timestamp = (TextView) itemView.findViewById(R.id.timestamp);
}
}
public ChatRoomThreadAdapter(Context mContext, ArrayList<Message> messageArrayList, String userId) {
this.mContext = mContext;
this.messageArrayList = messageArrayList;
this.userId = userId;
Calendar calendar = Calendar.getInstance();
today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
// view type is to identify where to render the chat message
// left or right
if (viewType == SELF) {
// self message
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item_self, parent, false);
} else {
// others message
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item_other, parent, false);
}
return new ViewHolder(itemView);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if (message.getUser().getId().equals(userId)) {
return SELF;
}
return position;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Message message = messageArrayList.get(position);
((ViewHolder) holder).message.setText(message.getMessage());
String timestamp = getTimeStamp(message.getCreatedAt());
if (message.getUser().getName() != null)
timestamp = message.getUser().getName() + ", " + timestamp;
((ViewHolder) holder).timestamp.setText(timestamp);
}
#Override
public int getItemCount() {
return messageArrayList.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;
}
}
Set setReverseLayout=true so that LayoutManager will layout items from end.
Something like this:
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
recyclerView.setLayoutManager(layoutManager);
EDIT: This will reverse the data order but not scroll the RecyclerView to the last item. For keeping data order same and simply scrolling the RecyclerView to the last item set setStackFromEnd=true
Sample:
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
Use RecyclerView LayoutManager to scroll item at position
recyclerView.getLayoutManager().scrollToPosition(messageList.size()-1);
And u are good to go
LinearLayoutManager manager = new LinearLayoutManager(ActivityMessage.this);
manager.setStackFromEnd(true);
manager.setReverseLayout(false);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(manager);
My sinch client sends duplicate messages to my parse database in an incremental way. That is for the first message it posts once in the database. Twice for the second message. Thrice for the third in that order.
This is my ChatActivity
package com.app.knowtes;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.sinch.android.rtc.PushPair;
import com.sinch.android.rtc.messaging.Message;
import com.sinch.android.rtc.messaging.MessageClient;
import com.sinch.android.rtc.messaging.MessageClientListener;
import com.sinch.android.rtc.messaging.MessageDeliveryInfo;
import com.sinch.android.rtc.messaging.MessageFailureInfo;
import com.sinch.android.rtc.messaging.WritableMessage;
import java.util.Arrays;
import java.util.List;
/**
* Created by RR on 12/6/2015.
*/
public class ChatActivity extends ActionBarActivity {
private String recipientId;
private EditText messageBodyField;
private String messageBody;
private MessageService.MessageServiceInterface messageService;
private String currentUserId;
private ServiceConnection serviceConnection = new MyServiceConnection();
ListView messagesList;
MessageAdapter messageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatactivity);
bindService(new Intent(this, MessageService.class), serviceConnection, BIND_AUTO_CREATE);
//get recipientId from the intent
Intent intent = getIntent();
recipientId = intent.getStringExtra("RECIPIENT_ID");
currentUserId = ParseUser.getCurrentUser().getObjectId();
messageBodyField = (EditText) findViewById(R.id.messageBodyField);
messagesList = (ListView) findViewById(R.id.listMessages);
messageAdapter = new MessageAdapter(this);
messagesList.setAdapter(messageAdapter);
String[] cuserIds = {currentUserId, recipientId};
String[] ruserIds = {recipientId,currentUserId};
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereContainedIn("senderId", Arrays.asList(cuserIds));
query.whereContainedIn("recipientId", Arrays.asList(ruserIds));
query.orderByAscending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> messageList, com.parse.ParseException e) {
if (e == null) {
for (int i = 0; i < messageList.size(); i++) {
WritableMessage message = new WritableMessage(messageList.get(i).get("recipientId").toString(), messageList.get(i).get("messageText").toString());
if (messageList.get(i).get("senderId").toString().equals(currentUserId)) {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_OUTGOING);
} else {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_INCOMING);
}
}
}
}
});
//listen for a click on the send button
findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//send the message!
messageBody = messageBodyField.getText().toString();
if (messageBody.equals("")) {
Toast.makeText(getApplicationContext(), "Please enter a message", Toast.LENGTH_SHORT).show();
return;
}else {
messageService.sendMessage(recipientId, messageBody);
messageBodyField.setText("");
}
}
});
}
//unbind the service when the activity is destroyed
#Override
public void onDestroy() {
unbindService(serviceConnection);
messageService.removeMessageClientListener(new MyMessageClientListener());
super.onDestroy();
}
private class MyServiceConnection implements ServiceConnection {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
messageService = (MessageService.MessageServiceInterface) iBinder;
messageService.addMessageClientListener(new MyMessageClientListener());
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
messageService = null;
}
}
private class MyMessageClientListener implements MessageClientListener {
//Notify the user if their message failed to send
#Override
public void onMessageFailed(MessageClient client, Message message,
MessageFailureInfo failureInfo) {
Toast.makeText(getApplicationContext(), "Message failed to send." + failureInfo.getSinchError().getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onIncomingMessage(MessageClient client, Message message) {
//Display an incoming message
if (message.getSenderId().equals(recipientId)) {
WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_INCOMING);
}
}
#Override
public void onMessageSent(MessageClient client, Message message, final String recipientId) {
//Display the message that was just sent
//Later, I'll show you how to store the
//message in Parse, so you can retrieve and
//display them every time the conversation is opened
//WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
//messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
Toast.makeText(getApplicationContext(), "Message successfully senT.", Toast.LENGTH_SHORT).show();
final WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
//only add message to parse database if it doesn't already exist there
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereEqualTo("sinchId", message.getMessageId());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> messageList, com.parse.ParseException e) {
if (e == null) {
if (messageList.size() == 0) {
ParseObject parseMessage = new ParseObject("ParseMessage");
parseMessage.put("senderId", currentUserId);
parseMessage.put("recipientId", recipientId);
parseMessage.put("messageText", writableMessage.getTextBody());
parseMessage.put("sinchId", writableMessage.getMessageId());
parseMessage.saveInBackground();
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
}
}
}
});
}
//Do you want to notify your user when the message is delivered?
#Override
public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {}
//Don't worry about this right now
#Override
public void onShouldSendPushData(MessageClient client, Message message, List<PushPair> pushPairs) {}
}
}
And this is my MessageService.java
package com.app.knowtes;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import com.parse.ParseUser;
import com.sinch.android.rtc.ClientRegistration;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchClientListener;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.messaging.MessageClient;
import com.sinch.android.rtc.messaging.MessageClientListener;
import com.sinch.android.rtc.messaging.WritableMessage;
/**
* Created by RR on 12/4/2015.
*/
public class MessageService extends Service implements SinchClientListener {
private static final String APP_KEY = "XXXXXXXXXXXXXXXXXXX";
private static final String APP_SECRET = "XXXXXXXXXXXXXXXX";
private static final String ENVIRONMENT = "sandbox.sinch.com";
private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
private SinchClient sinchClient = null;
private MessageClient messageClient = null;
private String currentUserId;
private Intent broadcastIntent = new Intent("com.app.knowtes.ChatListActivity");
private LocalBroadcastManager broadcaster;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//get the current user id from Parse
currentUserId = ParseUser.getCurrentUser().getObjectId();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
broadcaster = LocalBroadcastManager.getInstance(this);
return super.onStartCommand(intent, flags, startId);
}
public void startSinchClient(String username) {
sinchClient = Sinch.getSinchClientBuilder()
.context(this)
.userId(username)
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
//this client listener requires that you define
//a few methods below
sinchClient.addSinchClientListener(this);
//messaging is "turned-on", but calling is not
sinchClient.setSupportMessaging(true);
sinchClient.setSupportActiveConnectionInBackground(true);
sinchClient.checkManifest();
sinchClient.start();
}
private boolean isSinchClientStarted() {
return sinchClient != null && sinchClient.isStarted();
}
//The next 5 methods are for the sinch client listener
#Override
public void onClientFailed(SinchClient client, SinchError error) {
sinchClient = null;
broadcastIntent.putExtra("success", false);
broadcaster.sendBroadcast(broadcastIntent);
}
#Override
public void onClientStarted(SinchClient client) {
client.startListeningOnActiveConnection();
messageClient = client.getMessageClient();
broadcastIntent.putExtra("success", true);
broadcaster.sendBroadcast(broadcastIntent);
}
#Override
public void onClientStopped(SinchClient client) {
sinchClient = null;
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration clientRegistration) {}
#Override
public void onLogMessage(int level, String area, String message) {}
#Override
public IBinder onBind(Intent intent) {
return serviceInterface;
}
public void sendMessage(String recipientUserId, String textBody) {
if (messageClient != null) {
WritableMessage message = new WritableMessage(recipientUserId, textBody);
messageClient.send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.removeMessageClientListener(listener);
}
}
#Override
public void onDestroy() {
sinchClient.stopListeningOnActiveConnection();
//sinchClient.stop();
sinchClient.terminate();
}
//public interface for ListUsersActivity & MessagingActivity
public class MessageServiceInterface extends Binder {
public void sendMessage(String recipientUserId, String textBody) {
MessageService.this.sendMessage(recipientUserId, textBody);
}
public void addMessageClientListener(MessageClientListener listener) {
MessageService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
MessageService.this.removeMessageClientListener(listener);
}
public boolean isSinchClientStarted() {
return MessageService.this.isSinchClientStarted();
}
public void terminateSinchClient(){
}
}
}
enter code here
When you log out, our servers dont know that the messages have been delivered to that device. We keep messages for delivery for 30 days. AS a developer you will experience this more since you are wiping the install when you deploy.
If you just kill the app and launch it again you will see that its not delivered again.
There is a couple of ways of avoiding this,
1. Dont log out
2. If you want logout functionality, dont toast as old messages arrive look at time stamp.
or keep track of messages id in your own database
When I first run my app, on cicking on a particular Place Type, it generates every tpe of nearby place like: atm, malls, food,schools etc. within my specified mile radius.
Code for Places Activity:
package www.uneditedmap.com.locationandmap;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import www.uneditedmap.com.locationandmap.model.Places;
import www.uneditedmap.com.locationandmap.parsers.PlacesJSONParser;
public class PlacesActivity extends ListActivity {
TextView placeName;
TextView placeVicinity;
TextView placeStatus;
String locationType;
String myUrl;
ProgressDialog pDialog;
// List<FetchLocationTask> tasks;
List<Places> placesList;
String lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_places);
// Initialize the TextView for vertical Scrolling
placeName = (TextView) findViewById(R.id.place_title);
placeVicinity = (TextView) findViewById(R.id.vicinity);
placeStatus = (TextView) findViewById(R.id.openNow);
// tasks = new ArrayList<>();
//locationFetcher();
Bundle extras = getIntent().getExtras();
if (extras != null) {
locationType = (extras.getString("TAG")).toString();
lat = extras.getString("lat").toString();
lng = extras.getString("lng").toString();
} else {
// set default value for now
locationType = "atm";
}
myUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
+ lat + ","
+ lng
+ "&radius="
+ getString(R.string.radius)
+ "&types="
+ locationType
+ "&sensor=true&key="
+ getString(R.string.google_maps_key);
myUrl = myUrl.replaceAll(" ", "_");
//Log.d("generated URL: ", myUrl);
requestData(myUrl);
}
protected void updatePlaces() {
if (placesList.isEmpty()) {
Toast.makeText(getApplicationContext(), "No Result", Toast.LENGTH_LONG).show();
}
PlacesListAdapter adapter = new PlacesListAdapter(this, R.layout.item_vicinity, placesList);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_places, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_refresh) {
//Toast.makeText(this, locationType, Toast.LENGTH_SHORT).show();
requestData(myUrl);
}
return false;
}
private void requestData(String uri) {
/*
Methods for Volley
Comment out this block and Uncomment AsyncTask to Use the AsyncTask block
The Volley Library uses less lines of code than the AsyncTask
*/
StringRequest request = new StringRequest(uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
placesList = PlacesJSONParser.parseFeed(response);
updatePlaces();
pDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError ex) {
//Toast.makeText(PlacesActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();
Toast.makeText(PlacesActivity.this, "Please Check your network connection and" +
" refresh again", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
// add the request to queue
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
pDialog = new ProgressDialog(PlacesActivity.this);
pDialog.setMessage("Loading locations..");
pDialog.setCancelable(false);
pDialog.show();
//Methods using AsyncTask, Uncomment if using AsyncTask
// FetchLocationTask myTask = new FetchLocationTask();
// myTask.execute(uri);
}
/*
Replacing the AsyncTask with Volley.
To Use the AsyncTask, Comment out the Volley Method inside the RequestData() Method
and Uncomment AsyncTask with the corresponding methods
*/
/*private class FetchLocationTask extends AsyncTask<String, String, List<Places>> {
#Override
protected void onPreExecute() {
//updatePlaces();
pDialog = new ProgressDialog(PlacesActivity.this);
pDialog.setMessage("Loading locations..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected List<Places> doInBackground(String... params) {
String content = HttpManager.getData(params[0]);
placesList = PlacesJSONParser.parseFeed(content);
Log.d("results : ", content);
return placesList;
}
#Override
protected void onPostExecute(List<Places> result) {
if (pDialog.isShowing())
pDialog.dismiss();
if (result == null) {
Toast.makeText(PlacesActivity.this, "Web service not available", Toast.LENGTH_LONG).show();
return;
}
placesList = result;
updatePlaces();
}
#Override
protected void onProgressUpdate(String... values) {
// updatePlaces(values[0]);
}
}*/
}
**Code for Restaurant.java**
package www.uneditedmap.com.locationandmap;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
public class Restaurant extends FragmentActivity {
MyLocation mLocation;
String lat, lng;
String[] keywords;
//String restaurants;
//private int defautltId, restaurantId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_map);
// defautltId = R.drawable.ic_default;
// restaurantId = R.drawable.ic_restaurant;
keywords = getResources().getStringArray(R.array.keywords);
mLocation = new MyLocation(this);
//fetch location method
locationFetcher();
//keywords[0]
if (isOnline()) {
// Toast.makeText(getActivity().getBaseContext(), "You clicked "+ keywords[position]
// + " from " + lat + " , " + lng, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, PlacesActivity.class)
.putExtra("TAG", keywords[0])
.putExtra("lat", lat)
.putExtra("lng", lng);
startActivity(intent);
} else {
Toast.makeText(this.getBaseContext(), "Network Isn't Available", Toast.LENGTH_LONG).show();
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public void locationFetcher() {
if (mLocation.canGetLocation()) {
//mLocation.getLocation();
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
lat = String.valueOf(latitude);
lng = String.valueOf(longitude);
} else {
Toast.makeText(this, "LOCATION NOT ACQUIRED,TURN ON A PROVIDER", Toast.LENGTH_SHORT).show();
}
}
}
Code for the cardview where the restaurant.java is first added to the cardview stack:
package www.uneditedmap.com.locationandmap;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by null on 28/02/2015.
*/
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
public static String FAV = "New Activity";
List<EndangeredItem> mItems;
// LayoutInflater inflater;
private Context context;
public GridAdapter() {
super();
//inflater = LayoutInflater.from(viewGroup.getContext())
// this.context=context;
// this.mItems=mItems;
// inflater = LayoutInflater.from(context);
mItems = new ArrayList<EndangeredItem>();
EndangeredItem species = new EndangeredItem();
species.setName("Restaurant");
species.setThumbnail(R.drawable.restaurant);
mItems.add(species);
species = new EndangeredItem();
species.setName("Churches");
species.setThumbnail(R.drawable.church);
mItems.add(species);
species = new EndangeredItem();
species.setName("Laundry");
species.setThumbnail(R.drawable.laundry);
mItems.add(species);
species = new EndangeredItem();
species.setName("Schools");
species.setThumbnail(R.drawable.school);
mItems.add(species);
species = new EndangeredItem();
species.setName("Cinemas");
species.setThumbnail(R.drawable.cinema);
mItems.add(species);
species = new EndangeredItem();
species.setName("Hospitals");
species.setThumbnail(R.drawable.hospital);
mItems.add(species);
species = new EndangeredItem();
species.setName("Tech Centers");
species.setThumbnail(R.drawable.hubs);
mItems.add(species);
species = new EndangeredItem();
species.setName("Clubs");
species.setThumbnail(R.drawable.clubs);
mItems.add(species);
species = new EndangeredItem();
species.setName("Fashion House");
species.setThumbnail(R.drawable.fashion);
mItems.add(species);
species = new EndangeredItem();
species.setName("Banks");
species.setThumbnail(R.drawable.bank);
mItems.add(species);
species = new EndangeredItem();
species.setName("Atms");
species.setThumbnail(R.drawable.atm);
mItems.add(species);
species = new EndangeredItem();
species.setName("Sport Centers");
species.setThumbnail(R.drawable.sportcenters);
mItems.add(species);
species = new EndangeredItem();
species.setName("Supermarkets");
species.setThumbnail(R.drawable.supermarket);
mItems.add(species);
species = new EndangeredItem();
species.setName("Sitouts");
species.setThumbnail(R.drawable.sitouts);
mItems.add(species);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.grid_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
EndangeredItem nature = mItems.get(i);
viewHolder.tvspecies.setText(nature.getName());
viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView imgThumbnail;
public TextView tvspecies;
public ViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail);
tvspecies = (TextView) itemView.findViewById(R.id.tv_species);
imgThumbnail.setOnClickListener(this);
//to enable user clicking long n the cardview image
imgThumbnail.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = null;
switch (getPosition()) {
case 0:
intent = new Intent(context, Restaurant.class);
break;
case 1:
intent = new Intent(context, TestIntent.class);
break;
case 2:
intent = new Intent(context, TestIntent.class);
break;
case 3:
intent = new Intent(context, TestIntent.class);
break;
case 4:
intent = new Intent(context, TestIntent.class);
break;
case 5:
intent = new Intent(context, TestIntent.class);
break;
case 6:
intent = new Intent(context, TestIntent.class);
break;
default:
intent = new Intent(context, MainActivity.class);
break;
}
context.startActivity(intent);
}
#Override
public boolean onLongClick(View view) {
// Intent intent;
// intent = new Intent(context, Favourites.class);
// intent.putExtra(FAV, R.id.img_thumbnail);
// context.startActivity(intent);
Toast.makeText(context, "added to favourites", Toast.LENGTH_SHORT).show();
return false;
}
}
}
My String Array:
<string-array name="keywords">
<item>Restaurants</item>
<item>Churches</item>
<item>Laundry</item>
<item>Schools</item>
<item>Cinemas</item>
<item>Hospitals</item>
<item>Tech Centers</item>
<item>Clubs</item>
<item>Fashion House</item>
<item>Banks</item>
<item>Atms</item>
<item>Sport Centers</item>
<item>Supermarkets</item>
<item>Sitouts</item>
</string-array>
Use this Google API to get food and bars around the location,
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=ADD_LATITUDE,ADD_LONGITUDE&radius=5000&types=food,bar&sensor=true&key=YOUR_GOOGLE_MAP_BROWSER_KEY
Enable GooglePlacesAPI from Google Developers Console.
Generate Browser Key not Android Key, it will not work in this case.
Add this in your AndroidManifest.xml:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
also add this permission:
<uses-permission android:name="android.permission.INTERNET" />
Response:
You will get JSON response when you enter URL in browser.
Use this as your URL String that searches for specific places.
String loginURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=19.9974,73.7876113&radius=2000&type=SBH&name=atm&key=API_KEY_HERE";
The problem is your Nearby Search request contains types=Restaurants, but that isn't a valid value for the types parameter. The valid values are in Table 1 of Place Types documentation. E.g. instead of Restaurants you want restaurant.
A secondary issue is that types is a deprecated parameter. You're only passing one type at a time, so you can easily switch to the fully supported type parameter. See the deprecation notice in the Place Search documentation.
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...
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