AdMob Rewarded Video Ads Failed to Load inside Fragment in Android - android

Admob rewarded video ads fail to load in fragment.
I think there is problem in these two lines
mAd = MobileAds.getRewardedVideoAdInstance(getActivity());
mAd.setRewardedVideoAdListener(this);
Please check the code below.
The code is working fine in Activity but doesn't work in Fragment.
public class FragmentWatchEarn extends Fragment implements RewardedVideoAdListener {
int coins = 0;
View rootView;
Button bAdmob;
TextView tvCoins;
private RewardedVideoAd mAd;//Admob
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_watch_earn, container, false);
bAdmob = (Button) rootView.findViewById(R.id.btnAdmob);
admobAdsPart();
return rootView;
}
private void admobAdsPart() {
mAd = MobileAds.getRewardedVideoAdInstance(getActivity()); //Might me Problem in this line
mAd.setRewardedVideoAdListener(this); //Might me Problem in this line
loadAd();
bAdmob.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mAd.isLoaded()){
mAd.show();
}else {
Toast.makeText(getActivity(), "Ad not yet loaded", Toast.LENGTH_SHORT).show();
loadAd();
}
}
});
}
private void loadAd() {
if (!mAd.isLoaded()) {
mAd.loadAd("ca-app-pub-5059726881726792/4575431467", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem rewardItem) {
coins = coins + 20;
myRef.setValue("" + coins);
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(getActivity(), "Admob Ad Failed to load", Toast.LENGTH_SHORT).show();
}
}

This code works for me.
With this code you dont have to implement the OnRewardListener in the top side of your XXXXXFragment.java
private RewardedVideoAd mRewardedVideoAd;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_main, container, false);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(getContext());
mRewardedVideoAd.setRewardedVideoAdListener(rewardedVideoAdListener);
CircleImageView circleImageView = (CircleImageView)rootView.findViewById(R.id.btn_play);
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadRewardedVideoAd();
}
});
return rootView;
}
RewardedVideoAdListener rewardedVideoAdListener = new RewardedVideoAdListener() {
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(getActivity(), "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
Toast.makeText(getActivity(), "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
Toast.makeText(getActivity(), "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(getActivity(), "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
////// UpdateDataBase
}
#Override
public void onRewarded(RewardItem reward) {
Toast.makeText(getActivity(), getString(R.string.on_rewarded_video) + " " + reward.getAmount() + " " + reward.getType(), Toast.LENGTH_LONG).show();
// Reward the user.
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(getActivity(), "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(getActivity(), "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show();
}
};
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-#################/##########",
new AdRequest.Builder().build());
}
I hope it can helps you

Try to change:
mAd = MobileAds.getRewardedVideoAdInstance(getContext());
I have same code and it's working.

Related

Call an dialog fragment method from Activity to Dialog Fragment

I am showing one dialog fragment (showing progress ) in my activity . Calling rest api methods are in my activity . Based on rest api results , I need to some progress in the dialog fragment . So I need to call a method of dialog fragment from activity . I tried with event bus , (Firing from Activity caught on Dialog Fragment ) - But events are not caught in dialog fragment . Is there any other solution ?
Fragment Code:
public class SyncProgressFragment extends BaseDialogFragment {
#BindView(R.id.layout_cancel)
LinearLayout layoutCancel;
#BindView(R.id.sync_with_master_breadcrumbs)
BreadcrumbsView syncWithMasterBreadCrumbs;
#BindView(R.id.master_breadcrumbs)
BreadcrumbsView masterBreadCrumbs;
#BindView(R.id.tvStep)
AppCompatTextView tvStep;
#BindView(R.id.tv_create_defect_title)
AppCompatTextView tvTitle;
private ThreadBus bus;
private FragmentManager manager;
private GoogleApiHelper googleApiHelper;
private Handler handler;
private Runnable runnable;
private boolean isOld;
private boolean isSync;
//private long requestId;
private BreadcrumbsView breadcrumbsView;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bus = AppController.getInstance().getBus();
bus.register(this);
googleApiHelper = AppController.getInstance().getGoogleApiHelper();
googleApiHelper.reconnect();
if (getArguments() != null) {
Bundle bundle = getArguments();
isOld = bundle.getBoolean(AppConstants.IS_OLD,false);
isSync = bundle.getBoolean(AppConstants.IS_OLD,false);
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initUI();
}
private void initUI() {
if (isOld && isSync)
tvTitle.setText(getString(R.string.syncing_old_data_with_bo));
else if(!isOld && isSync)
tvTitle.setText(getString(R.string.syncing_data_with_bo));
else {
tvTitle.setText(getString(R.string.downloading_master_data));
}
if(isSync) {
breadcrumbsView = syncWithMasterBreadCrumbs;
syncWithMasterBreadCrumbs.setVisibility(View.VISIBLE);
masterBreadCrumbs.setVisibility(View.GONE);
tvStep.setText(getString(R.string.sending_data));
}
else{
breadcrumbsView = masterBreadCrumbs;
masterBreadCrumbs.setVisibility(View.VISIBLE);
syncWithMasterBreadCrumbs.setVisibility(View.GONE);
tvStep.setText(getString(R.string.getting_master_data));
}
}
private void initValues() {
handler = new Handler();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sync_progress, container, false);
ButterKnife.bind(this, view);
initValues();
return view;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
if (bus != null) {
bus.unregister(this);
}
try {
handler.removeCallbacks(runnable);
} catch (Exception e) {
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void setCancelable(boolean cancelable) {
super.setCancelable(cancelable);
}
#Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
try {
handler.removeCallbacks(runnable);
} catch (Exception e) {
}
}
#OnClick({R.id.img_close, R.id.layout_cancel})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.layout_cancel:
case R.id.img_close:
dismissAllowingStateLoss();
break;
}
}
#Subscribe
public void onSyncGotResponse(SyncGotResponse syncGotResponse) {
Utilities.log(SyncProgressFragment.class,"onSyncGotResponse",""+syncGotResponse.isSuccess());
if(syncGotResponse.isSuccess()) {
breadcrumbsView.nextStep();
tvStep.setText(getString(R.string.synced_data_with_bo));
}
else
dismissAllowingStateLoss();
}
#Subscribe
public void onMasterGotResponse(MasterGotResponse masterGotResponse) {
Utilities.log(SyncProgressFragment.class,"onMasterGotResponse",""+masterGotResponse.isSuccess());
if(masterGotResponse.isSuccess()) {
tvStep.setText(getString(R.string.downloaded_data_from_bo));
breadcrumbsView.nextStep();
}
else
dismissAllowingStateLoss();
}
}
Activity Code:
#Override
public void dataSyncSuccess(DataSyncResponse dataSyncResponse) {
bus.post(new SyncGotResponse(true));
}
#Override
public void dataSyncFailure(String msg) {
UiUtils.showToast(getContext(), msg);
bus.post(new SyncGotResponse(false));
}
//Calling Rest Api method
if (CheckInternetConnection(getContext())) {
try {
presenter.data_sync();
Bundle bundle = new Bundle();
bundle.putBoolean(AppConstants.IS_OLD,false);
bundle.putBoolean(AppConstants.IS_SYNC,true);
syncProgressFragment.setArguments(bundle);
syncProgressFragment.setCancelable(false);
syncProgressFragment.show(getSupportFragmentManager(), syncProgressFragment.getTag());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
ShowSanckBarShow();
}

android viewpager2 page buton controller

if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)

adapter is refreshed on second notifyDataSetChanged?

the Adapter won't refresh unless notifyDataSetChanged is executed two times!
but when I track it in the debugger it works perfectly!
That problem happens only on sendRequest method, it works perfectly fine on other methods!
if (friendListHelper.isFriendRequestAlreadySent(user.getId())) {
holder.addFriendBtn.setText("Cancel Request");
holder.addFriendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cancelRequest(view, user, position);
}
});
} else if (friendListHelper.isFriend(user.getId())) {
holder.addFriendBtn.setText("Unfriend");
holder.addFriendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteFriend(view, position, user);
}
});
} else {
holder.addFriendBtn.setText("Add Friend");
holder.addFriendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendRequest(user, view, position);
}
});
}
}
private void deleteFriend(final View view, final int position, QBUser user) {
friendListHelper.removeFriend(user, new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
notifyItemChanged(position);
}
});
}
private void cancelRequest(final View view, QBUser user, final int position) {
friendListHelper.cancelFriendRequest(user.getId(), new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
notifyItemChanged(position);
}
}
private void sendRequest(final QBUser user, final View view, final int position) {
friendListHelper.sendFriendRequest(user, new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
notifyDataSetChanged();
}
});
}

Firebase Recycler Adapter is not showing my Recyclerview in Fragments

Basically i followed the accepted answer of this with few changes in my Activity and it worked perfect. My problem is that I wrote the exact same codes for my Fragment. when I open my app, it doesn't show anything. Before I changed my code in my fragment from a custom Adapter to the FirebaseRecyclerAdapter, everything worked fine.
This is my Fragment class
public class HomeFragment extends BaseFragment {
public Button buttonsrch, openFreezer, openRef, openPantry, scrollToFreezer, scrollToRef, scrollToPantry;
public NestedScrollView scrollView;
public RelativeLayout mFreezerLayout,mRefrigeratorLayout, mPantryLayout;
public FloatingActionButton mAddItems;
public DatabaseReference mDatabaseFreezer;
public RecyclerView mFreezerRecyclerView;
public ArrayList<Event> mDataSet;
private FirebaseRecyclerAdapter<Event, ProductHolder> firebaseRecyclerAdapter;
#Override
public int getLayoutResId() {
return R.layout.fragment_home;
}
#Override
public View inOnCreateView(View root, #Nullable ViewGroup container, Bundle savedInstancesState) {
View view = mRoot;
buttonsrch = view.findViewById(R.id.searchButton);
openPantry = view.findViewById(R.id.ShowMorePantry);
openRef = view.findViewById(R.id.ShowMoreRefrigerator);
openFreezer = view.findViewById(R.id.ShowMoreFreezer);
scrollToFreezer = view.findViewById(R.id.bringToFreezer);
scrollToPantry = view.findViewById(R.id.bringToPantry);
scrollToRef = view.findViewById(R.id.bringToRefrigerator);
scrollView = view.findViewById(R.id.scrollViewHomeFragment);
mFreezerLayout = view.findViewById(R.id.FreezerLayout);
mPantryLayout =view.findViewById(R.id.PantryRelativeLayout);
mRefrigeratorLayout = view.findViewById(R.id.RefrigeratorRelativeLayout);
mAddItems = view.findViewById(R.id.addItems_Inventory);
mAddItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), AddInventoryActivity.class));
}
});
buttonsrch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getActivity(), Search_Activity.class);
getActivity().startActivity(i);
}
});
openPantry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent h = new Intent(getActivity(), PantryActivity.class);
getActivity().startActivity(h);
}
});
openRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent g = new Intent(getActivity(), RefActivity.class);
getActivity().startActivity(g);
}
});
openFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent s = new Intent(getActivity(), FreezerActivity.class);
getActivity().startActivity(s);
}
});
scrollToFreezer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToFreezer();
}
});
scrollToRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToRef();
}
});
scrollToPantry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FocusToPantry();
}
});
mDataSet = new ArrayList<>();
mFreezerRecyclerView = view.findViewById(R.id.FreezerRecyclerView);
mFreezerRecyclerView.setHasFixedSize(true);
mFreezerRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mDatabaseFreezer = FirebaseDatabase.getInstance().getReference().child("FreezerItems");
Query query = mDatabaseFreezer;
FirebaseRecyclerOptions<Event> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Event>()
.setQuery(query, Event.class).build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, ProductHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(ProductHolder holder, int position, Event model) {
model = mDataSet.get(position);
holder.mItemName.setText(model.getName());
holder.mItemDate.setText(model.getDate());
final Event finalModel = model;
holder.mDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseFreezer.child(finalModel.get_id()).removeValue();
}
});
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_view_row_inventory,parent,false);
return new ProductHolder(view);
}
};
mDatabaseFreezer.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap<String, String> value = (HashMap<String,String>) dataSnapshot.getValue();
if (value != null) {
String name = value.get("Name");
String date = value.get("Date");
String key = value.get("Key");
mDataSet.add(new Event(name,date,null, key));
Collections.sort(mDataSet, new Comparator<Event>() {
#Override
public int compare(Event event, Event t1) {
if (event.getDate() == null || t1.getDate() == null)
return 0;
return event.getDate().compareTo(t1.getDate());
}
});
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFreezerRecyclerView.setAdapter(firebaseRecyclerAdapter);
return root;
}
private class ProductHolder extends RecyclerView.ViewHolder{
private TextView mItemName, mItemDate;
private Button mDeleteBtn;
public ProductHolder(View itemView) {
super(itemView);
mItemName = itemView.findViewById(R.id.ItemNameTxtView);
mItemDate = itemView.findViewById(R.id.BestBeoforeTxtView);
mDeleteBtn = itemView.findViewById(R.id.deleteItem);
}
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if (firebaseRecyclerAdapter != null){
firebaseRecyclerAdapter.startListening();
}
}
private void FocusToFreezer(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mFreezerLayout.getTop());
}
});
}
private void FocusToRef(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mRefrigeratorLayout.getTop());
}
});
}
private void FocusToPantry(){
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, mPantryLayout.getTop());
}
});
}
}
The only difference I could find is OnStart() and onStop() in activity are protected while on fragments are public
EDIT I found another page with the same problem and apparently FirebaseRecyclerAdapter doesn't work well with Fragments
I finally found an answer
simply remove mFreezerRecyclerView.setHasFixedSize(true);

How to connect WebSocket to Android Applicaton?

I am new in Android. I want to make a demo where I can connect my mobile phone to Server which is running on Different computer. My Backend gave me WebSocket URL. I am implementing then I able to get browser message on my phone but I can't send message to server. What I did, its here. Please guide me
public class MainActivity extends Activity {
private WebSocketClient mWebSocketClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectWebSocket();
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://xx.xxxxx.xxxxx.com:9000");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
#Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView) findViewById(R.id.messages);
textView.setText(textView.getText() + "\n" + message);
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.message);
mWebSocketClient.send(editText.getText().toString());
editText.setText("");
}
}

Categories

Resources