Bad Token Exception while adding Progress Dialog in android app widget - android-asynctask

I want to show a spinning refresh when the data is loading but getting this exception. I am using async task for my processing. Please guide how to properly add progress dialog to give the spinning effect. ANy help will be appreciated.
My widget provider class-onUpdate() method
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
//---
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
try {
fetchTask.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mContext = context;
}
protected void onPreExecute(){
mProgressDialog.show();
//updateViews.setViewVisibility(R.id.refresh, View.GONE);
//updateViews.setViewVisibility(R.id.progress, View.VISIBLE);
}
protected Store doInBackground(URL... arg0) {
//my stuff
}
protected void onPostExecute(Store storeObj) {
mProgressDialog.dismiss();
//updateViews.setViewVisibility(R.id.progress, View.GONE);
//updateViews.setViewVisibility(R.id.refresh, View.VISIBLE);
pushWidgetUpdate(mContext,updateViews);
}
My xml
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginLeft="25dp"
android:layout_marginRight="20dp"
android:background="#0079C1"
android:src="#drawable/navigation_refresh"
android:visibility="visible" />
<ProgressBar
android:id="#+id/progress"
android:indeterminate="true"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:visibility="gone" />
</RelativeLayout>

Got it corrected. I had incorrect width, height for button and progress bar, corrected that. Also, made foll. changes to code..Here is the correct one. Nothing to be done in onUpdate.
protected void onPreExecute(){
updateViews.setViewVisibility(R.id.refresh, View.GONE);
updateViews.setViewVisibility(R.id.progress, View.VISIBLE);
pushWidgetUpdate(mContext,updateViews);
}
protected void onPostExecute(Store storeObj) {
//my stuff
updateViews.setViewVisibility(R.id.progress, View.GONE);
updateViews.setViewVisibility(R.id.refresh, View.VISIBLE);
pushWidgetUpdate(mContext,updateViews);
}
//My Layout file
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/refresh"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="20dp"
android:background="#0079C1"
android:src="#drawable/navigation_refresh"
android:visibility="visible" />
<ProgressBar
android:id="#+id/progress"
android:indeterminate="true"
style="?android:attr/progressBarStyle"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_margin="10dp"
android:indeterminateBehavior="cycle"
android:visibility="gone" />
</RelativeLayout>

Related

XAMARIN : programatically created layout lost during page navigation between different activities

I have created a Xamarian Form.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
<ScrollView
android:id="#+id/configureScroll"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/dynamicLinearlayout"
android:orientation="vertical"/>
</ScrollView>
</LinearLayout>
Programatically added a layout to Linearlayout inside the ScrollView.
LinearLayout dynamicL;
protected override void OnCreate(Bundle savedInstanceState)
{
//.....
dynamicL = FindViewById<LinearLayout>(Resource.Id.dynamicLinearLayout);
}
var layout = new LinearLayout(this);
layout.Orientation = Orientation.Horizontal;
layout.Id = 500;
Button btnRemove = new Button(this);
btnRemove.Text = "-";
btnRemove.TextAlignment = TextAlignment.Center;
layout.AddView(btnRemove);
//Add to scroll layout
dynamicL.AddView(layout);
As soon as I navigate to another page and come back it looses the layout. how can i save it?
After dynamically adding views to page.
Once I navigate to home page and comes back.
I create one sample about navigation between different activities, and come back, the layout still appear, please take a look the following code.
Activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:id="#+id/configureScroll"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/dynamicLinearlayout"
android:orientation="vertical"/>
</ScrollView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="btn"
android:id="#+id/button1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="navigation"
android:id="#+id/button2"/>
</LinearLayout>
MainActivity.cs:
public class MainActivity : AppCompatActivity
{
private Button btn;
private LinearLayout dynamicL;
private Button btn1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
btn = FindViewById<Button>(Resource.Id.button1);
btn.Click += Btn_Click;
btn1 = FindViewById<Button>(Resource.Id.button2);
btn1.Click += Btn1_Click;
dynamicL = FindViewById<LinearLayout>(Resource.Id.dynamicLinearlayout);
}
private void Btn1_Click(object sender, EventArgs e)
{
var intent = new Intent(this, typeof(Activity1));
StartActivity(intent);
}
private void Btn_Click(object sender, EventArgs e)
{
var layout = new LinearLayout(this);
Button btn = new Button(this);
btn.Text = "btn";
btn.TextAlignment = Android.Views.TextAlignment.Center;
layout.AddView(btn);
dynamicL.AddView(layout);
}
}
When click Button to navigate to another activity, come back button in device, layout still appear.

Add a toolbar in a MvxPreferenceFragmentCompat

I'm getting some problems creating a settings page using MvxPreferenceFragmentCompat. I've already shown the preferences view, but I could not include the toolbar in the same page.
I'm using XPlatformMenus sample to create my app.
I've already try many solutions like
attempt 1 or attempt 2, but no success.
Here is my current code:
SettingsFragment.cs
[MvxFragment(typeof(MainViewModel), Resource.Id.content_frame)]
[Register("myapp.droid.fragments.SettingsFragment")]
public class SettingsFragment : BasePreferenceFragment<SettingsViewModel>
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.showHamburgerMenu = true;
return base.OnCreateView(inflater, container, savedInstanceState);
}
public override void OnCreatePreferences(Bundle savedInstanceState, string rootKey)
{
this.AddPreferencesFromResource(FragmentId);
}
protected override int FragmentId
{
get
{
return Resource.Layout.fragment_settings;
}
}
}
fragment_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_sync"
android:title="Title sample"
android:summary="Here is the checkbox summary"
android:defaultValue="true" />
</PreferenceScreen>
BasePreferenceFragment
public abstract class BasePreferenceFragment : MvxPreferenceFragmentCompat
{
protected Toolbar _toolbar;
protected MvxActionBarDrawerToggle _drawerToggle;
/// <summary>
/// If true show the hamburger menu
/// </summary>
protected bool showHamburgerMenu = false;
protected BasePreferenceFragment()
{
RetainInstance = true;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = base.OnCreateView(inflater, container, savedInstanceState);
_toolbar = view.FindViewById<Toolbar>(Resource.Id.toolbar);
if (_toolbar != null)
{
((MainActivity)Activity).SetSupportActionBar(_toolbar);
if (showHamburgerMenu)
{
((MainActivity)Activity).SupportActionBar.SetDisplayHomeAsUpEnabled(true);
_drawerToggle = new MvxActionBarDrawerToggle(
Activity, // host Activity
((MainActivity)Activity).DrawerLayout, // DrawerLayout object
_toolbar, // nav drawer icon to replace 'Up' caret
Resource.String.drawer_open, // "open drawer" description
Resource.String.drawer_close // "close drawer" description
);
_drawerToggle.DrawerOpened += (object sender, ActionBarDrawerEventArgs e) =>
{
if (Activity != null)
((MainActivity)Activity).HideSoftKeyboard();
};
((MainActivity)Activity).DrawerLayout.AddDrawerListener(_drawerToggle);
}
}
return view;
}
protected abstract int FragmentId { get; }
public override void OnConfigurationChanged(Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
if (_toolbar != null && null != _drawerToggle)
{
_drawerToggle.OnConfigurationChanged(newConfig);
}
}
public override void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
if (_toolbar != null && null != _drawerToggle)
{
_drawerToggle.SyncState();
}
}
}
public abstract class BasePreferenceFragment<TViewModel> : BasePreferenceFragment where TViewModel : class, IMvxViewModel
{
public new TViewModel ViewModel
{
get { return (TViewModel)base.ViewModel; }
set { base.ViewModel = value; }
}
}
toolbar_actionbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/appbar"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
fragment_setting_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="#layout/toolbar_actionbar" />
<FrameLayout
android:id="#+id/content_frame"
android:layout_below="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
What am I doing wrong? Any idea?

RecyclerView item dynamic Height micro stutter

I use an EndlessAdapter with a RecyclerView to fetch and load few hundred items from server.
Glide takes care to load the images for each row.
If user scrolls slowly, everything works fine, but when he flings, there are some micro stuttering in scrolling.
I think that this happens due to different image height for each row, but I don't know how to eliminate it.
My adapter code:
public final class ImagesAdapter extends EndlessAdapter<Image, ImagesAdapter.imageHolder> {
#NonNull
private static Fragment mFragment;
private OnItemClickListener onItemClickListener;
private static int mScreenWidth;
private int layoutStyle;
public ImagesAdapter(#NonNull Fragment fragment, List<Image> images, int layoutStyle) {
super(fragment.getActivity(), images == null ? new ArrayList<Image>() : images);
mFragment = fragment;
setHasStableIds(true);
mScreenWidth = fragment.getResources().getDisplayMetrics().widthPixels;
this.layoutStyle = layoutStyle;
}
public void changeLayout(int layoutStyle){
this.layoutStyle = layoutStyle;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#Override
public long getItemId(int position) {
return (!isLoadMore(position)) ? mItems.get(position).getId() : -1;
}
#Override
protected imageHolder onCreateItemHolder(ViewGroup parent, int viewType) {
final imageHolder holder;
switch (layoutStyle) {
case 0:
default:
holder = new imageHolder(mInflater.inflate(R.layout.item_image_enhanced_optim, parent, false));
break;
case 1:
holder = new imageHolder(mInflater.inflate(R.layout.item_image, parent, false));
break;
}
return holder;
}
#Override
protected ProgressViewHolder onCreateItemProgressBarHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.progressbar_item, parent, false);
return new ProgressViewHolder(v);
}
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if (holder instanceof ProgressViewHolder) {
((ProgressViewHolder) holder).progressBar.stop();
Timber.d("Stopped progressbar");
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == VIEW_TYPE_ITEM) {
((imageHolder) holder).bind(mItems.get(position));
} else {
((ProgressViewHolder) holder).start();
}
}
public void shuffle(List<Image> images) {
mItems.clear();
this.mItems.addAll(images);
notifyDataSetChanged();
}
final class imageHolder extends RecyclerView.ViewHolder {
#Bind(R.id.item_image_content)
FrameLayout container;
#Bind(R.id.item_image_img)
ImageView mImageView;
#Bind(R.id.item_image_name)
TextView imageName;
#Bind(R.id.item_author_name)
TextView imageAuthorName;
#Bind(R.id.item_author_image)
CircleImageView userImage;
#Bind(R.id.item_image_date)
TextView imageDate;
#Bind(R.id.item_image_comments)
TextView comments;
#Bind(R.id.item_view_on_map)
LinearLayout viewOnMap;
#Bind(R.id.item_view_share)
LinearLayout share;
#Bind(R.id.moreView)
LinearLayout moreView;
#Bind(R.id.progress_image)
LoadingView loadingView;
public imageHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
public void bind(#NonNull final Image image) {
container.setOnClickListener(new onImageClickListener(getAdapterPosition()));
userImage.setOnClickListener(new onAuthorClickListener(userImage, getAdapterPosition()));
viewOnMap.setOnClickListener(new onViewOnMapClickListener(getAdapterPosition()));
share.setOnClickListener(new onShareClickListener(getAdapterPosition()));
moreView.setOnClickListener(new onMoreClickListener(getAdapterPosition()));
loadingView.setVisibility(View.VISIBLE);
imageName.setText(image.getCombinedTitle());
imageAuthorName.setText(image.getAuthor());
imageDate.setText(image.getReadableDate());
comments.setText(image.getComments());
if(!loadingView.isCircling())
loadingView.start();
Glide.with(mFragment)
.load(image.getImageSrc(mScreenWidth))
.crossFade()
.override(mScreenWidth, (int) ((float) mScreenWidth / image.getRatio()))
.listener(new RequestListener<String, GlideDrawable>() {
#Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
loadingView.stop();
loadingView.setVisibility(View.GONE);
return false;
}
})
.into(mImageView);
}
}
and the row item
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_container"
android:layout_marginBottom="5dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_marginTop="5dp"
app:cardCornerRadius="0dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/light_gray"
android:orientation="vertical">
<ImageView
android:id="#+id/item_image_img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
tools:src="#drawable/header"
android:contentDescription="#string/img_content"
android:scaleType="fitXY" />
<FrameLayout
android:id="#+id/item_image_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:foreground="?selectableItemBackgroundBorderless"
android:orientation="vertical" />
</FrameLayout>
<include layout="#layout/item_image_header"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:layout_marginLeft="47dp"
android:visibility="visible"
android:paddingRight="10dp"
android:layout_marginBottom="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:gravity="center_vertical">
<ImageView
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_marginRight="3dp"
android:contentDescription="#string/descr" />
<TextView
android:id="#+id/item_image_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="1"
android:textColor="#color/colorPrimary"
android:textSize="15.0sp"
android:layout_gravity="center_vertical" />
</LinearLayout>
<TextView
android:id="#+id/item_image_comments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="end"
android:maxLines="4"
tools:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:textColor="#android:color/primary_text_light_nodisable"
android:textSize="13.0sp"
android:layout_marginBottom="10dp" />
</LinearLayout>
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:background="#drawable/divider_shape"
android:layout_height="0.5dp" />
<include layout="#layout/item_image_bottom_buttons"/>
</LinearLayout>
Glide stop loading Images When you scroll list very fast it is done to improve the speed of Scrolling and avoiding any jitter
If you want to show images to your user I suggest you to use Picasso.
https://github.com/square/picasso
However Picasso is not good in caching the Images or has a limited Caching
or Either way u use placeHolder to represent the Image.
Edit
Heads up u can do it easily with Glide
Glide.with(getActivity())
.load("http://www.mediafile.com/12364f")
.placeholder(R.drawable.circle_placeholder_drawable)//this will show this image till your image is not fully loaded
.error(R.drawable.error_drawable)// if there is a problem in loading image an error image would be loaded instead
.into(holder.mFileTransferCircleImageView);

Sending sms app inside a Fragment

I'm creating an android using fragments .I have created a an sms fragment for sending sms to a specific number but when it runs well but when i type the message then press send , the app crashes and closes. help me out.
public class SMS extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.fragment, null);
View v = inflater.inflate(R.layout.sms, container, false);
return v;
}
public void sendsms(View v)
{
//refernce the edittext
EditText message=(EditText) v.findViewById(R.id.Messege);
//get the phone the number and the message
String number="0712345678";
String msg=message.getText().toString();
//use the sms manager to send message
SmsManager sm=SmsManager.getDefault();
sm.sendTextMessage(number, null, msg, null, null);
Toast.makeText(getActivity(),"Messege sent",Toast.LENGTH_LONG).show();
}
}
the following is the xml layout that I have used.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="#drawable/log"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send your feedback" />
<EditText
android:id="#+id/Messege"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:hint="Enter your messege"
android:layout_marginTop="15dp"
android:ems="10" >
</EditText>
<Button
android:id="#+id/send"
android:onClick="sendsms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send SMS" />
</LinearLayout>
The onClick() method is run in the UI thread. You don't want to send an SMS message from the UI thread. Try wrapping your sendSMS code in an AsyncTask or create a new Thread to run that code.

TextView not updating

I am developing a chat application using socketIO library. Every thing seems to work fine except the UI updation. I am able to send message to the port and receive from it. But after reception, i cant update textview or any other UI. the code is given below
Any help is most appreciated
NB: the toast is coming, the **updated* message is also showing when next new message comes
chatRoomActivity.java
public class chatRoomActivity extends Activity implements OnClickListener{
int channelId = 0;
public final String SocketURL = "someURL";
String userName = "";
int connectioAttempt = 0;
SocketIOClient socketClient = null;
SocketIOClientOperations sioOps = null;
Button chatRoomSend = null;
EditText chatInput = null;
TextView msgcntr;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_room);
chatRoomSend = (Button)findViewById(R.id.chatRoomSendBtn);
chatInput = (EditText)findViewById(R.id.chatRoomInput);
msgcntr=(TextView)findViewById(R.id.textView1);
chatRoomSend.setOnClickListener(this);
sioOps = new SocketIOClientOperations();
msgcntr = (TextView) findViewById(R.id.textView1);
socketClient = sioOps.connectToSocket(SocketURL);
System.out.println("**********Connected**********");
if(socketClient != null)
{
boolean joined = false;
joined = sioOps.joinChannel(socketClient, channelId);
System.out.println("*******Joined*********");
}
else
{
System.out.println("*******Null*********");
}
socketClient.on("incomingMessage", new EventCallback() {
public void onEvent(JSONArray argument, Acknowledge acknowledge) {
System.out.println("***************New Message*********");
System.out.println("***************"+argument.toString()+"*********");
msgcntr.setText("test");
updateClock();
}
});
}
#Override
public void onClick(View v) {
if(v == chatRoomSend)
{
boolean sent = sioOps.sendNewMessage(socketClient, userName, "empty");
if(sent)
System.out.println("************** Message Sent *********");
else
System.out.println("************** Message Failed *********");
}
}
protected void updateClock() {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "end", Toast.LENGTH_SHORT).show();
msgcntr.setText("test");
System.out.print("************Updated*********");
}
});
}
}
socketIOClientOperations.java
public class SocketIOClientOperations {
public SocketIOClientOperations(){}
public SocketIOClient connectToSocket(String SocketURL)
{
SocketIORequest connectionRequest = new SocketIORequest(SocketURL);
SocketIOClient socketClient = null;
try {
socketClient = SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), connectionRequest, null).get();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
} catch (ExecutionException e) {
e.printStackTrace();
return null;
}
return socketClient;
}
public boolean joinChannel(SocketIOClient client,int channelId)
{
JSONArray joinChannel = new JSONArray();
JSONObject values = new JSONObject();
try {
values.put("channelID", channelId);
joinChannel.put(values);
client.emit("joinChannel", joinChannel);
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
public boolean sendNewMessage(SocketIOClient client,String name,String txt)
{
JSONArray newMsg = new JSONArray();
JSONObject msgBody = new JSONObject();
try {
msgBody.put("From", name);
msgBody.put("Content", txt);
newMsg.put(msgBody);
client.emit("newMessage", newMsg);
System.out.println("***************SendMessage*********");
System.out.println("************** "+newMsg.toString()+" *********");
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
}
chat_room.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#000"
android:padding="10dp"
android:id="#+id/header">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chat Room"
android:textColor="#fff"
android:textSize="14sp"/>
</RelativeLayout>
<ListView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:stackFromBottom="true"
android:layout_above="#+id/footer"
android:layout_below="#+id/header"
android:id="#+id/chatRoomMsgs"
android:background="#cccccc"
android:visibility="gone" />
<TextView
android:id="#+id/msgConatainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/fooer"
android:layout_below="#+id/header"
android:background="#ccc"
android:textColor="#000" />
<RelativeLayout
android:id="#+id/fooer"
android:background="#000"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/chatRoomInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your message...."
android:layout_toLeftOf="#+id/chatRoomSendBtn"
android:layout_alignParentLeft="true"/>
<Button
android:id="#+id/chatRoomSendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_alignParentRight="true" />
</RelativeLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/msgConatainer"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:text="TextView"
android:textColor="#android:color/black" />
</RelativeLayout>
Try this way
private Handler mHandler = new Handler();
mHandler.post(new Runnable() {
public void run() {
msgcntr.setText("test");
}
});

Resources