I have a problem with a simple class that contains information that I will like to call from another class. For example here is the class Util which contains the info:
public class Util{
public ArrayList<RecetaBean> getRellenas() {
ArrayList<RecetaBean> MiLista = new ArrayList<RecetaBean>();
RecetaBean receta1 = new RecetaBean();
String ingrediente1[] = { getString(R.string.app_name),getString(R.string.app_name),
};
receta1.setIngredientesLista(ingrediente1);
MiLista.add(receta1);
MiLista.add(receta1);
MiLista.add(receta1);
return MiLista;
}
}
Then in another class I get the Items calling like this:
Util u = new Util();
ArrayList<RecetaBean> Recetas = u.getRellenas();
So, I have a execution problem in the class Util with the GETSTRING, because I would like to get a different string (because of different languages). The way to quit the error is to extend the class Util from Activity, but Util is not an Activity! And if I extend from Activity, the app crash.
all you need to do is Define a Context in the Method .
and call it like this;
Util u = new Util();
ArrayList<RecetaBean> Recetas = u.getRellenas(this);
and you the context in you Methods like this:
public ArrayList<RecetaBean> getRellenas(Context con) {
ArrayList<RecetaBean> MiLista = new ArrayList<RecetaBean>();
RecetaBean receta1 = new RecetaBean();
String ingrediente1[] = { con.getString(R.string.app_name), con.getString(R.string.app_name),
};
receta1.setIngredientesLista(ingrediente1);
MiLista.add(receta1);
MiLista.add(receta1);
MiLista.add(receta1);
return MiLista;
}
have you thought about using a string array? It would be so much simpler than what you are trying to do.
I do not think that your concerns about language change are justified, in terms of the overall user experience.
Related
I want to use common function in multiple activity. How can I achieve this?
In my application I am displaying a Dialog box which have some data coming from some api. And this Dialog box, used in multiple activities. Right now I have implemented same Dialog box in all activities. Now I want common Dialog box for all activities. I am using this Dialog box in activity as well in adapter.
How could I do this? Using extends or using fragment.
I am already extending some class so I can not extend again( As I read, we can not extends more than one class.).
Also I want to pass some value to this function and based on return value I want to call another function.
private boolean allGroupsEdit(final String type) {
String allGroups = "allGroups";
final String url = Constants.CONSTANT_SERVER_URL + Constants.CONSTANT_GET_GROUPS_URL;
final ProgressDialog dialog = new ProgressDialog(context);
dialog.setMessage(context.getResources().getString(R.string.please_wait));
dialog.show();
StringRequest allGroupsRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
final SharedPreferences sharedPreferencesRemember = PreferenceManager.getDefaultSharedPreferences(context);
sessionGroupId = sharedPreferencesRemember.getString(Constants.CONSTANT_session_group_id, "");
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.optJSONArray(Constants.CONSTANT_data);
int a = jsonArray.length();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject schObj = jsonArray.optJSONObject(i);
schData = schObj.optJSONArray(Constants.CONSTANT_data);
}
dialog.dismiss();
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_checkbox_options);
Window window = dialog.getWindow();
window.setLayout(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.WRAP_CONTENT);
if(..someting){
editPublicComments(type);
}else{
editPublicPosts(type);
}
}catch(){}
}
}
Note: This a very long function so I am pasting some code for basic understand. If u need anything more detail let me know. Thanks in advance and editing and suggestions are welcome.
Edit_1: I want this whole function to be common.
Edit_2: How to return value to activity from utils ?
Edit_3: Now I created a static function in a class and I am able to call it from my activity. Now I want call another function based on common function result. (I am using SharedPreferences to store value of common function).
But in my activity where I called a common function, I doesn't execute common function first. It call another function then It call common function and after completing common method, it doesn't call another method again.
All I want to call another function based on result of common function which is true or false
boolean abab = CommonGroupBox.allGroupsEdit(context,"share", selectedPostId, localGrpArray);
if (abab){
boolean pubFlag = pref.getBoolean("isPublicFlag", false);
String qType = pref.getString("questionType","0");
if (pubFlag) {
editPublicComments(qType);
}else{
ediComments(qType);
}
else{
boolean pubFlag = pref.getBoolean("isPublicFlag", false);
String qType = pref.getString("questionType","0");
if (pubFlag) {
PublicComments(qType);
}else{
Comments(qType);
}
}
Here it doesn't call CommonGroupBox.allGroupsEdit firsts. It is called after if and else loop.
Just create a normal java class
public class Utility {
//your common method
public static void showDialog(Context context,int type){
//TODO task
}
}
Now you can use the showDialog method any where in your application
Utility.showDialog(ctx,type);
You can create an abstract class which extends AppCompatActivity, implement your method there and make all your other activities extend this class:
public abstract class BaseActivity extends AppCompatActivity {
protected boolean allGroupsEdit(final String type) {
// ...
}
// Other methods
}
Then implement your activity as :
public class MainActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
allGroupsEdit("Some type");
}
...
To create a Utility Class:
1) Create a Java file with name AppUtil which extends Activity.
2) Select a common method that you are going to use in your Application.
3) Write the function in AppUtil java file
4) Make all the function as static in your Java file so it can be easy to call inside your activity (example: AppUtil.yourMethod() )
5) Pass the context of your Activity.
Here is a simple example to check internet connection:
public class AppUtilities extends Activity {
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting() &&
netInfo.isAvailable();
}
}
And you can easily call this method from anywhere in your Application
example ::
AppUtilities.isInternetConnected(YourActivity.this);
EDIT:
This is the method I use to initialize variables after the layout of the activity is loaded in the onCreate() method
private void initializeVariables() {
randomButton = (Button) findViewById(R.id.randomButton);
gameButton = (Button) findViewById(R.id.gameButton);
i = 1;
listIndex = 0;
nameList = PlayersNames.nameList;
villagerBundle = new ArrayList<>();
characters = new ArrayList<Card>();
players = new ArrayList<Player>();
villagerOne = new Villager();
villagerTwo = new Villager();
villagerThree = new Villager();
villagerFour = new Villager();
villagerFive = new Villager();
villagerBundle.add(villagerOne);
villagerBundle.add(villagerTwo);
villagerBundle.add(villagerThree);
villagerBundle.add(villagerFour);
villagerBundle.add(villagerFive);
}
ORIGINAL QUESTION:
I have 2 activities in Android.
In one i create:
public static Villager villagerOne;
villagerOne = new Villager();
Then in the other one I should access to the villagerOne's mAlive variable:
villagerOne.getMAlive();
For reference, these is the Card class:
public class Card {
//Names
public String mCharacter;
//Status
private boolean mAlive;
private boolean mDefended;
private boolean mOwled;
private boolean mLastSavaged;
private boolean mLastLynched;
//Constructor
public Card(){
}
public void setMCharacter(String value){
this.mCharacter = value;
}
public void setMAlive(boolean alive){
this.mAlive = alive;
}
public String getMCharacter(){
return mCharacter;
}
public boolean getMAlive(){
return mAlive;
}
}
And this is the Villager class which extends Card:
public class Villager extends Card {
public Villager(){
mCharacter = "Villager";
}
}
I think if you make the Villager class implement Serializable you could send it with an intent like:
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
Villager villagerOne;
villagerOne = new Villager();
i.putExtra("Villager", strName);
startActivity(i);
And on the second activity you get the results:
Villager villager = (Villager) getIntent.getSerializableExtra("Villager");
Since you declared your villager as static in activity one you should be able to access it from anywhere by
one.villagerOne.getMAlive()
(here I assume the name of the activity class one is one)
Since this solution seems to be controversial I'll tell you why I think it is a good one:
If you pass a copy of the Villager through intent and your Villager gets "killed", the original Villager will be destroyed, why the copies will still be alive. this means you have to communicate to every activity with a copy and tell them to defunct their copy of the villager. Listeners and all.
If you use the reference to the static member, as I suggested, all you have to do is test the reference for null before you call any method:
if( one.villagerOne != null ) alive = one.villageOne.getMAlive();
If you need a copy of that variable, you should pass it in via extras. If you need to access that actual variable- you probably should rearchitect. Data that's needed by multiple Activities shouldn't be owned by any Activity, it should be owned by another data structure that both Activities could reach. For example a singleton Player object which can be queried for its list of cards.
i like use a ActivityName.this (Java Code)
How to convert to C#(Xamarin)?
"this" is not a member of ActivityName
thanks.
public static class a{
public staric void DoWork(Context context){}
}
class b{
a.DoWork((Context)ActivityName)<- error is type but is used like a variable
a.DoWork(ActivityName) <- error is type but is used like a variable
a.DoWork(ActivityName.Context) <-no member Conttext
a.DoWork(ActivityName.this)<-no member this
}
class b is not Activity so this Just not available
There is no this word for Activity.
If you write your app in Xamarin you should use just this keyword.
Please see this, I am creating new CustomProgressDialog object:
CustomProgressDialog _customProgressDialog = new CustomProgressDialog(this);
Hope this will help.
Maybe this could be helpful for you -> For example if you have this code in Java
orientationEventListener = new OrientationEventListener(this) {
#Override
public void onOrientationChanged(int orientation) {
MainActivity.this.onOrientationChanged(orientation);
}
};
You could transfer it to this one in C# (Xamarin)
var myOrientationListener = new MyListener();
myOrientationListener.OrientationChanged += (s, e) => {
MyActivity.onOrientationChanged(e);
};
For a whole example, take a look at this forum post http://forums.xamarin.com/discussion/32576/need-help-porting-java-to-c-how-to-handle-anonymous-inner-class
I want to pass a value from activity A to activity B without actually starting the activity B (therefore this rules out the use of Intents and putExtra). The activity B may or may not be started but when it does it needs to display the value passed to it by activity A.
I searched high and low but couldn't find any relevant solution to this seemingly simple question. Any help will be appreciated!
You can't find a solution, because it's something that goes against any logic.
Activity B can't do anything if not started and visible. Activity B might even already be destroyed by the system without you knowing.
You can use a lot of things to set some variables, which your Activity B can read such as in your Application, somewhere in your XML or simply any random class.
Still, you can not actually DO anything with any of these options, until you start Activity B and when you can, it will just effectively be the same as giving the extra data in the Intent.
Use global class like :
public class AppConfig {
Context context;
public AppConfig(Context mxt) {
context = mxt;
}
public static String filepath = null;
Then, in activity A before onCreate() :
AppConfig config;
Context context;
and in onCreate() method put this :
context = getApplicationContext();
config = new AppConfig(context);
And, in second Activity B before onCreate() :
AppConfig config;
Context context;
And, in onCreate() method put this :
context = getApplicationContext();
config = new AppConfig(context);
And set the value where you want. Hope this will help you.
You can use shared Preferences. Using this one Activity can set Value into it, and other activity can read from it.
So you need to keep a value for an activity . If it starts it means you have to use those values, otherwise you will discard those values. For this you can use a separate class with a variable of datatype that you want and you can create getter setter for that and you can use it.
Make use of the classes
public class GetSet {
public GetSet() {
super();
}
private static boolean passwordSet = false;
public static boolean isPasswordSet() {
return passwordSet;
}
public static void setPasswordSet(boolean passwordSet) {
GetSet.passwordSet = passwordSet;
}
}
You can access ths using GetSet.setPasswordSet(false);
and Boolean flag = GetSet.isPasswordSet();
Set the value as Global:
public class Global {
public static int mValue;
public static int getValue() {
return mValue;
}
public static void setValue(int mValue) {
Global.mValue = mValue;
}
}
I was looking for answers to that but I couldn't find it. So I found a way to do that.
First Activity
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Flag" , true);
startActivity(intent);
Second Activity
boolean flag;
flag = getIntent().getBooleanExtra("Flag" ,false);
if(flag == true)
{
this.finish();
}
So now you may send any data you want it will open the Second Activity and then immediately close it after you wouldn't even realize it. You may use Shared prefences to save your data for after usage.
I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But often my code for using these methods is in some other class that has no reference to an activity. Up until now, I've either stored a reference to the main activity or passed the context of some activity to the class. Is there some better way to do this?
If you already have a valid context, just use this:
Activity activity = (Activity) context;
Passing context is better way for refrence Activity.
You can pass Context to another class.
IN Activity ::
AnotherClass Obj = new AnotherClass(this);
IN Another Class
class AnotherClass{
public AnotherClass(Context Context){
}
}
You can implement the necessary methods in your activity and implement a Handler. Then, simply pass a handler instance to your classes, where you can obtain a message for handler and send it to target.
You can make you application instance a singleton, and use it when you need a Context
An example is in this question:
Android Application as Singleton
This way, when you need a Context, you can get it with
Context context = MyApplication.getInstance()
This might not be the cleanest solution, but it has worked well for me so far
I found a way to get the Activity to a non-activity class that I have not seen discussed in forums. This was after numerous failed attempts at using getApplicationContext() and of passing the context in as a parameter to constructors, none of which gave Activity. I saw that my adapters were casting the incoming context to Activity so I made the same cast to my non-activity class constructors:
public class HandleDropdown extends Application{
...
public Activity activity;
...
public HandleDropdown() {
super();
}
public HandleDropdown(Activity context) {
this.activity = context;
this.context = context;
}
public void DropList(View v,Activity context) {
this.activity = context;
this.context = context;
...
}
After doing this cast conversion of Context to Activity I could use this.activity wherever I needed an Activity context.
I'm new to android so my suggestion may look guffy but what if you'll just create a reference to your activity as private property and assign that in OnCreate method? You can even create your CustomActivity with OnCreate like that and derive all your activities from your CustomActivity, not the generic Activity provided by android.
class blah extends Activity{
private Activity activityReference;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityReference = this;
}
}
after that you could use that the way you want, i.e. in
Intent i = new Intent(activityReference, SomeOtherActivity.class)
etc
There are many ways for Activities communication.
you can use:
the startActivityForResult method
a system of broadcast message and receiver (you can broadcast an event from the actual activity, and register a receiver in the target activity. Remember that the target activity must be previously initialized and non finished)
as you say, store a reference of the target activity wherever you need.
We built a framework for this. We have a BaseActivity class that inherits from Activity and it overrides all the lifecycle methods and has some static (class) variables that keep track of the activity stack. If anything wants to know what the current activity is, it just calls a static method in BaseActivity that returns the activity on top of our privately-managed stack.
It is kinda hacky, but it works. I'm not sure I would recommend it though.
Handle the Intent in the class you want to do these methods, and send your information to it in a Bundle like so:
Intent i = new Intent("android.intent.action.MAIN");
i.setComponent(new ComponentName("com.my.pkg","com.my.pkg.myActivity"));
Bundle data = new Bundle();
i.putExtras(data);
startActivityForResult(i);
Then use an OnActivityResultListener to grab the new data.
I solved this by making a singleton class has an instance of the class below as a member.
public class InterActivityReferrer <T> {
HashMap<Integer, T> map;
ArrayList<Integer> reserve;
public InterActivityReferrer() {
map = new HashMap<>();
reserve = new ArrayList<>();
}
public synchronized int attach(T obj) {
int id;
if (reserve.isEmpty()) {
id = reserve.size();
}
else {
id = reserve.remove(reserve.size() - 1);
}
map.put(id, obj);
return id;
}
public synchronized T get(int id) {
return map.get(id);
}
public synchronized T detach(int id) {
T obj = map.remove(id);
if (obj != null) reserve.add(id);
return obj;
}
}
This class can get a T object and return a unique integer assigned to the object by attach(). Assigned integers will not collide with each other unless HashMap fails. Each assigned integer will be freed when its corresponding object is detached by detach(). Freed integers will be reused when a new object is attached.
And from a singleton class:
public class SomeSingleton {
...
private InterActivityReferrer<Activity> referrer = new InterActivityReferrer<>();
...
public InterActivityReferrer<Activity> getReferrer() {return referrer;}
}
And from an activity that needs to be referred:
...
int activityID = SomeSingleton.getInstance().getReferrer().attach(this);
...
Now with this, a unique integer corresponding to this activity instance is returned. And an integer can be delivered into another starting activity by using Intent and putExtra().
...
Intent i = new Intent(this, AnotherActivity.class);
i.putExtra("thisActivityID", activityID);
startActivityForResult(i, SOME_INTEGER);
...
And from the another activity:
...
id refereeID = getIntent().getIntExtra("thisActivityID", -1);
Activity referredActivity = SomeSingleton.getInstance().getReferrer().get(refereeID);
...
And finally the activity can be referred. And InterActivityReferrer can be used for any other class.
I hope this helps.
public static Activity getLaunchActivity()
{
final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
final Method methodApp = activityThreadClass.getMethod("currentApplication");
App = (Application) methodApp.invoke(null, (Object[]) null);
Intent launcherIntent = App.getPackageManager().getLaunchIntentForPackage(App.getPackageName());
launchActivityInfo = launcherIntent.resolveActivityInfo(App.getPackageManager(), 0);
Class<?> clazz;
try
{
clazz = Class.forName(launchActivityInfo.name);
if(clazz != null)
return Activity.class.cast(clazz.newInstance());
}
catch (Exception e)
{}
return null;
}
Just a guess since I haven't done this but it might work.
1) Get your applicationContext by making your Android Application class a Singleton.
2) Get your ActivityManager class from the context.
3) Get a list of RunningTaskInfos using getRunningTasks() on the ActivityManager.
4) Get the first RunningTaskInfo element from the list which should be the most recent task launched.
5) Call topActivity on that RunningTaskInfo which should return you the top activity on the activity stack for that task.
Now, this seems like a LOT more work than any of the other methods mentioned here, but you can probably encapsulate this in a static class and just call it whenever. It seems like it might be the only way to get the top activity on the stack without adding references to the activities.