center the text in a Full screen Dialog - android

I am trying to develop network app which shows a dialog when network is disconnected. I have made everything but the text inside the dialog is not centered.
package com.example.ayyappaboddupalli.networkchecker;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
/**
* Created by ayyappaboddupalli on 10/23/2017.
*/
public class ApplicationClass extends Application implements android.app.AlertDialog.OnDismissListener {
private static ApplicationClass mInstance;
private NetworkObserver networkObserver;
private NetworkDetector detector;
private AlertDialog.Builder ad = null;
private AlertDialog alertDialog;
public AlertDialog getAlertDialog() {
return alertDialog;
}
#Override
public void onCreate() {
super.onCreate();
networkObserver = new NetworkObserver();
}
public static ApplicationClass getmInstance() {
if (mInstance == null) {
synchronized (Object.class) {
mInstance = mInstance == null ? new ApplicationClass() : mInstance;
}
}
return mInstance;
}
public NetworkObserver getNetworkObserver() {
if (networkObserver == null) {
networkObserver = new NetworkObserver();
return networkObserver;
} else {
return networkObserver;
}
}
public void registerReceiver(Context context) {
detector = new NetworkDetector();
context.registerReceiver(detector, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public void unRegisterReciver(Context context) {
try {
unregisterReceiver(detector);
} catch (Exception f) {
}
}
public void showDialog(Context context) {
if(alertDialog!=null)
{
alertDialog.dismiss();
}
ad = new AlertDialog.Builder(context);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.weak_net_dialog, null);
ad.setView(view);
alertDialog = ad.create();
alertDialog.show();
alertDialog.setCancelable(false);
}
#Override
public void onDismiss(DialogInterface dialog) {
alertDialog=null;
}
}
public class NetworkDetector extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetOn=isnetworkOnline(context);
ApplicationClass.getmInstance().getNetworkObserver().setValue(isNetOn);
}
public boolean isnetworkOnline(Context context)
{
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
public class NetworkObserver extends Observable {
private boolean netWorkOff=false;
public boolean isNetWorkOff() {
return netWorkOff;
}
public void setValue(boolean netWorkOff) {
this.netWorkOff = netWorkOff;
setChanged();
notifyObservers();
}
}
#Override
public void update(Observable o, Object arg) {
if(ApplicationClass.getmInstance().getNetworkObserver().isNetWorkOff()) {
Toast.makeText(getApplicationContext(),"Network is online",Toast.LENGTH_LONG).show();
if(ApplicationClass.getmInstance().getAlertDialog()!=null&&ApplicationClass.getmInstance().getAlertDialog().isShowing())
ApplicationClass.getmInstance().getAlertDialog().dismiss();
}
else
{
ApplicationClass.getmInstance().showDialog(this);
// Toast.makeText(getApplicationContext(),"Network is offline",Toast.LENGTH_LONG).show();
}
}

Try this:
android:layout_gravity="center"

use following lines in ur xml file:
android:center_vertical = true
android:center_horizontal=true
It will work if you are using relativeLayout
also set width to match_parent of your dialogue and editText

Related

How to get the result from EventObserver in Android Java

I am following this post: https://stackoverflow.com/questions/56071990/android-architecture-singleliveevent-and-eventobserver-practicle-example-in-java
public class Event<T> {
private boolean hasBeenHandled = false;
private T content;
public Event(T content) {
this.content = content;
}
public T getContentIfNotHandled() {
if (hasBeenHandled) {
return null;
} else {
hasBeenHandled = true;
return content;
}
}
public boolean isHandled() {
return hasBeenHandled;
}
}
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
public class EventObserver<T> implements Observer<Event<T>> {
private OnEventChanged onEventChanged;
public EventObserver(OnEventChanged onEventChanged) {
this.onEventChanged = onEventChanged;
}
#Override
public void onChanged(#Nullable Event<T> tEvent) {
if (tEvent != null && tEvent.getContentIfNotHandled() != null && onEventChanged != null)
onEventChanged.onUnhandledContent(tEvent.getContentIfNotHandled());
}
interface OnEventChanged<T> {
void onUnhandledContent(T data);
}
}
I have this in my repository:
private MutableLiveData<Event<String>> _amsRepositoryError = new MutableLiveData<>();
public MutableLiveData<Event<UserModel>> amsLoginSuccessReply(){return _amsLoginSuccessReply;}
_amsLoginSuccessReply.postValue(new Event(userModel));
And I catch this in my viewmodel:
amsRepository.amsLoginSuccessReply().observe(mLifeCycleOwner, new EventObserver<UserModel>(data -> {
// HOW DO I GET THE data here.
}));
on the observe, how do I get the values of the data?

(Chromium for android studio) How to use addPossiblyUnsafeJavascriptInterface?

In ChromeActivity.Java, I customized some code, but it's not working like webview's addJavascriptInterface I did:
import org.chromium.content.browser.JavascriptInterface;
#SuppressLint("JavascriptInterface")
#Override
public void createContextualSearchTab(String searchUrl) {
Tab currentTab = getActivityTab();
if (currentTab == null) return;
Class<? extends Annotation> requiredAnnotation = JavascriptInterface.class;
currentTab.getWebContents().addPossiblyUnsafeJavascriptInterface(new MyJavaScriptInterface(this), "MyJS", requiredAnnotation);
TabCreator tabCreator = getTabCreator(currentTab.isIncognito());
if (tabCreator == null) return;
tabCreator.createNewTab(
new LoadUrlParams(searchUrl, PageTransition.LINK),
TabModel.TabLaunchType.FROM_LINK, currentTab);
}
public class MyJavaScriptInterface {
ChromeActivity context;
public MyJavaScriptInterface(ChromeActivity activity) {
this.context = activity;
}
#JavascriptInterface
#SuppressWarnings("unused")
public void closeApp(){
this.context._closeApp();
}
}
Chromium for android studio source code: https://github.com/kuoruan/Chromium-Android
Since Chromium 65, addPossiblyUnsafeJavascriptInterface has been changed to addPossiblyUnsafeInterface
mTabModelSelectorTabObserver = new TabModelSelectorTabObserver(mTabModelSelector) {
#Override
public void onShown(Tab tab) {
setStatusBarColor(tab, tab.getThemeColor());
JavascriptInjector ji = JavascriptInjector.fromWebContents(tab.getWebContents());
ji.setAllowInspection(true);
ji.addPossiblyUnsafeInterface(new MyJavaScriptInterface(ChromeActivity.this), "BEEB", JavascriptInterface.class);
}
}
public class MyJavaScriptInterface {
ChromeActivity context;
public MyJavaScriptInterface(ChromeActivity activity) {
this.context = activity;
}
#JavascriptInterface
public void closeApp(){
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "ccccccccccccccccccccccccccccccc", duration);
toast.show();
}
}

android home button pressed

please check this code completely and suggest me some ideas
i had executed this in android studio 3.0.1 and showing me no error but doesnt shows any ouput
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
// do something here...
}
#Override
public void onHomeLongPressed() {
}
});
mHomeWatcher.startWatch();
check this
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
check this
public interface OnHomePressedListener {
public void onHomePressed();
public void onHomeLongPressed();
}
this code was not working for me i tried of toasting a msg when home button is pressed in onHomePressed() method but msg not display plz help me to get through it
You arenĀ“t supposed to see when users press the "Home" key, mostly for security reasons and consistent behaviour for the user.
(Except for special cases like Launchers)
Most methods of doing it have been disabled already, your method probably has been disabled aswell.

How to keep the switch widget in OFF position after closing the application

I am trying to implement the switch widget in Android. However whenever I set the switch to 'OFF' position and I close and re-open my application, it again sets itself to 'ON' value. How can I make it set itself according to the user.
My SettingScreen,java
toggleCamera = (ToggleButton) findViewById(R.id.toggleCamera);
Boolean b = AppTypeDetails.getInstance(SettingScreen.this).getToggleStatus();
toggleCamera.setChecked(b);
toggleCamera.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toggleCamera.isChecked()) {
AppTypeDetails.getInstance(SettingScreen.this).setToggleStatus(true);
} else {
AppTypeDetails.getInstance(SettingScreen.this).setToggleStatus(false);
}
}
});
AppTypeDetails.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class AppTypeDetails {
private SharedPreferences sh;
private AppTypeDetails() {
}
private AppTypeDetails(Context mContext) {
sh = PreferenceManager.getDefaultSharedPreferences(mContext);
}
private static AppTypeDetails instance = null;
public synchronized static AppTypeDetails getInstance(Context mContext) {
if (instance == null) {
instance = new AppTypeDetails(mContext);
}
return instance;
}
// get toggle Status
public boolean getToggleStatus() {
return sh.getBoolean("ToggleButton", false);
}
public void setToggleStatus(Boolean toggle) {
sh.edit().putBoolean("ToggleButton", toggle).commit();
}
public void clear() {
sh.edit().clear().commit();
}
}
This will successfully worked...

Why main thread can't update UI elements inside a horizontallistview?

Last few days I'm trying to update some UI Views inside a custom HorizontalListView. I've been trying countless way like using Async Task, posting message via handler etc. I didn't figure out to update them. As a result, I tried to build a queue system to update them one by one. Here is my code and it's still not updating them.
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import roboguice.RoboGuice;
import CustomChannel;
import EGPInfo;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class EPGLoader {
static private EPGLoader _instance;
public static EPGLoader getInstance(Context context) {
if (_instance == null) {
_instance = new EPGLoader();
}
mContext = context;
return _instance;
}
private HashMap<String, WeakReference<EPGChannel>> _cachedChannels;
private Queue<EPGChannel> _queue;
private EPGThread _thread;
private static Context mContext;
private boolean _isBusy;
public EPGLoader() {
_cachedChannels = new HashMap<String, WeakReference<EPGChannel>>();
_queue = new LinkedList<EPGChannel>();
_isBusy = false;
}
public void load(ArrayList<TextView> textViews, CustomChannel channel) {
Iterator<EPGChannel> it = _queue.iterator();
EPGChannel epgChannel = new EPGChannel();
epgChannel.setChannel(channel);
epgChannel.setTextViews(textViews);
while (it.hasNext()) {
if (it.next().equals(epgChannel)) {
it.remove();
break;
}
}
_queue.add(epgChannel);
loadNext();
}
private void loadNext() {
Iterator<EPGChannel> it = _queue.iterator();
if (!_isBusy && it.hasNext()) {
_isBusy = true;
EPGChannel epgChannel = it.next();
it.remove();
EPGChannel epgCache = get(epgChannel.getChannel().getChannelId());
if (epgCache != null) {
Log.i("A", "Cache");
epgChannel.textViews.get(0).setText("1");
epgChannel.textViews.get(1).setText("2");
epgChannel.textViews.get(2).setText("3");
epgChannel.textViews.get(3).setText("4");
_isBusy = false;
loadNext();
} else {
_thread = new EPGThread(epgChannel);
_thread.start();
Log.i("A", "Live");
}
}
}
private EPGChannel get(String channelId) {
if (_cachedChannels.containsKey(channelId)) {
return _cachedChannels.get(channelId).get();
} else {
return null;
}
}
private class EPGThread extends Thread {
private EPGChannel EPGChannel;
final Handler threadHandler = new Handler();
final Runnable threadCallBack = new Runnable() {
#Override
public void run() {
onLoad();
}
};
public EPGThread(EPGChannel epgChannel) {
this.EPGChannel = epgChannel;
}
private void onLoad() {
if (_thread != null) {
EPGChannel epgChannel = _thread.EPGChannel;
// epgChannel.getTextViews().get(1).setText(epgChannel.getChannel().getName());
epgChannel.getTextViews().get(0).setText("1");
epgChannel.getTextViews().get(1).setText("2");
epgChannel.getTextViews().get(2).setText("3");
epgChannel.getTextViews().get(3).setText("4");
}
_thread = null;
_isBusy = false;
loadNext();
}
#Override
public void run() {
try {
_isBusy = true;
ChannelManager channelManager = RoboGuice.getInjector(mContext).getInstance(ChannelManager.class);
ArrayList<EGPInfo> epgInfo = channelManager.getChannelEPG(EPGChannel.getChannel().getChannelId());
if (epgInfo.size() == 2) {
EPGChannel.getChannel().updateEPGInformations(epgInfo.get(0), epgInfo.get(1));
}
if (!_cachedChannels.containsKey(EPGChannel.getChannel().getChannelId()))
_cachedChannels.put(EPGChannel.getChannel().getChannelId(), new WeakReference<EPGLoader.EPGChannel>(EPGChannel));
} catch (Exception e) {
e.printStackTrace();
} finally {
threadHandler.post(threadCallBack);
}
}
}
private class EPGChannel {
private ArrayList<TextView> textViews;
private CustomChannel channel;
public ArrayList<TextView> getTextViews() {
return textViews;
}
public void setTextViews(ArrayList<TextView> textViews) {
this.textViews = textViews;
}
public CustomChannel getChannel() {
return channel;
}
public void setChannel(CustomChannel channel) {
this.channel = channel;
}
}
}
I call it from main thread when getView event of ArrayAdapter fires.
#Override
public View getView(int position, View retval, ViewGroup parent) {
if (retval == null) {
retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.channel_item, null);
}
final CustomChannel currentChannel = getItem(position);
final TextView nowTitle = (TextView) retval.findViewById(R.id.channel_item_current_show_title);
final TextView nowPlayTime = (TextView) retval.findViewById(R.id.channel_item_current_show_play_time);
final TextView nextTitle = (TextView) retval.findViewById(R.id.channel_item_next_show_title);
final TextView nextPlayTime = (TextView) retval.findViewById(R.id.channel_item_next_show_play_time);
ArrayList<TextView> textViews = new ArrayList<TextView>();
textViews.add(nowTitle);
textViews.add(nowPlayTime);
textViews.add(nextTitle);
textViews.add(nextPlayTime);
EPGLoader.getInstance(mContext).load(textViews, currentChannel);
return retval;
}
So, what is wrong with my codes? Thanks in advance.
Edit: I replace the HorizontalListView with normal Android's ListView and it works but I have to use HorizontalListView in the project. Any suggesstions?
Edit 2: I reward to back (HorizontalListView) and tried to set Background color of some UI controllers, guess what? It updated. It doesn't update text property!!! Why????

Categories

Resources