Hi friends please help me out i am making chating app with the conversion of text and images Whenever user changes the image in his profile it need to be update in the conversion as well but its not getting updated but whenever i sends a new message then the new image is updating and also i dont set the primary key
Here is below link i had tried nothing worked:
How to update the values in Table using Realm android?
Update mutiple rows in table using Realm in Android
public class Chat_history extends AppCompatActivity {
#BindView(R.id.chat_history_toolbar)
CustomToolbar chat_history_toolbar;
#BindView(R.id.sendmessgae)
CustomEditText sendmessgae;
#BindView(R.id.chat_history_list)
ListView chat_history_list;
Chat_history_Adapter chathisadapter;
RealmResults<Chat_history_pojo> chathistorylist;
Realm chatrealm;
BroadcastReceiver chatreceiver;
public static final String BroadCastAction = "com.parallelspace.parallelspace.Chat_history";
RealmChangeListener chatupdatelisterner = new RealmChangeListener() {
#Override
public void onChange(Object element) {
chathisadapter.addmessage(chathistorylist);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_history);
ButterKnife.bind(this);
Realm.init(getApplicationContext());
setSupportActionBar(chat_history_toolbar);
assert getSupportActionBar() != null;
**chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
RealmQuery<Chat_history_pojo> getLoginData= chatrealm.where(Chat_history_pojo.class).beginGroup().equalTo("receiverid", getIntent().getStringExtra("rid")).endGroup();
RealmResults<Chat_history_pojo> registrationRealm = getLoginData.findAll();
for (Chat_history_pojo chtapojo:registrationRealm) {
chtapojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.copyToRealm(registrationRealm);
}
chatrealm.commitTransaction();**
chathistorylist = chatrealm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
chathisadapter = new Chat_history_Adapter(Chat_history.this, chathistorylist);
chat_history_list.setStackFromBottom(true);
chat_history_list.setTranscriptMode(chat_history_list.TRANSCRIPT_MODE_NORMAL);
chat_history_list.setAdapter(chathisadapter);
/*chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Constant.l("Realm Update Called");
RealmResults<Chat_history_pojo> updatehispojo = chatrealm.where(Chat_history_pojo.class).equalTo("receiverid", getIntent().getStringExtra("rid")).findAll();
for(Chat_history_pojo updatepojo:updatehispojo){
updatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatrealm.insertOrUpdate(updatepojo);
chathisadapter.notifyDataSetChanged();
}
}
});*/
sendmessgae.setDrawableClickListener(new DrawableClickListener() {
#Override
public void onClick(DrawablePosition target) {
switch (target) {
case RIGHT:
if (sendmessgae.getText().toString().isEmpty()) {
Constant.t(getApplicationContext(), "Please Enter Message");
} else {
sendmessage();
}
break;
default:
break;
}
}
});
if (getIntent().hasExtra("mtype")) {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
} else {
chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
}
chat_history_toolbar.Whichonclicked("back", new View.OnClickListener() {
#Override
public void onClick(View view) {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
});
chat_history_toolbar.Whichonclicked("toolbar", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chathisintent = new Intent(getApplicationContext(), Detailed_friend.class);
chathisintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
chathisintent.putExtra("rname", getIntent().getStringExtra("rname"));
chathisintent.putExtra("rimage", getIntent().getStringExtra("rimage"));
chathisintent.putExtra("rid", getIntent().getStringExtra("rid"));
startActivity(chathisintent);
}
});
chat_history_toolbar.Whichonclicked("delete", new View.OnClickListener() {
#Override
public void onClick(View v) {
chatrealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Chat_history_pojo> deleteresults = realm.where(Chat_history_pojo.class).beginGroup()
.equalTo("senderid", Session.getUserID(getApplicationContext()))
.equalTo("receiverid", getIntent().getStringExtra("rid"))
.endGroup()
.or()
.beginGroup()
.equalTo("receiverid", Session.getUserID(getApplicationContext()))
.equalTo("senderid", getIntent().getStringExtra("rid"))
.endGroup()
.findAll();
deleteresults.deleteAllFromRealm();
}
});
}
});
chatreceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(getIntent().getStringExtra("rid"));
chatupdatepojo.setReceiverid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(intent.getStringExtra("msg").replace("$", " "));
chatupdatepojo.setType("text");
if (intent.getStringExtra("type").equals("image")) {
chatupdatepojo.setType("image");
} else if (intent.getStringExtra("type").equals("text")) {
chatupdatepojo.setType("text");
}
chatrealm.commitTransaction();
chatrealm.close();
}
};
IntentFilter intfil = new IntentFilter(BroadCastAction);
registerReceiver(chatreceiver, intfil);
}
#Override
protected void onDestroy() {
unregisterReceiver(chatreceiver);
super.onDestroy();
}
#Override
protected void onStart() {
super.onStart();
chatrealm.addChangeListener(chatupdatelisterner);
Session.pushnotification(getApplicationContext());
}
#Override
protected void onStop() {
super.onStop();
chatrealm.removeChangeListener(chatupdatelisterner);
Session.removepushnotification(getApplicationContext());
}
#OnClick(R.id.camera)
public void camera() {
TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(Chat_history.this)
.setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
#Override
public void onImageSelected(Uri uri) {
try {
Bitmap sendimage = MediaStore.Images.Media.getBitmap(Chat_history.this.getContentResolver(), uri);
sendimages(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("rid"), sendimage);
} catch (IOException e) {
Constant.l(e.toString());
}
}
})
.setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
.create();
bottomSheetDialogFragment.show(getSupportFragmentManager());
}
private void sendimages(String sid, String rid, Bitmap sendbitmap) {
Constant.showloader(Chat_history.this);
String sendumageurl = Constant.psurl + "chatdocument&task=send&sender_id=" + sid + "&reciever_id=" + rid;
Constant.l(sendumageurl);
AndroidNetworking.post(sendumageurl).addBodyParameter("image", Constant.getStringImage(sendbitmap)).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
Constant.l(String.valueOf(response));
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setMessage(response.getString("url"));
chatupdatepojo.setType("image");
chatrealm.commitTransaction();
chatrealm.close();
}
} catch (JSONException e) {
Constant.l(e.toString());
Constant.dismissloader();
}
Constant.dismissloader();
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
Constant.dismissloader();
}
});
}
#Override
public void onBackPressed() {
Session.removepushnotification(getApplicationContext());
Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(chathistoryintent);
}
private void sendmessage() {
String schatsendmesg = Constant.psurl + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("rid") + "&message=" + sendmessgae.getText().toString().replace(" ", "$");
Constant.l(schatsendmesg);
AndroidNetworking.get(schatsendmesg).setOkHttpClient(Constant.okClient()).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
chatrealm = Realm.getDefaultInstance();
chatrealm.beginTransaction();
Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
chatupdatepojo.setMessage(sendmessgae.getText().toString());
chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
chatupdatepojo.setType("text");
chatrealm.commitTransaction();
chatrealm.close();
sendmessgae.setText("");
}
} catch (JSONException e) {
Constant.l(e.toString());
}
}
#Override
public void onError(ANError anError) {
Constant.l(anError.toString());
}
});
}
#Override
protected void onResume() {
super.onResume();
Session.pushnotification(getApplicationContext());
}
#Override
protected void onPause() {
super.onPause();
Session.removepushnotification(getApplicationContext());
}
}
Try this way of updation.
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//Here i am checking the condition
RealmQuery<RegistrationRealm> getLoginData= realm.where(RegistrationRealm.class).equalTo("id",1);
//finding the first set if matches the criteria
RegistrationRealm registrationRealm = getLoginData.findFirst();
//setting the values
registrationRealm.setFirstname(firstname);
registrationRealm.setLastname(lastname);
//Updating the same object with new values
realm.copyToRealm(registrationRealm);
//commiting the current transaction
realm.commitTransaction();
If you need to update all, then get a RealmResults object and iterate through
RealmResults<RegistrationRealm> registrationRealm = getLoginData.findAll();
NOTE:
When using realm.copyToRealm() it is important to remember that only the returned object is managed by Realm, so any further changes to the original object will not be persisted.
Realm reference
Related
The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}
When i used mqtt client in other activity they show me error and when i closed client in OnDestroy and then used client in different activity then it didn't give error but setactioncallback didn't work it give no success and no failure
Mainactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
login = findViewById(R.id.btn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String clientId = MqttClient.generateClientId();
client =
new MqttAndroidClient(MainActivity.this, "tcp://broker.hivemq.com:1883",
clientId);
try {
MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d(TAG, "onSuccess");
gotosubscribelist();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d(TAG, "onFailure");
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
});
}
private void gotosubscribelist()
{
Intent intent = new Intent(this,SubscribelistActivity.class);
intent.putExtra("client", String.valueOf(client));
startActivity(intent);
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
client.unregisterResources();
client.close();
}
subscribe activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribelist);
try {
MainActivity.client.connect();
} catch (MqttException e) {
e.printStackTrace();
}
channel = findViewById(R.id.channel);
subscribe = findViewById(R.id.subscribe);
mRec = (RecyclerView) findViewById(R.id.recyclerview);
newlist = new ArrayList<>();
adapter = new ChannelAdapter(this,newlist);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRec.setHasFixedSize(true);
mRec.setLayoutManager(linearLayoutManager);
mRec.setAdapter(adapter);
subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
subscribe();
}
});
}
private void subscribe()
{
Log.e("hi","1");
final String topic = channel.getText().toString();
int qos = 1;
try {
IMqttToken subToken = MainActivity.client.subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.e("suc","create");
newlist.add(topic);
}
#Override
public void onFailure(IMqttToken asyncActionToken,
Throwable exception) {
Log.e("e",exception.getMessage());
}
});
adapter.notifyDataSetChanged();
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
My problem is if i remove client.unregisterResources and client.close in onDestroy then it show
E/ActivityThread: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection#7ce0751 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.example.mqtt.UI.MainActivity has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection#7ce0751 that was originally bound here
and when i put client.unregisterResources and client.close in onDestroy then it didn't show error but in the subscribe function it didn't run onsuccess and onfailure, please give some suggestion
channelactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_channel);
try {
MainActivity.client.connect();
MainActivity.client.isConnected();
} catch (MqttException e) {
e.printStackTrace();
}
message = findViewById(R.id.msg);
publish = findViewById(R.id.publish);
name = getIntent().getExtras().get("currentchannelname").toString();
Rec = (RecyclerView) findViewById(R.id.recyclerview_msg);
newlist = new ArrayList<>();
adapter = new msgAdapter(this,newlist);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
Rec.setHasFixedSize(true);
Rec.setLayoutManager(linearLayoutManager);
Rec.setAdapter(adapter);
getmessage();
publish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
publishmsg();
}
});
}
private void publishmsg()
{
String topic = name;
String payload = message.getText().toString().trim();
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
MainActivity.client.publish(topic, message);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}
}
private void getmessage()
{
MainActivity.client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
newlist.add(message.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
Remove
#Override
protected void onDestroy() {
super.onDestroy();
MainActivity.client.unregisterResources();
MainActivity.client.close();
}
from SubscribeActivity
I use this code to play the full-screen video but I have a problem when it is video playing and moving from the main activity to the full-screen activity occurs freezing of the video for 2-3 seconds This problem occurs only with the releases after 2.8.3 only but with 2.8.0 works Video is smooth
code full: https://github.com/MATPOCKIH/ExoPlayerFullscreen
PlayerViewManager
public class PlayerViewManager {
private static final String TAG = "ExoPlayerViewManager";
public static final String EXTRA_VIDEO_URI = "video_uri";
private static Map<String, PlayerViewManager> instances = new HashMap<>();
private Uri videoUri;
public boolean isPlayerPlaying;
private boolean isMustPlaying;
private UniversalPlayerView universalPlayer;
public static PlayerViewManager getInstance(String videoUri) {
PlayerViewManager instance = instances.get(videoUri);
if (instance == null) {
instance = new PlayerViewManager(videoUri);
instances.put(videoUri, instance);
}
return instance;
}
private PlayerViewManager(String videoUri) {
this.videoUri = Uri.parse(videoUri);
}
public void preparePlayer(PlayerHolderView playerHolderView) {
if (playerHolderView == null) {
return;
}
if (universalPlayer == null) {
universalPlayer = createPlayer(playerHolderView.getContext());
isPlayerPlaying = true;
isMustPlaying = true;
}
universalPlayer.initialize(videoUri, playerHolderView);
}
public void releaseVideoPlayer() {
if (universalPlayer != null) {
universalPlayer.release();
}
universalPlayer = null;
}
public void goToBackground() {
if (universalPlayer != null /*&& !isMustPlaying*/) {
//isPlayerPlaying = player.getPlayWhenReady();
universalPlayer.pause();
}
}
public void goToForeground() {
if (universalPlayer != null && isMustPlaying) {
universalPlayer.play();
}
}
public void pausePlayer(){
if (universalPlayer != null) {
universalPlayer.pause();
isPlayerPlaying = false;
isMustPlaying = false;
}
}
public void playPlayer(){
if (universalPlayer != null) {
universalPlayer.play();
isPlayerPlaying = true;
isMustPlaying = true;
}
}
private UniversalPlayerView createPlayer(Context context){
if (videoUri.getScheme().startsWith("http")){
return new FaceterExoPlayerView(context);
}
return new FaceterExoPlayerView(context);
}
}
FaceterExoPlayerView
public class FaceterExoPlayerView extends UniversalPlayerView {
private Uri videoUri;
private DefaultDataSourceFactory dataSourceFactory;
private SimpleExoPlayer player;
private PlayerView exoPlayerView;
private Context context;
public FaceterExoPlayerView(Context context) {
this.context = context;
}
#Override
public void initialize(Uri videoUri, PlayerHolderView playerHolderView) {
if (playerHolderView == null || videoUri == null)
return;
exoPlayerView = playerHolderView.findViewById(R.id.exo_player);
if (player == null) {
player = ExoPlayerFactory.newSimpleInstance(context, new DefaultTrackSelector());
dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "faceter"));
MediaSource videoSource = buildMediaSource(videoUri, null);
player.prepare(videoSource);
}
player.clearVideoSurface();
player.setVideoTextureView((TextureView) exoPlayerView.getVideoSurfaceView());
exoPlayerView.setPlayer(player);
exoPlayerView.hideController();
setResizeModeFill(playerHolderView.isResizeModeFill());
}
#Override
public void play() {
player.setPlayWhenReady(true);
}
#Override
public void pause() {
player.setPlayWhenReady(false);
}
#SuppressWarnings("unchecked")
private MediaSource buildMediaSource(Uri uri, #Nullable String overrideExtension) {
int type = Util.inferContentType(uri, overrideExtension);
switch (type) {
/*case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new DashManifestParser(), (List<RepresentationKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
buildDataSourceFactory(false))
.setManifestParser(
new FilteringManifestParser<>(
new SsManifestParser(), (List<StreamKey>) getOfflineStreamKeys(uri)))
.createMediaSource(uri);*/
case C.TYPE_HLS:
return new HlsMediaSource.Factory(dataSourceFactory)
/*.setPlaylistParser(
new FilteringManifestParser<>(
new HlsPlaylistParser(), (List<RenditionKey>) getOfflineStreamKeys(uri)))*/
.createMediaSource(uri);
case C.TYPE_OTHER:
return new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
default: {
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
#Override
public void release() {
if (player != null) {
player.release();
}
player = null;
}
#Override
public void setResizeModeFill(boolean isResizeModeFill) {
if (isResizeModeFill) {
exoPlayerView.setResizeMode(RESIZE_MODE_FILL);
} else {
exoPlayerView.setResizeMode(RESIZE_MODE_FIT);
}
}
}
PlayerHolderView.java
public class PlayerHolderView extends FrameLayout {
private String videoUrl;
private boolean isResizeModeFill = true;
private OnUserInteractionListener onUserInteractionListener;
public PlayerHolderView(#NonNull Context context) {
super(context);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PlayerHolderView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.layout_player, this, true);
View controlView = this.findViewById(R.id.exo_controller);
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(videoUrl).pausePlayer();
}
});
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FullscreenVideoActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
getContext().startActivity(intent);
}
});
MainActivity
public class MainActivity extends AppCompatActivity {
private List<PlayerHolderView> playerHolders = new ArrayList<>();
private List<TextView> links = new ArrayList<>();
private List<String> mVideoUrls = new ArrayList<>(
Arrays.asList(
//"http://10.110.3.30/api/Playlists/6a3ecad7-e744-446f-9341-0e0ba834de63?from=2018-09-20&to=2018-09-21"
"https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/hls/TearsOfSteel.m3u8",
"http://redirector.c.youtube.com/videoplayback?id=604ed5ce52eda7ee&itag=22&source=youtube&sparams=ip,ipbits,expire,source,id&ip=0.0.0.0&ipbits=0&expire=19000000000&signature=513F28C7FDCBEC60A66C86C9A393556C99DC47FB.04C88036EEE12565A1ED864A875A58F15D8B5300&key=ik0",
"https://html5demos.com/assets/dizzy.mp4"
//"https://cdn.faceter.io/hls/ab196789-8876-4854-82f3-087e5682d013",
//"https://cdn.faceter.io/hls/65d1c673-6a63-44c8-836b-132449c9462a"
)
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
playerHolders.add((PlayerHolderView) findViewById(R.id.holder1));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder2));
playerHolders.add((PlayerHolderView) findViewById(R.id.holder3));
links.add((TextView) findViewById(R.id.title1));
links.add((TextView) findViewById(R.id.title2));
links.add((TextView) findViewById(R.id.title3));
}
#Override
public void onResume() {
super.onResume();
int i = 0;
for (final String videoUrl : mVideoUrls) {
playerHolders.get(i).setupPlayerView(videoUrl);
playerHolders.get(i).setOnUserInteractionListener(this);
links.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVideoTitleClicked(videoUrl);
}
});
i++;
}
}
#Override
public void onPause() {
super.onPause();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).goToBackground();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
for (String videoUrl : mVideoUrls) {
PlayerViewManager.getInstance(videoUrl).releaseVideoPlayer();
}
}
public void onVideoTitleClicked(String videoUrl) {
Intent intent = new Intent(getBaseContext(), DetailActivity.class);
intent.putExtra(PlayerViewManager.EXTRA_VIDEO_URI, videoUrl);
startActivity(intent);
}
}
FullscreenVideoActivity
public class FullscreenVideoActivity extends AppCompatActivity {
/**
* Some older devices needs a small delay between UI widget updates
* and a change of the status and navigation bar.
*/
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private View mContentView;
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of
// API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
private String mVideoUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_video);
mContentView = findViewById(R.id.enclosing_layout);
PlayerHolderView playerHolderView = findViewById(R.id.player_holder);
playerHolderView.setResizeModeFill(false);
mVideoUri = getIntent().getStringExtra(PlayerViewManager.EXTRA_VIDEO_URI);
PlayerViewManager.getInstance(mVideoUri).preparePlayer(playerHolderView);
/*
// Set the fullscreen button to "close fullscreen" icon
View controlView = playerView.findViewById(R.id.exo_controller);
ImageView fullscreenIcon = controlView.findViewById(R.id.exo_fullscreen_icon);
fullscreenIcon.setImageResource(R.drawable.exo_controls_fullscreen_exit);
controlView.findViewById(R.id.exo_fullscreen_button)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
controlView.findViewById(R.id.exo_play)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).playPlayer();
}
});
controlView.findViewById(R.id.exo_pause)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerViewManager.getInstance(mVideoUri).pausePlayer();
}
});*/
}
#Override
public void onResume() {
super.onResume();
PlayerViewManager.getInstance(mVideoUri).goToForeground();
}
#Override
public void onPause() {
super.onPause();
PlayerViewManager.getInstance(mVideoUri).goToBackground();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide();
}
private void hide() {
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
/**
* Schedules a call to hide() in delay milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide() {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, 100);
}
}
Just try out this code for video freeze problem:
#Override
public void play() {
player.setPlayWhenReady(true);
player.getPlaybackState();
}
#Override
public void pause() {
player.setPlayWhenReady(false);
player.getPlaybackState();
}
Here player.getPlaybackState(); is help full to get it to back state.
I'm having a weird problem in my Android app when casting a Activity to my MainActivity. I'm using GeoFences to broadcasts events to a base activity called NotificationActivity. The NotificationActivity is used in all the other activities I use so when a GeoFence triggers an AlertDialog pops up. Now when a GeoFence triggers and I'm in an activity other than MainActivity, I need to finish the current activity and do a certain action on the MainActivity (switch to a certain tab). In my Application class I'm implementing the Application.ActivityLifeCycleCallbacks, in the onActivityResumed callback I set my currentActivity to the resumed activity (I know a static reference causes memory leaks but I need to fix this).
Here's my application class:
private static Activity currentActivity;
#Override
public void onCreate() {
super.onCreate();
// Setup Fabric
if (AppConfig.getEnvironment() != AppConfig.Environment.Development) {
Fabric.with(this, new Crashlytics(), new Answers());
}
// Init realm
Realm.init(this);
// Init Firebase
FirebaseApp.initializeApp(this);
if (AppConfig.getEnvironment() == AppConfig.Environment.Development) {
// Init Stetho with realm plugin
Stetho.initialize (
Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.build());
}
registerActivityLifecycleCallbacks(this);
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Log.d(Constants.DEBUG, "Activity created: " + activity.toString());
}
#Override
public void onActivityStarted(Activity activity) {
Log.d(Constants.DEBUG, "Activity started: " + activity.toString());
}
#Override
public void onActivityResumed(Activity activity) {
Log.d(Constants.DEBUG, "Activity resumed: " + activity.toString());
currentActivity = activity;
}
#Override
public void onActivityPaused(Activity activity) {
Log.d(Constants.DEBUG, "Activity paused: " + activity.toString());
}
#Override
public void onActivityStopped(Activity activity) {
Log.d(Constants.DEBUG, "Activity stopped: " + activity.toString());
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
Log.d(Constants.DEBUG, "Activity SaveInstanceState: " + activity.toString());
}
#Override
public void onActivityDestroyed(Activity activity) {
Log.d(Constants.DEBUG, "Activity Destroyed: " + activity.toString());
}
public static Activity getCurrentActivity() {
return currentActivity;
}
And here's my NotificationActivity (base) activity:
public abstract class NotificationActivity extends AppCompatActivity {
private BroadcastReceiver onNoticeWithinPoi = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Realm realm = Realm.getDefaultInstance();
Poi poi = realm.where(Poi.class).equalTo("ref", bundle.getString(Constants.POI_KEY_REF)).findFirst();
showAlertWithinPoi(context, poi);
}
}
};
private BroadcastReceiver onNoLocationProviderSet = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
warnUserNoLocationProviderSet();
}
};
private BroadcastReceiver onNoticeOutOfRange = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();
alertNoticeOutOfRange();
}
};
public Fragment getActiveFragment() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String tag = getFragmentManager().getBackStackEntryAt(getFragmentManager().getBackStackEntryCount() - 1).getName();
return getFragmentManager().findFragmentByTag(tag);
}
private void showAlertWithinPoi(final Context context, final Poi poi) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.poi_popup_title));
builder.setMessage(getString(R.string.poi_popup_subtitle));
builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Game currentGame = Helper.getCurrentGame(context);
Game poiGame = null;
Realm realm = Realm.getDefaultInstance();
for (Game game : realm.where(Game.class).findAll()) {
for (Tag tag : game.tags) {
if (tag.poi.ref.equals(poi.ref)) {
poiGame = game;
break;
}
}
if (poiGame != null) {
break;
}
}
if (poiGame != null && poiGame.ref.equals(currentGame.ref)) {
realm.beginTransaction();
currentGame.lastSeenPoi = poi.ref;
realm.commitTransaction();
checkCurrentActivity();
} else if (poiGame != null && !poiGame.ref.equals(currentGame.ref)) {
showAlertDifferentGame(context, poiGame, poi);
}
}
});
builder.setNegativeButton(getString(R.string.later), null);
builder.setIcon(R.drawable.poi_unvisited);
builder.create().show();
}
private void showAlertDifferentGame(final Context context, final Game game, final Poi poi) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(getString(R.string.game_switch_title));
builder.setMessage(getString(R.string.game_switch_message) + " " + LanguageHelper.getGameTitle(game) + " ?");
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
game.lastSeenPoi = poi.ref;
realm.commitTransaction();
SharedPreferencesHelper.saveString(context, Constants.PREF_SELECTED, game.ref);
GeofenceService.updateGeoFences(game, context);
checkCurrentActivity();
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
checkCurrentActivity();
}
});
builder.create().show();
}
private void checkCurrentActivity() {
final Activity currentActivity = GeoFortApplication.getCurrentActivity();
if (currentActivity instanceof MainActivity) {
((MainActivity) currentActivity).switchTab();
} else {
currentActivity.finish();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.d(Constants.DEBUG, "CurrentActivity: " + currentActivity.toString());
((MainActivity) currentActivity).switchTab();
} catch (ClassCastException e) {
Log.e(Constants.EXCEPTION, e.getLocalizedMessage());
}
}
}, 5000);
}
}
private void alertNoticeOutOfRange() {
new AlertDialog.Builder(this)
.setTitle(R.string.error_location_not_close_enough_title)
.setMessage(R.string.error_location_not_close_enough_alert)
.setPositiveButton(R.string.ok, null)
.setIcon(R.drawable.ic_launcher)
.show();
}
private void warnUserNoLocationProviderSet() {
new AlertDialog.Builder(this)
.setTitle(R.string.error_location_not_available_title)
.setMessage(R.string.error_location_services_not_available_text)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO no user location set?
}
})
.setIcon(null)
.show();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filterWithinPoi = new IntentFilter(Constants.NOTIFICATION_WITHIN_POI);
filterWithinPoi.setPriority(2);
registerReceiver(onNoticeWithinPoi, filterWithinPoi);
IntentFilter filterOutOfRange = new IntentFilter(Constants.NOTIFICATION_LOCATION_OUT_OF_RANGE);
filterOutOfRange.setPriority(2);
registerReceiver(onNoticeOutOfRange, filterOutOfRange);
IntentFilter filterLocationProviderOff = new IntentFilter(Constants.NOTIFICATION_LOCATION_PROVIDER_OFF);
registerReceiver(onNoLocationProviderSet, filterLocationProviderOff);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(onNoticeWithinPoi);
unregisterReceiver(onNoticeOutOfRange);
unregisterReceiver(onNoLocationProviderSet);
}
}
you are doing something wrong on else
private void checkCurrentActivity() {
final Activity currentActivity = GeoFortApplication.getCurrentActivity();
if (currentActivity instanceof MainActivity) {
((MainActivity) currentActivity).switchTab();
} else {
currentActivity.finish();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.d(Constants.DEBUG, "CurrentActivity: " + currentActivity.toString());
((MainActivity) currentActivity).switchTab();
} catch (ClassCastException e) {
Log.e(Constants.EXCEPTION, e.getLocalizedMessage());
}
}
}, 5000);
}
}
Within run method the activity is not a MainActivity, as you do check it before.
Fist check
if (activity instanceOf MainActivity){
// do typecast here
}else{
// you should which which instance you have
}
This way you will get rid of classCastException
I wrote code for connecting with Facebook and extracting username,email ID and Profile link .All the extracted details displays in different activity on the click of a button.But I wanted it to display it in the same actiivty as soon the login process is completed successfully.which means I need to edit the code after onSuccess but I don't no how to get the code
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
Button share,details;
ShareDialog shareDialog;
LoginButton login;
ProfilePictureView profile;
Dialog details_dialog;
TextView details_txt;
TextView details_txtx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
login = (LoginButton)findViewById(R.id.login_button);
profile = (ProfilePictureView)findViewById(R.id.picture);
shareDialog = new ShareDialog(this);
share = (Button)findViewById(R.id.share);
details = (Button)findViewById(R.id.details);
login.setReadPermissions("public_profile email");
share.setVisibility(View.INVISIBLE);
details.setVisibility(View.INVISIBLE);
details_dialog = new Dialog(this);
details_dialog.setContentView(R.layout.dialog_details);
details_dialog.setTitle("Details");
details_txtx = (TextView)details_txtx.findViewById(R.id.details_tetx);
details.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
details_dialog.show();
}
});
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(AccessToken.getCurrentAccessToken() != null) {
share.setVisibility(View.INVISIBLE);
details.setVisibility(View.INVISIBLE);
profile.setProfileId(null);
}
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShareLinkContent content = new ShareLinkContent.Builder().build();
shareDialog.show(content);
}
});
login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult ) {
if(AccessToken.getCurrentAccessToken() != null){
RequestData();
share.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
}
});
}
public void RequestData(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if(json != null){
String text = "<b>Name :</b> "+json.getString("name")+"<br><br><b>Email :</b> "+json.getString("email")+"<br><br><b>Profile link :</b> "+json.getString("link");
details_txt.setText(Html.fromHtml(text));
profile.setProfileId(json.getString("id"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
To be Clear: All i wanted is to display the extracted details in the same activity after a successful login can you please help with it.?
please check the following code
protected void connectToFacebook() {
ArrayList<String> list = new ArrayList<String>();
list.add("email");
// LoginManager.getInstance().logInWithReadPermissions(this, list);
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
// Application code
if (response.getError() != null) {
System.out.println("ERROR");
} else {
System.out.println("Success");
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
String fbUserId = json.optString("id");
String fbUserFirstName = json.optString("name");
String fbUserEmail = json.optString("email");
String fbUserProfilePics = "http://graph.facebook.com/" + fbUserId + "/picture?type=large";
callApiForCheckSocialLogin(fbUserId, fbUserFirstName, fbUserEmail, fbUserProfilePics, "fb");
}
Log.v("FaceBook Response :", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
// Log.v("LoginActivity", "" + exception);
Utilities.showToast(mActivity, "" + exception);
}
});
}