Nearby.Messages API seems not to be working - android

I'm not being able to publish messages with Nearby.Messages, although the Subscribe method seems to be working well. I've already created new credentials for Nearby in my Google Developer Console, made sure both the SHA-1's of my computer, and the app in the PlayStore are associated with those credentials, as well as the app's package name.
As I added an OnSuccessListener to both Publish, and Subscribe, within onStart, I noticed that the Subscribe method works well, while the Publish one Fails. The error code is 2806 - Forbidden.
It used to work just the way it is. Only after I uploaded the app to the Play Store, and had to add a new OAuth 2.0 Client ID, did it stop working, on publishing the desired Message. I've maintained the previous ID, as well, so I continue testing on my device, installing from Android Studio. Meanwhile, I've also re-created both ID's in the Console, but the problem still occurs. The Nearby function is also active, on the Console.
Adding the Fragment's code below:
package co.thanker.fragments;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.messages.Message;
import com.google.android.gms.nearby.messages.MessageListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import co.thanker.R;
public class FindFragment extends Fragment {
private final String TAG = "FindFragment";
private final String OUR_USER_ID = "our-user-id";
private final String OUR_USER_COUNTRY = "our-user-country";
private final String USER_ID_STRING = "user-id-string";
private final String THANKER_ID_STRING = "thanker-id-string";
private final String USER_COUNTRY = "user-country";
private final String CONTINUE_SENDING_ID = "continue-sending-user-id";
private final String ACTIVATED_THANKS = "activated-thanks";
private Message mSendingMessage;
private MessageListener mMessageListener;
private FirebaseAuth mAuth;
private String mCountry;
private String mUserId;
private boolean mActivatedThanks;
private ImageView mGifFind;
private ProgressBar mProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_find, container, false);
Log.v(TAG, "Entering FindFragment");
mAuth = FirebaseAuth.getInstance();
mActivatedThanks = true;
mGifFind = (ImageView) view.findViewById(R.id.gif_find);
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
if(getArguments() != null){
Log.v(TAG, "Finding passing Country. Thanks Fragment. GetArguments() exists");
mUserId = getArguments().getString(THANKER_ID_STRING);
mCountry = getArguments().getString(OUR_USER_COUNTRY);
}
else {
Log.v(TAG, "Finding passing Country. Thanks Fragment. GetArguments() does not exist");
mUserId = mAuth.getCurrentUser().getUid();
}
Log.v(TAG, "Nearby. Thanks got in Thanks Fragment: " + mCountry + ". User ID: " + mUserId);
if(getActivity() != null){
Glide.with(getActivity()).load(R.drawable.nearby_search).into(mGifFind);
mProgressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN );
}
mMessageListener = new MessageListener() {
#Override
public void onFound(Message message) {
Log.d(TAG, "Nearby. Found message: " + new String(message.getContent()));
final String otherUserId = new String(message.getContent()).trim();
if(!otherUserId.equalsIgnoreCase(mAuth.getCurrentUser().getUid())){
Fragment otherUserProfileFragment = new OtherProfileFragment();
Bundle userInfoBundle = new Bundle();
userInfoBundle.putString(USER_ID_STRING, otherUserId);
userInfoBundle.putString(OUR_USER_ID, mUserId);
userInfoBundle.putString(OUR_USER_COUNTRY, mCountry);
userInfoBundle.putBoolean(ACTIVATED_THANKS, mActivatedThanks);
userInfoBundle.putBoolean(CONTINUE_SENDING_ID, true);
otherUserProfileFragment.setArguments(userInfoBundle);
if(getActivity() != null){
mProgressBar.setVisibility(View.GONE);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, otherUserProfileFragment).addToBackStack(null).commit();
}
}
}
#Override
public void onLost(Message message) {
Log.d(TAG, "Nearby. Lost sight of message: " + new String(message.getContent()));
}
};
byte [] userIdInBytes = mUserId.getBytes();
mSendingMessage = new Message(userIdInBytes);
Log.v(TAG, "Nearby. Sending Message: " + new String(mSendingMessage.getContent()));
return view;
}
#Override
public void onStart(){
super.onStart();
if(getActivity() != null){
Nearby.getMessagesClient(getActivity()).publish(mSendingMessage).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v(TAG, "Nearby. Publishing key");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.v(TAG, "Nearby. Couldn\'t publish key. Error: " + e.toString());
}
});
Nearby.getMessagesClient(getActivity()).subscribe(mMessageListener).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v(TAG, "Nearby. Subscribing incoming message");
}
});
}
}
#Override
public void onStop(){
if(getActivity() != null){
Nearby.getMessagesClient(getActivity()).unpublish(mSendingMessage);
Nearby.getMessagesClient(getActivity()).unsubscribe(mMessageListener);
Log.v(TAG, "Nearby. Unpublished keys");
}
super.onStop();
}
}
Really appreciate your help!
Best regards,

Related

Getting Error in onResponse in Retrofit

I am a newbie to the android world. I am trying to develop an app for my school project and stumble upon this issue. please someone help me.
My fragment code is bellow. Where I want to fill up a form with Image and upload to PHP, Mysql server for registration. But the app is crashing.
package com.dgdev.mtmicds;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.dgdev.mtmicds.DbAccess.Remote.APIClient;
import com.dgdev.mtmicds.DbAccess.Remote.ApiInterface;
import com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.app.Activity.RESULT_OK;
import static android.provider.MediaStore.Images.Media.*;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;
/**
* A simple {#link Fragment} subclass.
*/
public class ProfileFragment extends Fragment {
View view;
AppCompatImageView imageView;
AppCompatEditText etFullname, etEmail, etDob, etMobile, etPsw, etRePsw, etAddr;
AppCompatButton btnRegister, btnCancel;
private static final int IMAGE_REQUEST = 7777;
Bitmap bitmap;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
imageView = (AppCompatImageView) view.findViewById(R.id.ProfileDP);
etFullname = (AppCompatEditText) view.findViewById(R.id.tvfullanme);
etEmail = (AppCompatEditText) view.findViewById(R.id.tvemail);
etDob = (AppCompatEditText) view.findViewById(R.id.tvdob);
etPsw = (AppCompatEditText) view.findViewById(R.id.tvpsw);
etRePsw = (AppCompatEditText) view.findViewById(R.id.tvpsw_re);
etAddr = (AppCompatEditText) view.findViewById(R.id.tvaddr);
etMobile = (AppCompatEditText) view.findViewById(R.id.tvmobile);
btnRegister = (AppCompatButton) view.findViewById(R.id.btnRegister);
btnCancel = (AppCompatButton) view.findViewById(R.id.btnCancel);
/*-----------------------------------------------------------------------------*/
/* this onClickListener will be responsible for getting image URI from gallery */
/*-----------------------------------------------------------------------------*/
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImageFromGallery();
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadData();
}
});
return view;
}
private void uploadData() {
String fullname = etFullname.getText().toString();
String dob = convertTOMysqlDate(etDob.getText().toString());
String mobile = etMobile.getText().toString();
String addr = etAddr.getText().toString();
String psw = etPsw.getText().toString();
String prof_pic = imageToString();
Toast.makeText(view.getContext(), dob, Toast.LENGTH_LONG).show();
ApiInterface apiInterface = APIClient.GetClient().create(ApiInterface.class);
Call<UserRegistrationModel> call = apiInterface.RegisterUser(fullname, dob, mobile, addr, psw, prof_pic);
call.enqueue(new Callback<UserRegistrationModel>() {
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
UserRegistrationModel res = response.body();
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<UserRegistrationModel> call, Throwable t) {
Toast.makeText(view.getContext(), "You are not able to talk to server!", Toast.LENGTH_LONG).show();
}
});
}
private String convertTOMysqlDate(String s) {
String $MysqlDateString;
String[] DateParts = s.split("/");
$MysqlDateString = DateParts[2] + "-" + DateParts[1] + "-" + DateParts[0];
return $MysqlDateString;
}
private void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap = getBitmap(getActivity().getApplicationContext().getContentResolver(), path);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String imageToString() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, outputStream);
byte[] ImageBytes = outputStream.toByteArray();
return Base64.encodeToString(ImageBytes, Base64.DEFAULT);
}
}
And I am getting bellow message in logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel.getStatus()' on a null object reference
at com.dgdev.mtmicds.ProfileFragment$3.onResponse(ProfileFragment.java:105)
Please Help me...I am a newbie...
Try this
#Override
public void onResponse(Call<UserRegistrationModel> call, Response<UserRegistrationModel> response) {
if(response.isSuccessful()) {
UserRegistrationModel res = response.body();
if(res!=null) {
Toast.makeText(view.getContext(), res.getStatus(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(view.getContext(), "Didn't get response", Toast.LENGTH_LONG).show();
}
}
}
Your com.dgdev.mtmicds.DbAccess.Remote.UserRegistrationModel is null. Check whether it is being alloted any value by getting in debug mode. Run the code step by step in debug mode and check how it is getting initialized.
Hint: Check this line of your code in debugger:
UserRegistrationModel res = response.body();

Android Wear DataMap onDataChanged() not called for data from other device only

I'm making a library that uses Android Wear's DataMap Api to send information between a Wear device and a phone. I've got the DataMap Api working with another project, but despite using the same steps, it doesn't seem to work in this one. If I use putDataItem on the wear device, or the phone, onDataChanged is only called on the device that changed the data, not the other device.
I've looked everywhere else I could find. I've included a timestamp in my data to make sure the data changes, I've set the PutDataRequest as Urgent with setUrgent() to make sure it gets sent immediately, and I've made sure the onResult returns true when I send the data. The gms versions in the manifest match, and I've tried setting up the intent filter in the manifest too.
Here's the code I've been using:
Phone Part:
package a.package.name; //I've changed this here, to hide stuff.. it's the same as below, though.
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
public class WatchCommsPhone implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, ResultCallback {
public static final String DATA_PATH_WATCH = "/watch_comms1";
public static final String DATA_PATH_PHONE = "/watch_comms2";
private GoogleApiClient gac;
Context c;
WatchCommsCallback wcc;
Handler h = new Handler();
public WatchCommsPhone(Context currentContext, WatchCommsCallback callback){
wcc = callback;
c = currentContext;
gac = new GoogleApiClient.Builder(c).addApi(Wearable.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
gac.connect();
}
public void sendString(String message,long timestamp, String tag){
PutDataMapRequest pdmr = PutDataMapRequest.create(DATA_PATH_PHONE);
DataMap dm = pdmr.getDataMap();
Asset a = Asset.createFromBytes(message.getBytes());
dm.putAsset("data",a);
dm.putLong("timestamp", timestamp);
dm.putString("tag",tag);
PutDataRequest pdr = pdmr.asPutDataRequest();
pdr.setUrgent();
Wearable.DataApi.putDataItem(gac,pdr).setResultCallback(this);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("WatchCommsPhone","Watch Comms Watch: Connected");
Wearable.DataApi.addListener(gac,this);
}
#Override
public void onConnectionSuspended(int i) {
Log.d("WatchCommsPhone","Watch Comms Watch: Connection Suspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e("WatchCommsPhone","Watch Comms Watch: Connection Failed");
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) { //This gets called when you get data!
Log.d("WatchCommsPhone", "On Data Changed!");
for (DataEvent event: dataEventBuffer){
if (event.getType() == DataEvent.TYPE_CHANGED){
Log.d("WatchCommsPhone","Got data of path: " + event.getDataItem().getUri().getPath());
if(event.getDataItem().getUri().getPath().equals(DATA_PATH_WATCH)){
Log.d("WatchCommsPhone","Got data from watch.");
DataMap dm = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
String tag = dm.getString("tag");
Long timestamp = dm.getLong("timestamp");
String data = dm.getString("data");
ProcessData pd = new ProcessData(tag,data,timestamp);
h.post(pd);
}
}
}
}
#Override
public void onResult(#NonNull Result result) {
Log.d("WatchCommsPhone","onResultCalled: " + result.getStatus().isSuccess());
}
public interface WatchCommsCallback{
void onWatchMessageReceived(String tag, String message, long timestamp);
}
public class ProcessData implements Runnable{
String tag;
String data;
Long timestamp;
public ProcessData(String receivedTag, String receivedData, Long receivedTimestamp){
tag = receivedTag;
data = receivedData;
timestamp = receivedTimestamp;
}
#Override
public void run(){
wcc.onWatchMessageReceived(tag,data,timestamp);
}
}
}
Then the Wear part:
package a.package.name; //I've changed this here, to hide stuff.. it's the same as above, though.
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
public class WatchCommsWatch implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, DataApi.DataListener, ResultCallback {
public static final String DATA_PATH_WATCH = "/watch_comms1";
public static final String DATA_PATH_PHONE = "/watch_comms2";
Context c;
GoogleApiClient gac;
WatchCommsCallback wcc;
Handler h = new Handler();
public WatchCommsWatch(Context currentContext,WatchCommsCallback callback){
wcc = callback;
c = currentContext;
gac = new GoogleApiClient.Builder(c).addApi(Wearable.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
gac.connect();
}
public void sendString(String message,long timestamp, String tag){
PutDataMapRequest pdmr = PutDataMapRequest.create(DATA_PATH_WATCH);
pdmr.setUrgent();
DataMap dm = pdmr.getDataMap();
Asset a = Asset.createFromBytes(message.getBytes());
dm.putAsset("data",a);
dm.putLong("timestamp", timestamp);
dm.putString("tag",tag);
PutDataRequest pdr = pdmr.asPutDataRequest();
pdr.setUrgent();
Wearable.DataApi.putDataItem(gac,pdr).setResultCallback(this);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("WatchCommsWatch","Watch Connected.");
Wearable.DataApi.addListener(gac,this);
}
#Override
public void onConnectionSuspended(int i) {
Log.d("WatchCommsWatch","Watch Connection Suspended.");
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d("WatchCommsWatch","onDataChanged Called.");
for (DataEvent event: dataEventBuffer){
if (event.getType() == DataEvent.TYPE_CHANGED){
if(event.getDataItem().getUri().getPath().equals(DATA_PATH_WATCH)){
Log.d("WatchCommsWatch","Got data from watch.");
DataMap dm = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
String tag = dm.getString("tag");
Long timestamp = dm.getLong("timestamp");
Asset dataAsset = dm.getAsset("data");
//String data = new String(dataAsset.getData());
String data = tag;
ProcessData pd = new ProcessData(tag,data,timestamp);
h.post(pd);
}
}
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e("WatchCommsWatch","WatchCommsWatch: Connection Failed.");
}
#Override
public void onResult(#NonNull Result result) {
Log.d("WatchCommsWatch","onResultCalled: " + result.getStatus().isSuccess());
}
public interface WatchCommsCallback{
void onWatchMessageReceived(String message, String tag, long timestamp);
}
public class ProcessData implements Runnable{
String tag;
String data;
Long timestamp;
public ProcessData(String receivedTag, String receivedData, Long receivedTimestamp){
tag = receivedTag;
data = receivedData;
timestamp = receivedTimestamp;
}
#Override
public void run(){
wcc.onWatchMessageReceived(tag,data,timestamp);
}
}
}
Thanks!
Of course you are free to choose their own way, but for my taste i prefer RXWear from Patloev
https://github.com/patloew/RxWear
See this snippet from my E52 watchface
Receive complex obj data from wear:
rxWear.message().listen("/dataMap", MessageApi.FILTER_LITERAL)
.compose(MessageEventGetDataMap.noFilter())
.subscribe(dataMap -> {
// String title = dataMap.getString("title", getString(R.string.no_message));
if (dataMap.containsKey("alWearTimersCategories")) {
String json = dataMap.getString("alWearTimersCategories");
alTimersCategories= allData.convertStringToALTimerWorkspace(json);
allData.setAlTimersCategoriesFromWear(alTimersCategories);
if (indata != null) {
timerdataset.refreshInternalData(alTimersCategories.get( iActiveWorkSpaceindex).alTimersCategoryInWorkspace);
}
}
});
Send some to clock:
rxWear.message().sendDataMapToAllRemoteNodes("/dataMap")
.putString("timers", "TimersCategories")
.putString("alTimersCategories", convertALTimerWorkspace(alTimersCategories))
.toObservable()
.subscribe(requestId -> { });
}

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".

skydrive app on phonegap

We are trying to access skydrive using phonegap.We used an activity to call login function of skydrive. But it does not call login function at all.
Would be great help if someone shed light on this.
Here is the code.
Here activity is called from plugin class of phonegap
Intent i = new Intent(myac, DispAct.class);
try{
System.out.println("before start activity");
//i.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
( this.cordova.getActivity()).startActivity(i);
}
catch(Exception e){ System.out.println("in catch"+e);}
Below code is the called activity
package org.apache.cordova;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
import com.microsoft.live.R;
public class DispAct extends Activity
{
log obj;
private Object cordova;
private static final String APP_CLIENT_ID ="00000000400D893E" ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("disp on create");
}
#Override
protected void onStart() {
super.onStart();
System.out.println("disp on start");
obj=new log();
obj.auth = new LiveAuthClient(this.getApplicationContext(), APP_CLIENT_ID);
Iterable<String> scopes = Arrays.asList("wl.basic","wl.signin","wl.skydrive","wl.skydrive_update");
obj.auth.login(this,scopes,obj);//********this is the function which has to call login page but does not work
System.out.println("disp after login");
}
#Override
public void onResume()
{
super.onResume();
//finish();
}
}
final class log implements LiveAuthListener{
String type,message;
LiveConnectClient client;
LiveAuthClient auth;
//Parcel out;
public log()
{
//auth=new LiveAuthClient(this, message);
}
synchronized public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
if(status == LiveStatus.CONNECTED) {
// this.resultTextView.setText("Signed in.");
System.out.println("IN SUCCess");
client = new LiveConnectClient(session);
//download(0);
notify();
}
else {
//this.resultTextView.setText("Not signed in.");
type="ERROR";
message="Not Connected";
client = null;
System.out.println("IN complete err");
notify();
}
}
synchronized public void onAuthError(LiveAuthException exception, Object userState) {
//this.resultTextView.setText("Error signing in: " + exception.getMessage());
client = null;
//type="ERROR";
//message="Error logging in";
System.out.println("IN error");
notify();
}
}
Here activity is displayed but login page does not appear which should appear as the result of login function

Get name and picture after obtaining email address [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I obtain an user's email address via the account manager with the following code :
package g.login;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class GLogin extends Activity {
private AccountManager _accountMgr = null;
private GLogin _this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
_this = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
_accountMgr = AccountManager.get(this);
Account [] accounts = _accountMgr.getAccountsByType("com.google");
String accountsList = "Accounts: " + accounts.length + "\n";
for (Account account : accounts) {
accountsList += account.toString() + "\n";
}
setMessage(accountsList);
} catch (Exception e) {
setMessage(e.toString());
}
Button loginBtn = (Button) findViewById(R.id.login);
loginBtn.setOnClickListener(mLoginListener);
}
private OnClickListener mLoginListener = new OnClickListener() {
public void onClick(View v) {
try {
Account [] accounts = _accountMgr.getAccounts();
if (accounts.length == 0) {
setResult("No Accounts");
return;
}
Account account = accounts[0];
_accountMgr.getAuthToken(account, "mail", false, new GetAuthTokenCallback(), null);
} catch (Exception e) {
setResult(e.toString());
}
}
};
private class GetAuthTokenCallback implements AccountManagerCallback<Bundle> {
public void run(AccountManagerFuture<Bundle> result) {
Bundle bundle;
try {
bundle = result.getResult();
Intent intent = (Intent)bundle.get(AccountManager.KEY_INTENT);
if(intent != null) {
// User input required
startActivity(intent);
} else {
_this.setResult("Token: " + bundle.getString(AccountManager.KEY_AUTHTOKEN) + "\n" +
"KEY_ACCOUNT_NAME: " + bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
Log.e("TOKEN", bundle.getString(AccountManager.KEY_AUTHTOKEN));
}
} catch (Exception e) {
_this.setResult(e.toString());
}
}
};
public void setResult(String msg) {
TextView tv = (TextView) this.findViewById(R.id.result);
tv.setText(msg);
}
public void setMessage(String msg) {
TextView tv = (TextView) this.findViewById(R.id.message);
tv.setText(msg);
}
}
I am able to extract the authtoken and the ACCOUNT_NAME (something like example#gmail.com).
My question is after I have this email how can I get addition details for the user like real name (if shared), profile picture etc. ?

Categories

Resources