Friends In My Application , i want to use text box value in
all other activity without passing any argument. how it's possible? Anyone
know these give me a example, thanks in advance. by Nallendiran.S
There are a few different ways you can achieve what you are asking for.
1.) Extend the application class and instantiate your controller and model objects there.
public class FavoriteColorsApplication extends Application {
private static FavoriteColorsApplication application;
private FavoriteColorsService service;
public FavoriteColorsApplication getInstance() {
return application;
}
#Override
public void onCreate() {
super.onCreate();
application = this;
application.initialize();
}
private void initialize() {
service = new FavoriteColorsService();
}
public FavoriteColorsService getService() {
return service;
}
}
Then you can call the your singleton from your custom Application object at any time:
public class FavoriteColorsActivity extends Activity {
private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_colors);
service = ((FavoriteColorsApplication) getApplication()).getService();
favoriteColors = service.findAllColors();
ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
favoriteColors);
lv.setAdapter(adapter);
}
2.) You can have your controller just create a singleton instance of itself:
public class Controller {
private static final String TAG = "Controller";
private static sController sController;
private Dao mDao;
private Controller() {
mDao = new Dao();
}
public static Controller create() {
if (sController == null) {
sController = new Controller();
}
return sController;
}
}
Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.
3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.
I hope I gave enough detail in regards to how you can do what you are hoping for.
Create it static type and than you can get it where you want.
Private TextVeiw txtvw;
Public static String myText="";
myText=txtvw.getText();
Access this variable with class name in which it defined.
MyActivity.myString
Related
I have 3 classes, one in my CustomDialog class, another one is a non-activity class where i call my custom dialog, and a third class that is my App class from where I want want to dismiss the custom dialog.
Custom Dialog class:
public class DCCView extends Dialog {
private final String dCancel= "CANCEL";
private ResultListener listener;
private Button btnCurrency1;
private Button btnCurrency2;
private Button btnCancel;
private TextView tvCurrency1;
private TextView tvCurrency2;
private TextView tvMsg;
private Handler mTimer;
private Response response;
public DCCView(#NonNull Context context) {
super(context);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dcc_interface);
setCancelable(false);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btnCancel = findViewById(R.id.btn_cancel);
tv1 = findViewById(R.id.tv1);
tv2 = findViewById(R.id.tv2);
tvMsg = findViewById(R.id.tv_dcc_msg);
btnCurrency1.setOnClickListener(view -> {
response = Response.C1;
cancelAlert();
listener.onResult(response);
});
btnCurrency2.setOnClickListener(view -> {
response = Response.C2;
cancelAlert();
listener.onResult(response);
});
btnCancel.setOnClickListener(view -> {
response = Response.CANCEL;
cancelAlert();
listener.onResult(response);
});
}
public interface ResultListener {
void onResult(Response response);
}
public void showDCC(String transCurrency, double transAmount, String dccCurrency, String dccAmount,String dataDisplay, #NonNull ResultListener listener) {
this.listener = listener;
Handler hnd = new Handler(getContext().getMainLooper());
hnd.post(() -> {
showAlert();
btn1.setText(transCurrency);
tv1.setText(String.format("%.2f",transAmount));
btn2.setText(dccCurrency);
tv2.setText(dccAmount);
btnCancel.setText(dCancel);
tvMsg.setText(dataDisplay);
});
}
public void showAlert() {
if (!isShowing()) {
show();
}
}
public void cancelAlert() {
dismiss();
}
Non-activity class:
public class MSG1002{
private static DCCView mDccView;
public MSG1002() {
Handler hnd = new Handler(App.getContext().getMainLooper());
hnd.post(() -> {
mDccView = new DCCView(App.getContext());
});
}
public void process(){
mDccView.showDCC(transactionCurrency, transA, dccCurrency, dccAmount, dataUserDisplay, (DCCView.Response response) -> {
onDccResponse(response, socketCliente);
});
}
App class:
public class App extends Application{
private static DCCView mDCCView;
public static void realCancelAlert() {
mDCCView.cancelAlert();
}
#Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
mDCCView =new DCCView(mContext);
}
App.realCancelAlert();
So when I call my custom dialog from MSG1002 class, the dialog appears and it works, but when i what to close it from the class App with the command line App.realCancelAlert(); it doesn't close, and I don't understand why, because when I debug it the flow continues until it get's to dismiss() and it executs it but it doesn't dissapear.
WARNING Fragment or activity that had shown a dialogue is responsible for closing it. No other class should be responsible for that. Otherwise, you are going down the route of memory leaks and code that is hard to maintain.
Why doesn't it close?
Inside of your App class in onCreate you instantiate an object of type DCCView and store it as a static variable of that class. Let us say that variable is now pointing to the memory address 0x1234.
Then somewhere else in the code you invoke constructor of MSG1002 class. It creates it's own instance of DCCView as new DCCView(App.getContext()); and stores it inside of MSG1002 class static variable. Let us say that variable is now pointing to the memory address 0x5678.
These variables MSG1002.mDCCView and App.mDCCView are two absolutely different variables that hold references to two different instances of mDCCView. That is why they have different addresses 0x1234 and 0x5678. By attempting to close App.mDCCView you do not close MSG1002.mDCCView dialogue.
How to fix?
Note: strongly recommend to go away from holding a static reference to something related to UI as it holds the reference to Context value and prevents it from being garbage collected when it should be. That is memory leak.
Make private static DCCView mDCCView; public or create get/set methods;
public class App extends Application{
public static DCCView mDCCView;
...
Remove private static DCCView mDccView; from MSG1002 class;
Update MSG1002 class to use App.mDccView:
public class MSG1002{
public MSG1002() {
Handler hnd = new Handler(App.getContext().getMainLooper());
hnd.post(() -> {
App.realCancelAlert();
App.mDccView = new DCCView(App.getContext());
});
}
public void process(){
App.mDccView.showDCC(transactionCurrency, transA, dccCurrency, dccAmount, dataUserDisplay, (DCCView.Response response) -> {
onDccResponse(response, socketCliente);
});
}
...
}
More about memory leaks: memory leak in android, stack overflow issues on dialogues causing memory leaks (9270 results).
public class MyApp extends MultiDexApplication {
private static MyApp instance;
private static class LazyHolder {
private static final Realm INSTANCE = Realm.getDefaultInstance();
}
public static Realm getRealm() {
return LazyHolder.INSTANCE;
}
public static Context getContext() {
return instance;
}
#Override
public void onCreate() {
instance = this;
super.onCreate();
Realm.init(this);
}
}
this is my application activity.
one recyclerView Adapter is using two activities.
first, normal Article List Activity.
second, find Article List Activity.
when I select an Article with the same Url for any Activity, I want to save the Url for that Article.
And this is how I determine if it's stored in Realm in onBindViewHolder().
RealmResults<Article> results = MyApp.getRealm().where(Article.class).equalTo("link", list.get(position).getLink()).findAll();
boolean isSeenArticle = results.size() >= 1;
if(hasKeyword(position)) {
String[] temp = list.get(position).getTitle().split(keyword);
setTitleSpannable(holder.title, temp, isSeenArticle);
}
else {
holder.title.setText(list.get(position).getTitle());
holder.title.setTextColor(isSeenArticle ? context.getResources().getColor(R.color.OneDarkSemiSemiGray) : context.getResources().getColor(R.color.textColorPrimary));
}
color of the holder.articler_title text changes on one side only.
However, both activities appear to have different Realm Instances.
How can I use the same Realm Instance?
I'm currently working on an Android App and i choosed the MVP-Arhitecture.
My Problem is right now, that i need to read and write something from the Database in the Model, but therefor you need a reference to the Context and that is in the View. I want to know, how to get the Context from the View to the Model without breaking the MVP-Architecture (if it is possible).
Thx!!!
Something has to create the model and the presenter i.e.:
new MyModel();
new Presenter();
Usually this is the Activity
#Override
public void onCreate(Bundle savedState) {
Model model = new MyModel();
Presenter presenter = new Presenter(model, this); // this being the View
}
If you are using a database inside of your model you want to use a dependency to do this, maybe called DatabaseReader
#Override
public void onCreate(Bundle savedState) {
DatabaseReader db = new DatabaseReader(this); // this being context
Model model = new MyModel(db);
Presenter presenter = new Presenter(model, this); // this being the View
}
Now you have a class called DatabaseReader that has a Context passed to it through the constructor so you can do "database things", and this class itself is used by the model.
public class DatabaseReader {
private final Context context;
public DatabaseReader(Context context) {
this.context = context;
}
}
and
public class MyModel implements Model {
private final DatabaseReader db;
public MyModel(DatabaseReader db) {
this.db = db;
}
}
So I have this "middle man" nonactivity class, where I want to get a string path from an activity class. Then, from my nonactivity class send that string path to a different activity?
Activity A
#Override
public void onCreate(Bundle savedInstanceState)
{
Intent imageToFactory = new Intent(this,NonActivity.class);
imageToFactory.putExtra("yourImage", user_image_path);//I already set user_image path
}
NonActivity
public class NonActivity
{
private Intent grabImagePath = new Intent();
private String grabImagePathString = getIntent.getStringExtra("yourImage");//this obviously gives an error but for the example
public String grabUserImage()
{
return grabImagePathString;
}
}
Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
NonActivity nonActivity;
String example = nonActivity.grabUserImage();
}
So this method doesn't work for some reason, I think I have to use contexts some how but im not sure exactly how to use them, if anyone can help with examples or modify the example code i did below that'd be awesome!
You can build a static variable that can serve as message bridge, first thing you need to create a class and name it anything you like, in my case I will name the example class as Conn, then add a static HashMap.
public class Conn {
public static HashMap<String,String> storage = new HashMap<>();
}
To utilize this this class in your example:
Activity A
#Override
public void onCreate(Bundle savedInstanceState){
Conn.storage.put("yourImage",user_image_path_in_string);
}
Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
String example = Conn.storage.get("yourImage");
}
if you want to use third class ( here NonActivity.class ) for some reasons, just do it like this:
create globals class like this :
package helper;
public class Globals {
private static final Globals instance = new Globals();
private GlobalVariables globalVariables = new GlobalVariables();
private Globals() {
}
public static Globals getInstance() {
return instance;
}
public GlobalVariables getValue() {
return globalVariables;
}
}
and global variables class like this :
public class GlobalVariables {
public String grabImagePathString;
}
now in activity A::
Globals.getInstance().getValue(). grabImagePathString = "something......";
and in activity B::
String gtabImagePathString = Globals.getInstance().getValue(). grabImagePathString;
Good Luck
is it possible to get all activities in the application? i have a global integer variable that should be in the ActionBar of every activity. i thought something like this:
for (Layout/Activity l in (all activites)) {
l.setTitle(variable);
}
i already tried it with R.layout but this didnt work for me.
How can i do this or is there a better way to display my variable in all activity labels? later i want to call this code from my set method for the global variable.
There is only one activity running at a time, so you can’t get this kind of references.
Said that, I think the way to go it’s create an int static variable in some class, and called it from your activities.
//SomeClass
public static int xValue = 0;
//ActivityOne || ActivityTwo || ActivityThree ...
String text = String.valueOf(SomeClass.xValue);
SomeClass.xValue = 1;
Because it’s a public static variable, you don’t need to instantiate any object to get/set its value, and it will be accesible from any class. Furthermore, this value will be reachable as long as its class is in the memory, and destroy just when class gets unloaded.
yes it's possible with singleton.
This is how to use singleton:
This is Singleton class:
public class Singleton {
private static Singleton mInstance = null;
private String mTitle;
public void setmTitle(String mtitle){
this.mTitle=mtitle
}
public String getmTitle(){
return mTitle;
}
public static FilterArrayList getInstance(){
if(mInstance == null)
{
mInstance = new FilterArrayList();
}
return mInstance;
}
}
This is the first activity:
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Singleton.mInstance.setmTitle("This is Singleton");
}
}
and in second activity:
public class SecondActivity extends Activity {
String Title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Title=Singleton.mInstance.getmTitle();
}
}