Socket IO runOnUiThread doesn't work - android

I have trouble with runOnUiThread in socket io. I use this library. I have listener for some event. If I get this event I change the image. But when I get event image stay as before and I don't understand why it's happen. Maybe someone help or explain me what I'm doing wrong. Thanks in advance. This is my code
private void online(){
SocketService.getSocket().on("online", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "online");
onlineOffline.setImageResource(R.drawable.online);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
}
});
}
});
}
private void offline() {
SocketService.getSocket().on("offline", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "offline");
onlineOffline.setImageResource(R.drawable.offline);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
}
});
}
});
}
EDIT!
Socket connected successfully and I can see message online/offline in the log. Also I debug code and don't show error. Full code
public class ProfileList extends Fragment implements View.OnClickListener{
private int pos=0;
private DecodeBitmap decodeBitmap=new DecodeBitmap();
private ArrayList<String> online = new ArrayList<>();
private ImageView onlineOffline;
private RelativeLayout callToRegion;
private Button callTo;
private Activity activity;
static ProfileList newInstance(int position, ArrayList<String> online) {
ProfileList pageFragment = new ProfileList();
Bundle arguments = new Bundle();
arguments.putInt("page", position);
arguments.putStringArrayList("online", online);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pos = getArguments().getInt("page");
online = getArguments().getStringArrayList("online");
Log.d("myLogs", "page pos: " + pos);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.profile_list_layout, container, false);
Log.d("myLogs","fragment onCreateView pos "+ pos);
callToRegion = (RelativeLayout) rootView.findViewById(R.id.callToRegion);
callTo = (Button) rootView.findViewById(R.id.callTo);
ImageView mainProfileIcon = (ImageView) rootView.findViewById(R.id.mainProfileIcon);
onlineOffline = (ImageView) rootView.findViewById(R.id.onlineOffline);
if(CallPageFragment.online.get(0).equals("empty")){
new LoadDataFromDatabase("relatives", getActivity(), "");
}
if(LoadDataFromDatabase.relativesData.size()==0){
DialogFragment dlgFragment = new ErrorPopupFragment();
int REQUEST_CODE_DIALOG = 101;
dlgFragment.setTargetFragment(this, REQUEST_CODE_DIALOG);
dlgFragment.setCancelable(true);
String dialogTitle = "error_dialog";
dlgFragment.show(getFragmentManager(), dialogTitle);
activity.onBackPressed();
}
else {
callTo.setText(LoadDataFromDatabase.relativesData.get(pos).getFirstName());
File imgFile = new File(LoadDataFromDatabase.relativesData.get(pos).getAvatar());
if (imgFile.exists()) {
mainProfileIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
mainProfileIcon.setImageBitmap(decodeBitmap.decodeSampledBitmapFromResource(LoadDataFromDatabase.relativesData.get(pos).getAvatar(), 300, 300));
}
}
Log.d("myLogs", "all relatives online" + online);
Log.d("myLogs", "all relatives" + LoadDataFromDatabase.relativesData.get(pos).getRelativesId());
if(online.size()==0){
onlineOffline.setImageResource(R.drawable.offline);
Log.d("myLogs", "online false");
}
else {
Log.d("myLogs", "online true " + pos + " " + LoadDataFromDatabase.relativesData.get(pos).getRelativesId());
for(int i=0;i<online.size();i++) {
if (LoadDataFromDatabase.relativesData.get(pos).getRelativesId().equals(online.get(i))) {
Log.d("myLogs", "online id " + LoadDataFromDatabase.relativesData.get(pos).getRelativesId() + " " + online.get(i) + " pos: " + pos);
onlineOffline.setImageResource(R.drawable.online);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
break;
}
else {
onlineOffline.setImageResource(R.drawable.offline);
callTo.setEnabled(false);
}
}
}
try {
MainActivity.textClock.setVisibility(View.VISIBLE);
}
catch(Throwable e) {
Log.d("myLogs", "WTF???!!!!", e);
}
online();
offline();
return rootView;
}
#Override
public void onClick(View v) {
CallPageFragment.currentPosition=pos;
Log.d("myLogs","save currentPosition " + CallPageFragment.currentPosition);
Bundle bundle = new Bundle();
bundle.putString("firstName", LoadDataFromDatabase.relativesData.get(pos).getFirstName());
bundle.putString("avatar", LoadDataFromDatabase.relativesData.get(pos).getAvatar());
bundle.putString("id", LoadDataFromDatabase.relativesData.get(pos).getRelativesId());
Fragment fragment = new CallToFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = activity.getFragmentManager();
fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.content_frame, fragment).commit();
}
private void online(){
SocketService.getSocket().on("online", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "online");
onlineOffline.setImageResource(R.drawable.online);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
}
});
}
});
}
private void offline() {
SocketService.getSocket().on("offline", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "offline");
onlineOffline.setImageResource(R.drawable.offline);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
}
});
}
});
}
#Override
public void onStop() {
super.onStop();
SocketService.getSocket().off("online");
SocketService.getSocket().off("offline");
}
}

I have already solved my issue. I dont know why, but runOnUiThread works fine. I three days tried to find whats wrong with my code and than it have just work. It's fully working code
private void online(){
if (SocketService.getSocket() != null)
SocketService.getSocket().on("online", new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d("myLogs", "online");
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "online");
onlineOffline.setImageResource(R.drawable.online);
callToRegion.setOnClickListener(ProfileList.this);
tvHelpDescription.setText("To call " + LoadDataFromDatabase.relativesData.get(pos).getFirstName() + " " +
LoadDataFromDatabase.relativesData.get(pos).getLastName() + " tap here");
CallPageFragment.arrow.setVisibility(View.VISIBLE);
}
});
}
});
else{
Log.e("myLogs", "Socket is null");
}
}
private void offline() {
if(SocketService.getSocket() != null) {
SocketService.getSocket().on("offline", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "offline");
onlineOffline.setImageResource(R.drawable.offline);
callToRegion.setOnClickListener(null);
tvHelpDescription.setText("You can't call " + LoadDataFromDatabase.relativesData.get(pos).getFirstName() + " " +
LoadDataFromDatabase.relativesData.get(pos).getLastName() + " because she offline");
CallPageFragment.arrow.setVisibility(View.INVISIBLE);
}
});
}
});
}
else{
Log.e("myLogs", "Socket is null");
}
}

Related

Getting Null Adapter Error : E/RecyclerView: No adapter attached; skipping layout

Trying to retrieve data and place it into RecyclerView. But i always end up getting a null adapter error. My List Adapter is not being recognized.
I have initialized adapter and recyclerview in OnCreate(), OnViewCreated() nothing changed except app-crash.
Can you guys shed any light please?
My List Adapter:
public class PostListAdapter extends RecyclerView.Adapter<PostListAdapter.ViewHolder>{
private static final String TAG = "PostListAdapter";
private static final int NUM_GRID_COLUMNS = 3;
private ArrayList<Post> mPosts;
private Context mContext;
public class ViewHolder extends RecyclerView.ViewHolder{
SquareImageView mPostImage;
public ViewHolder(View itemView) {
super(itemView);
mPostImage = (SquareImageView) itemView.findViewById(R.id.post_image);
int gridWidth = mContext.getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
mPostImage.setMaxHeight(imageWidth);
mPostImage.setMaxWidth(imageWidth);
}
}
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(mContext);
public PostListAdapter(Context context, ArrayList<Post> posts) {
mPosts = posts;
mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.layout_view_post, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(mContext));
UniversalImageLoader.setImage(mPosts.get(position).getImage(), holder.mPostImage);
//GlideApp.with(mContext).load(mPosts.get(position)).into(holder.mPostImage);
//imageLoader.displayImage(mPosts.get(position).getImage(), holder.mPostImage);
final int pos = position;
holder.mPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: selected a post");
//TODO
//view the post in more detail
}
});
}
#Override
public int getItemCount() {
return mPosts.size();
}
}
My Fragment (where i initiliaze adapter and recyclerview):
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
mFilters = view.findViewById(R.id.ic_search);
mSearchText = view.findViewById(R.id.input_search);
mRecyclerView = view.findViewById(R.id.recyclerView);
mFrameLayout = view.findViewById(R.id.container);
getElasticSearchPassword();
init();
return view;
}
private void setupPostsList(){
RecyclerViewMargin itemDecorator = new RecyclerViewMargin(GRID_ITEM_MARGIN, NUM_GRID_COLUMNS);
mRecyclerView.addItemDecoration(itemDecorator);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), NUM_GRID_COLUMNS);
mRecyclerView.setLayoutManager(gridLayoutManager);
mAdapter = new PostListAdapter(getActivity(), mPosts);
mRecyclerView.setAdapter(mAdapter);
}
private void init(){
mFilters.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to filters activity.");
Intent intent = new Intent(getActivity(), FiltersActivity.class);
startActivity(intent);
}
});
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH
||actionId == EditorInfo.IME_ACTION_DONE
|| event.getAction() == KeyEvent.ACTION_DOWN
|| event.getKeyCode() == KeyEvent.KEYCODE_ENTER){
mPosts = new ArrayList<Post>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);
HashMap<String, String> headerMap = new HashMap<String, String>();
headerMap.put("Authorization", Credentials.basic("", mElasticSearchPassword));
String searchString = "";
if(!mSearchText.equals("")){
searchString = searchString + mSearchText.getText().toString() + "*";
}
if(!mPrefCity.equals("")){
searchString = searchString + " city:" + mPrefCity;
}
if(!mPrefStateProv.equals("")){
searchString = searchString + " state_province:" + mPrefStateProv;
}
if(!mPrefCountry.equals("")){
searchString = searchString + " country:" + mPrefCountry;
}
Call<HitsObject> call = searchAPI.search(headerMap, "AND", searchString);
call.enqueue(new Callback<HitsObject>() {
#Override
public void onResponse(Call<HitsObject> call, Response<HitsObject> response) {
HitsList hitsList = new HitsList();
String jsonResponse = "";
try{
Log.d(TAG, "onResponse: server response: " + response.toString());
if(response.isSuccessful()){
hitsList = response.body().getHits();
}else{
jsonResponse = response.errorBody().string();
}
Log.d(TAG, "onResponse: hits: " + hitsList);
for(int i = 0; i < hitsList.getPostIndex().size(); i++){
Log.d(TAG, "onResponse: data: " + hitsList.getPostIndex().get(i).getPost().toString());
mPosts.add(hitsList.getPostIndex().get(i).getPost());
}
Log.d(TAG, "onResponse: size: " + mPosts.size());
//setup the list of posts
setupPostsList();
}catch (NullPointerException e){
Log.e(TAG, "onResponse: NullPointerException: " + e.getMessage() );
}
catch (IndexOutOfBoundsException e){
Log.e(TAG, "onResponse: IndexOutOfBoundsException: " + e.getMessage() );
}
catch (IOException e){
Log.e(TAG, "onResponse: IOException: " + e.getMessage() );
}
}
#Override
public void onFailure(Call<HitsObject> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage() );
Toast.makeText(getActivity(), "search failed", Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
});
}
public void viewPost(String postId){
ViewPostFragment fragment = new ViewPostFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(getString(R.string.arg_post_id), postId);
fragment.setArguments(args);
transaction.replace(R.id.container, fragment, getString(R.string.fragment_view_post));
transaction.addToBackStack(getString(R.string.fragment_view_post));
transaction.commit();
mFrameLayout.setVisibility(View.VISIBLE);
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));
}
#Override
public void onResume() {
super.onResume();
getFilters();
}
private void getElasticSearchPassword(){
Log.d(TAG, "getElasticSearchPassword: retrieving elasticsearch password.");
Query query = FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.node_elasticsearch))
.orderByValue();
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot singleSnapshot = dataSnapshot.getChildren().iterator().next();
mElasticSearchPassword = singleSnapshot.getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getFilters(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mPrefCity = preferences.getString(getString(R.string.preferences_city), "");
mPrefStateProv = preferences.getString(getString(R.string.preferences_state_province), "");
mPrefCountry = preferences.getString(getString(R.string.preferences_country), "");
Log.d(TAG, "getFilters: got filters: \ncity: " + mPrefCity + "\nState/Prov: " + mPrefStateProv
+ "\nCountry: " + mPrefCountry);
}
}
It seems like you never call the method setupPostsList(). You should move your code in Fragment from onCreateView() to onViewCreated() - that's the mehod where all views in fragment are created and you can use findViewById(). First find all view by ids and then call method setupPostsList() to set up the recycle view.

What is the correct method for dynamic subscription in rxJava 2 in android?

What is the appropriate method to dynamically subscribe observer in rxJava2 in android.Though I am getting the desired output,I am not sure if this is the correct way of implementing in terms of memory. Following is my code
flowableObservable = getHumanflowable();
subscriber = getFlowableObserver();
flowableObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);
/////////////////////// Observable code
private Flowable<String> getHumanflowable() {
return new Flowable<String>() {
#Override
protected void subscribeActual(final Subscriber<? super String> s) {
t = new Timer();
t.scheduleAtFixedRate(
new TimerTask() {
public void run() {
if (listObj.size() > 0) {
varToBeAddedInObservable = listObj.remove(listObj.size() - 1);
// Log.d("&&&&&&&&&&",""+varToBeAddedInObservable);
s.onNext(varToBeAddedInObservable);
} else {
s.onComplete();
t.cancel();
}
}
},
0,
1000);
}
};
}
//////////////////////////// Observer
private Subscriber<String> getFlowableObserver() {
/*return new Subscriber<Integer>() {
#Override
public void onSubscribe(Disposable d) {
Log.d(TAG, "onSubscribe");
// disposable = d;
}
#Override
public void onSuccess(Integer integer) {
Log.d(TAG, "onSuccess: " + integer);
}
#Override
public void onError(Throwable e) {
Log.e(TAG, "onError: " + e.getMessage());
}
};*/
return new Subscriber<String>() {
#Override
public void onSubscribe(Subscription s) {
mSubscriptionObject =s;
s.request(Long.MAX_VALUE);
}
#Override
public void onNext(String integer) {
Log.d("+++++++++", "" + integer);
int colorIndex = random.nextInt(arrayColors.length);
//Color color = (arrayColors[colorIndex]);
textView.setTextColor(arrayColors[colorIndex]);
textView.setText(varToBeAddedInObservable);
AlphaAnimation fadeIn = new AlphaAnimation(0.0f, 1.0f);
AlphaAnimation fadeOut = new AlphaAnimation( 1.0f , 0.0f ) ;
textView.startAnimation(fadeIn);
// textView.startAnimation(fadeOut);
fadeIn.setDuration(1500);
fadeIn.setFillAfter(true);
// fadeOut.setDuration(1200);
fadeOut.setFillAfter(true);
// fadeOut.setStartOffset(1200 - fadeIn.getStartOffset());
fadeIn.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
textView.setTextColor(Color.BLACK);
textView.setText("Jadu cha Khel Sampla !!!!");
textView.setTextSize(25);
textView.setGravity(View.TEXT_ALIGNMENT_CENTER);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
#Override
public void onError(Throwable t) {
}
#Override
public void onComplete() {
createList();
/* Flowable<String> flowableObservable = getHumanflowable();
Subscriber<String> subscriber = getFlowableObserver();*/
//SingleObserver<Integer> observer = getFlowableObserver();
// flowableObservable.publish(AndroidSchedulers.mainThread());
/* flowableObservable.subscribeOn(Schedulers.io())
// .onBackpressureLatest()
*//* .reduce(500, new BiFunction<Integer, Integer, Integer>() {
#Override
public Integer apply(Integer result, Integer number) {
Log.e(TAG, "Result: " + result + ", new number: " + number);
return result + number;
}
})
.*//*.observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);*/
/* if(mSubscriptionObject!=null) {
mSubscriptionObject.request(Long.MAX_VALUE);
}*/
}
};
}
So as you can see I am subscribing it again in the onComplete() method of observer.So it is subscribing it. Consider it same for api call. Can I keep on subscribing with the same subscriber object each time we receive a response in api call success,like I have done in onComplete ??? or is there a better way to do it ??

Solved: Android socket is not getting connected to the server

Here I have a query related to connection between android socket and server. I'm following https://socket.io/blog/native-socket-io-and-android/ and found that it is working fine, so I replaced my local server URL with the URL in the tutorial. But here I'm always getting a connection failed or disconnection error. Here is my application class for further clarification.
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
IO.Options options = new IO.Options();
options.forceNew = true;
options.reconnection = true;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("uid", 1);
jsonObject.put("usid", 6847);
options.query = jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("JSON", jsonObject.toString());
Log.e("OPTIONS", options.toString());
mSocket = IO.socket(Constants.CHAT_SERVER_URL, options);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
And the code of the fragment is below. It keeps calling onDisconnect() whenever I use my local server for it.
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private static final int REQUEST_LOGIN = 0;
private static final int TYPING_TIMER_LENGTH = 600;
private RecyclerView mMessagesView;
private EditText mInputMessageView;
private List<Message> mMessages = new ArrayList<Message>();
private RecyclerView.Adapter mAdapter;
private boolean mTyping = false;
private Handler mTypingHandler = new Handler();
private String mUsername;
private Socket mSocket;
private Boolean isConnected = true;
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isConnected) {
if (null != mUsername)
mSocket.emit("add user", mUsername);
Toast.makeText(getActivity().getApplicationContext(),
R.string.connect, Toast.LENGTH_LONG).show();
isConnected = true;
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i(TAG, "diconnected");
isConnected = false;
Toast.makeText(getActivity().getApplicationContext(),
R.string.disconnect, Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Error connecting");
Toast.makeText(getActivity().getApplicationContext(),
R.string.error_connect, Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onNewMessage = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
removeTyping(username);
addMessage(username, message);
}
});
}
};
private Emitter.Listener onUserJoined = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
int numUsers;
try {
username = data.getString("username");
numUsers = data.getInt("numUsers");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addLog(getResources().getString(R.string.message_user_joined, username));
addParticipantsLog(numUsers);
}
});
}
};
private Emitter.Listener onUserLeft = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
int numUsers;
try {
username = data.getString("username");
numUsers = data.getInt("numUsers");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addLog(getResources().getString(R.string.message_user_left, username));
addParticipantsLog(numUsers);
removeTyping(username);
}
});
}
};
private Emitter.Listener onTyping = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
try {
username = data.getString("username");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
addTyping(username);
}
});
}
};
private Emitter.Listener onStopTyping = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
try {
username = data.getString("username");
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
return;
}
removeTyping(username);
}
});
}
};
private Runnable onTypingTimeout = new Runnable() {
#Override
public void run() {
if (!mTyping) return;
mTyping = false;
mSocket.emit("stop typing");
}
};
public MainFragment() {
super();
}
// This event fires 1st, before creation of fragment or any views
// The onAttach method is called when the Fragment instance is associated with an Activity.
// This does not mean the Activity is fully initialized.
#Override
public void onAttach(Context context) {
super.onAttach(context);
mAdapter = new MessageAdapter(context, mMessages);
if (context instanceof Activity) {
//this.listener = (MainActivity) context;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
ChatApplication app = (ChatApplication) getActivity().getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("new message", onNewMessage);
mSocket.on("user joined", onUserJoined);
mSocket.on("user left", onUserLeft);
mSocket.on("typing", onTyping);
mSocket.on("stop typing", onStopTyping);
mSocket.connect();
startSignIn();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("new message", onNewMessage);
mSocket.off("user joined", onUserJoined);
mSocket.off("user left", onUserLeft);
mSocket.off("typing", onTyping);
mSocket.off("stop typing", onStopTyping);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMessagesView = (RecyclerView) view.findViewById(R.id.messages);
mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));
mMessagesView.setAdapter(mAdapter);
mInputMessageView = (EditText) view.findViewById(R.id.message_input);
mInputMessageView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int id, KeyEvent event) {
if (id == R.id.send || id == EditorInfo.IME_NULL) {
attemptSend();
return true;
}
return false;
}
});
mInputMessageView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (null == mUsername) return;
if (!mSocket.connected()) return;
if (!mTyping) {
mTyping = true;
mSocket.emit("typing");
}
mTypingHandler.removeCallbacks(onTypingTimeout);
mTypingHandler.postDelayed(onTypingTimeout, TYPING_TIMER_LENGTH);
}
#Override
public void afterTextChanged(Editable s) {
}
});
ImageButton sendButton = (ImageButton) view.findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attemptSend();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Activity.RESULT_OK != resultCode) {
getActivity().finish();
return;
}
mUsername = data.getStringExtra("username");
int numUsers = data.getIntExtra("numUsers", 1);
addLog(getResources().getString(R.string.message_welcome));
addParticipantsLog(numUsers);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_leave) {
leave();
return true;
}
return super.onOptionsItemSelected(item);
}
private void addLog(String message) {
mMessages.add(new Message.Builder(Message.TYPE_LOG)
.message(message).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void addParticipantsLog(int numUsers) {
addLog(getResources().getQuantityString(R.plurals.message_participants, numUsers, numUsers));
}
private void addMessage(String username, String message) {
mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
.username(username).message(message).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void addTyping(String username) {
mMessages.add(new Message.Builder(Message.TYPE_ACTION)
.username(username).build());
mAdapter.notifyItemInserted(mMessages.size() - 1);
scrollToBottom();
}
private void removeTyping(String username) {
for (int i = mMessages.size() - 1; i >= 0; i--) {
Message message = mMessages.get(i);
if (message.getType() == Message.TYPE_ACTION && message.getUsername().equals(username)) {
mMessages.remove(i);
mAdapter.notifyItemRemoved(i);
}
}
}
private void attemptSend() {
if (null == mUsername) return;
if (!mSocket.connected()) return;
mTyping = false;
String message = mInputMessageView.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
mInputMessageView.requestFocus();
return;
}
mInputMessageView.setText("");
addMessage(mUsername, message);
// perform the sending message attempt.
mSocket.emit("new message", message);
}
private void startSignIn() {
// mUsername = null;
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivityForResult(intent, REQUEST_LOGIN);
}
private void leave() {
mUsername = null;
mSocket.disconnect();
mSocket.connect();
startSignIn();
}
private void scrollToBottom() {
mMessagesView.scrollToPosition(mAdapter.getItemCount() - 1);
}
}
I'm using CHAT_SERVER_URL = "http://192.168.1.14:3000/" to make connection with server but it's not working for me. It works fine when we try to make a web connection through emulator or computer system. Can anyone please give me an idea if I'm doing anything wrong.
Thanks.
After debugging at the server end too, I got to know how to hit my server to make a connection and I got that we don't require IO.Options and Options.query in every case and now it is working fine completely. So for more clarification I'm posting an answer here:
//connect to server
public void startRunning() {
try {
if (baseUrl != null) {
socket = IO.socket("http://" + baseUrl + ":3000?uid=" + userId + "&usid=" + userSessionId);
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (socket == null) return;
socket
.on(Socket.EVENT_CONNECT, CONNECTED)
.on(Socket.EVENT_DISCONNECT, DISCONNECTED)
.on("chat-message", CHAT_MESSAGE)
.on("chats-active", CHATS_ACTIVE)
.on("chat-logout", LOGOUT)
.on("messages-read", MESSAGE_READ)
.on("chat-login", CHAT_LOGIN);
socket.connect();
}

How to remove this update icon? Android Swiperefersh

CODE
public class YellowFragment extends Fragment implements FlowerAdapter.FlowerClickListener{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_yellow, container, false);
swipeContainer_yellow = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer_yellow);
setRetainInstance(true);
mReferSharedPreference = new ReferSharedPreference(getContext());
mlat = mReferSharedPreference.getValue("Lat", "None");
mlon = mReferSharedPreference.getValue("Lon", "None");
mCoordinatesTextLinear = (TextView) view.findViewById(R.id.tv_coordinates_linear);
if(!mlat.equals("None")){
getLinearPosts();
}
else {
Toast.makeText(getContext(), "Choose your location", Toast.LENGTH_LONG).show();
}
swipeContainer_yellow.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if(!mlat.equals("None")){
getLinearPosts();
}
else {
Toast.makeText(getContext(), "Choose your location", Toast.LENGTH_LONG).show();
}
}
});
configViews(view);
return view;
}
private void getLinearPosts() {
ReferSharedPreference preferenceCoordinates = new ReferSharedPreference(getContext());
String lat = preferenceCoordinates.getValue("Lat", "None");
String lon = preferenceCoordinates.getValue("Lon", "None");
mCoordinatesTextLinear.setText("Your Location :" + lat + " , " + lon);
mRestManager = new RestManager();
Call<List<Flower>> listCall = mRestManager.getmFlowerApiService(getActivity()).getAllFlowers(lat, lon);
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
mFlowerAdapter.clear();
List<Flower> flowerList = response.body();
for(int i =0; i<flowerList.size(); i++) {
Flower flower = flowerList.get(i);
mFlowerAdapter.addFlower(flower);
}
swipeContainer_yellow.setRefreshing(false);
}
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
}
});
}
In this code, when i swipe, if mlat is None, there is swipe updating icon and it's not disappear.
What i wanted is that if mlat has some value, do getLinearPosts();, but if mlat has None, show Toast "Choose your location".
but refershing icon do not disappear
like this
Question: How can i disappear this updating or refreshing icon when mlat is None?
After your task is completed, just call swipeContainer_yellow.setRefreshing(false) and it will hide that progressbar
As i can see you have already used it, but problem is you are assuming that your response will be perfect all the time. So instead of keeping it inside if (response.isSuccessful()), keep it outside if condition and also put it in onFailure()
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
swipeContainer_yellow.setRefreshing(false);
if (response.isSuccessful()) {
mFlowerAdapter.clear();
List<Flower> flowerList = response.body();
for(int i =0; i<flowerList.size(); i++) {
Flower flower = flowerList.get(i);
mFlowerAdapter.addFlower(flower);
}
}
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
swipeContainer_yellow.setRefreshing(false);
}
});

How to pass the name of the item clicked to another class

How to pass the name of the item clicked on the on list item clicked through Intent?
is this correct?
public class View_PPT_List extends ListActivity {
private final String SAMPLE_DB_NAME = "project";
private final String PPT_TABLE_NAME1 = "notes";
private final String PPT_TABLE_NAME2 = "subject";
SQLiteDatabase notesDB = null;
ArrayList<String> results = new ArrayList<String>();
public void onListItemClick(ListView l, View view, final int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, view, position, id);
Intent ins = new Intent (View_PPT_List.this,PPTActivity.class);
ins.putExtra("com.example.tinio_bolasa_project.finame",
String.valueOf(position));
startActivity(ins);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
notesDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
notesDB.execSQL("CREATE TABLE IF NOT EXISTS " +
PPT_TABLE_NAME1 +
" ( notes_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "subjid
INTEGER, " + "pptName VARCHAR, " + "pptPath VARCHAR);");
int x1 = getIntent().getIntExtra("pos",1);
Cursor c = notesDB.rawQuery("SELECT * FROM notes WHERE "+ x1 +"=subjid", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String pptid = c.getString(c.getColumnIndex("notes_ID"));
String ppt = c.getString(c.getColumnIndex("pptName"));
results.add(pptid + ppt);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (notesDB != null)
notesDB.close();
}
setContentView(R.layout.activity_view__ppt__list);
Button addppt = (Button) this.findViewById(R.id.button1);
addppt.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inten = new Intent (View_PPT_List.this, Add_PPT_Activity.class);
int x = getIntent().getIntExtra("pos",1);
inten.putExtra("key", x);
startActivity(inten);
}
});
}
}
then in my PowerpointActiv
public class PPTActivity extends Activity implements
DocumentSessionStatusListener {
private PersentationView content;
private DocumentSession session;
private SlideShowNavigator navitator;
private int currentSlideNumber;
private Button prev;
private Button next;
private SeekBar scale;
String filename = getIntent().getStringExtra("com.example.tinio_bolasa_project.finame");
String filePath = Environment.getExternalStorageDirectory()
.getPath() + "/" + filename;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
copyFileToSdcard();
this.setContentView(R.layout.powerpoint_main);
this.content = (PersentationView) this.findViewById(R.id.content);
this.prev = (Button) this.findViewById(R.id.prev);
this.prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prev();
}
});
this.next = (Button) this.findViewById(R.id.next);
this.next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
});
this.scale = (SeekBar) this.findViewById(R.id.scale);
this.scale
.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (progress < 1) {
progress = 1;
}
PPTActivity.this.content
.notifyScale(progress /
250.0);
}
});
try {
Context context = PPTActivity.this.getApplicationContext();
IMessageProvider msgProvider = new AndroidMessageProvider(context);
TempFileManager tmpFileManager = new TempFileManager(
new AndroidTempFileStorageProvider(context));
ISystemColorProvider sysColorProvider = new
AndroidSystemColorProvider();
session = new DocumentSessionBuilder(new File(filePath))
.setMessageProvider(msgProvider)
.setTempFileManager(tmpFileManager)
.setSystemColorProvider(sysColorProvider)
.setSessionStatusListener(this).build();
session.startSession();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStart() {
super.onStart();
this.content.setContentView(null);
}
#Override
protected void onDestroy() {
if (this.session != null) {
this.session.endSession();
}
super.onDestroy();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Toast.makeText(this,
// "(" + event.getRawX() + "," + event.getRawY() + ")",
// Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event);
}
public void onSessionStarted() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onSessionStarted",
Toast.LENGTH_SHORT).show();
}
});
}
public void onDocumentReady() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onDocumentReady",
Toast.LENGTH_SHORT).show();
PPTActivity.this.navitator = new SlideShowNavigator(
PPTActivity.this.session.getPPTContext());
PPTActivity.this.currentSlideNumber =
PPTActivity.this.navitator
.getFirstSlideNumber() - 1;
PPTActivity.this.next();
}
});
}
public void onDocumentException(Exception e) {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onDocumentException",
Toast.LENGTH_SHORT).show();
PPTActivity.this.finish();
}
});
}
public void onSessionEnded() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onSessionEnded",
Toast.LENGTH_SHORT).show();
}
});
}
private void navigateTo(int slideNumber) {
SlideView slideShow = this.navitator.navigateToSlide(
this.content.getGraphicsContext(), slideNumber);
this.content.setContentView(slideShow);
}
private void next() {
if (this.navitator != null) {
if (this.navitator.getFirstSlideNumber()
+ this.navitator.getSlideCount() - 1 >
this.currentSlideNumber) {
this.navigateTo(++this.currentSlideNumber);
} else {
Toast.makeText(this, "Next page",
Toast.LENGTH_SHORT).show();
}
}
}
private void prev() {
if (this.navitator != null) {
if (this.navitator.getFirstSlideNumber() < this.currentSlideNumber)
{
this.navigateTo(--this.currentSlideNumber);
} else {
Toast.makeText(this, "Pre page", Toast.LENGTH_SHORT).show();
}
}
}
private void copyFileToSdcard() throws FileNotFoundException {
File file = new File(filePath.toString());
FileInputStream inputstream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int count = 0;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filePath));
while ((count = inputstream.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
} catch (FileNotFoundException e1) {
Toast.makeText(PPTActivity.this, "Check your sdcard",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
i get error (java.runtimeExceptin: cannot instantiate activity ComponentInfo: Java.lang.nullpointerexception)..
how to pass the String name of the item :( pls help :(
This line
String nam = getIntent().getStringExtras("string");
should be
String nam = getIntent().getStringExtra("string"); // without the 's'
String nam = getIntent().getStringExtra("string"); //not getStringExtras
Because you have specified the tag (string) to get one String
You should pick up with:
String nam = getIntent().getStringExtra("string"); //without 's'

Categories

Resources