Specify a java.lang.Class name in a text file? - java

We started an informal Android development group at work. We'll each be adding semi-independent Activities to a single app. Goofing around yesterday, the best I could come up with to make this 'easy' was to have our main activity be a GridView and allow developers to 'register' their Activities in the main Activity via an element in a hard-coded array of 'ActionItems':
private final ActionItem[] actionItems = {
new ActionItem(R.drawable.dms_to_dd, "DMS to/from DD", DegreeConverter.class)
};
where an ActionItem is just this:
public class ActionItem {
private int drawingID;
private String label;
private java.lang.Class<?> activity;
public ActionItem(int drawingID, String label, Class<?> activity) {
this.drawingID = drawingID;
this.label = label;
this.activity = activity;
}
public int getDrawingID() {
return drawingID;
}
public String getLabel() {
return label;
}
public Class<?> getActivity() {
return activity;
}
}
To get people started I created the first simple Activity/ActionItem and it is registered as shown above.
We want the drawable to be there for the image in the GridView and the String for labeling and, most importantly, the class that will be launched through an Intent when the corresponding GridView item is selected.
All of this works. However, it would be nice if folks didn't have to edit the main Activity to make this work. I was hoping we could read this same information (for the ActionItem) from a text file before populating the GridView. The drawable id and the String are no problem. So the main question: How might we specify that class in a text file?
Is there someway to create a java.lang.Class instance from a name (String/char[])?
Is there some better way to do what I've described above?
Happy to provide further details if helpful.

Have you tried with:
Class.forName("com.something.MyClass")
http://developer.android.com/reference/java/lang/Class.html#forName(java.lang.String)
You can read the name from a file, and set the string in the forName method.
So, you can do something like this:
public ActionItem(int drawingID, String label, String activityClassName) {
this.drawingID = drawingID;
this.label = label;
this.activity = Class.forName(activityClassName);
}

Using reflection, an example below:
Class theClass = Class.forName("YourClass");
YourClass instancevariable = (YourClass)theClass.newInstance();

Related

How To set named locators for allure report?

I've saw a video where is possible to set named locators for allure report
to get view $(locatorname).click - passed:
There is code:
public class Named extends NamedBy {
private final By origin;
private String name;
public Named(By origin) {
this.origin = origin;
}
public Named as(String name) {
this.name = name;
}
#Override
public String toString() {
return Objects.nonNull(name) ? name : this.origin.toString();
}
#Override
public List<WebElement> findElements(SearchContext context) {
return new Named(By.id(id));
}
}
And code for elements:
SelenideElement button = $(id("someid").**as("locatorName")**)
and then should be possible to work with this element.
But i can't.
I dont have method as when i try to create selenideElement.
Pls help. such report is mush more readble.
video URL: https://youtu.be/d5gjK6hZHE4?t=1300
Your example doesn't seem to be valid. At least, a method as must return this. Moreover, id in the overridden findElements is missing. Plus, it's not really clear why you extend NamedBy instead of By.
Anyway, that's just a wrapper around By. To see those locators' names in report you have to follow a previous example in a video first (event listener), before completing NamedBy implementation.
P.S. To make it works the same way as was introduced in the code snippet, you have to add an additional creational logic, e.g.:
public static NamedBy id(String locator) {
return new NamedBy(By.id(locator));
}

How can I add methods that I often use to android studio?

For example,
public void show_message(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
I want this method add auto Activity.java when create new activity or java class.
I want to save different methods like this and include it in the my project quickly where it is needed.
What you should do is create a BaseActivity and make your activity extend this BaseActivity. Add all the default methods in this activity so you can use them everywhere. You can refer this Github project for reference. It uses MVP.
Here is direct link to BaseActivity.
You just need to make a Common Utilities class. Just copy and paste the class in whatever project you are using it. Just make its method access specifiers as public staic so that you can easily access it.
For e.g.
CommonUtilities.showToastMessage(String text);
What I would do is create a config class and store all these small things in it. For example have a look at this :
public class Config {
public Context context;
public String sharedPrefsName;
public String carTablesName, carsTableCarColumn, databaseName;
public int databaseNewVersion, databaseOldVersion;
public boolean showNotificationsToCustomer;
public String customerNotificationState;
public String userMobile;
public SharedPreferences preferences;
public String customerChatTableName;
public String customerChatMessageColumn;
public String customerChatSentByCustomerColumn;
public String customerChatTimeColumn;
public String loggedInUserId;
public String loggedInUserName;
public String customerChatSupportNotifyingUrl;
public Config(Context context) {
this.context = context;
customerChatSupportNotifyingUrl = "";
customerChatTableName = "customerChat";
customerChatMessageColumn = "customerMessage";
customerChatTimeColumn = "sentOn";
customerChatSentByCustomerColumn = "isSentByCustomer";
sharedPrefsName = context.getString(R.string.shared_prefs_login_validator);
preferences = context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE);
customerNotificationState = context.getString(R.string.customer_notification_state);
showNotificationsToCustomer = preferences.getBoolean(customerNotificationState, true);
carTablesName = context.getString(R.string.user_car_table);
carsTableCarColumn = context.getString(R.string.user_car_table_car_column);
databaseName = context.getString(R.string.user_db);
databaseNewVersion = 3;
databaseOldVersion = 1;
loggedInUserId = preferences.getString(context.getString(R.string.user_db), "");
userMobile = preferences.getString(context.getString(R.string.user_mobile), "");
loggedInUserName = preferences.getString(context.getString(R.string.user_name), "");
}
}
I've placed all the constants in a single file so you need not look at them always. If your app grows in size this would be extremely useful.
For using a progress dialog I use a class like this :
public class MyProgressDialog extends ProgressDialog {
String title, message;
public MyProgressDialog(Context context, String title, String message) {
super(context);
if (!title.equals("")) this.setTitle(title);
this.setMessage(message);
this.setCancelable(false);
this.setIndeterminate(false);
}
}
This is nothing but a single class that extends ProgressDialog.So you can aquire all the functionalities of the progress dialog class.
Similarly for toast you could do the same. If you want them to appear when the activity gets created simply keep this:
MyProgressDialog dialog=new MyProgressDialog(this,"title","message");
dialog.show();
in your activity's onCreate() method. You can do the same for toast too.
In case if it is a java class just create a constructor and keep that snippet in that constructor..
You need to read about "File Templates" https://riggaroo.co.za/custom-file-templates-android-studio/ this a large topic, but this is worth it.

Migrate String from Java class to resources

I working in a Quiz Question.
I have on "Questions.java"
package com.example.luisbalmant.quickquiz_science;
import android.widget.TextView;
/**
* Created by LuisBalmant on 15/07/2017.
*/
public class Questions {
public String mQuestions[] = {
"My question here",
};
}
I'm trying use string language of "strings.xml" on "My question here".
Eg:
<string name="Q1_function_insulin">What is the function of insulin?</string>
I'm trying this:
getString(R.string.Q1_function_insulin),
Can someone help me please?
You need a Context object in order to perform getString(). Thus, you can refactor your class this way:
public class Questions {
private static final int QUESTIONS[] = {
R.string.text1,
R.string.text2
};
private Context context;
public Questions(Context context) {
this.context = context;
}
public String getString(int index) {
return context.getString(QUESTIONS[index]);
}
}
And then, from your activity:
Questions questions = new Questions(MainActivity.this);
questions.getString(0);
If i got your question right, i assume you want to load all questions from the strings.xml file and place them inside the mQuestions array. What you wrote there (getString(R.string.Q1_function_insulin)) should work without any problem. I suggest that you put all your questions in an array inside the xml and load the whole array at once with getStringArray(R.array.questions).

Serialization of a Callback

My application has some settings that can be configured, and some generate warnings. I need a way to preserve those warnings even if the application has been closed.
My warnings are structured as it follows :
public class CustomWarning implements Serializable {
private final WarningType warningType; // enum
private final String title, description;
private final CustomCallback resolution;
public CustomWarning(String title, String description, CustomCallback resolution, WarningType warningType) {
this.title = title;
this.description = description;
this.resolution = resolution;
this.warningType = warningType;
}
public WarningType getWarningType(){
return warningType;
}
public String getTitle(){
return title;
}
public String getDescription() {
return description;
}
public CustomCallback getResolution() {
return resolution;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof CustomWarning){
return ((CustomWarning) obj).getWarningType() == warningType;
}
return false;
}
}
The context is the following : An user, for example, wants to set the logging output to HIGH. This will decrease the performance of the app, and thus a warning is generated. This warning will contain a title ("High output") and a description ("You have set HIGH as Logging") and will be displayed in a Dialog. Here is the function that shows my warning in the Dialog :
// This will show a new dialog with title, description, and resolve/close buttons
Optional<Boolean> result = DialogFactory.getInstance().createShowWarning().showAndWait();
if(result.isPresent() && result.get())
myWarning.getResolution().run(); // calls the "callback"
By pressing the "Resolve" button on the Dialog, it will get my CustomCallback and invoke the run() function, which can be, for example, show the configuration panel for the logging options.
The CustomCallback is just an interface :
public interface CustomCallback extends Runnable, Serializable {}
What would be the best way to preserve a List<CustomWarning> warnings after closing the app ? The following have been checked, but none seemed to work correctly :
Serialization of the List<CustomWarning> : Was a bit difficult, since the serialization from the Java API also serializes the parents, and I don't want to serialize every controller I have in my app.
Serialization of the class name / method name of the callback : Couldn't find a way to call the callback without the instance of the class, which I can't always recreate or provide.
Are there any other possibilities for the ways I've mentionned, or any new ideas ? Every comment is welcome.
Also : No external library would be better

Permanent Objects passed from one Activity to another

I must pass an ArrayList from one Activity A to another Activity B.
I did it using getSerializableExtra and putExtra methods. I already know the meaning of these methods, but I don't know if stuff that I passed using them is stored permanently in the new activity or if it is necessary to reload activity A in order to retrieve my data in B.
So the question is: how can I load my data in a initial splash screen and then use it in all my others activity without reloading the splash screen?
Don't use Preference Class! Preferences are only used for settings values. For passing data to another Activity use Serializable or Parcelable. Remember that all the objects which will be passed to another activity have to implement Serializable or Parcelable. So you extend the ArrayList to a custom Class which implements Parcelable or Serializable.
You do this like this:
Intent intent = new Intent(getContext(), SomeClass.class);
intent.putSerializableExtra("value", <your serializable object>);
startActivity(intent);
and receive them like
YourObject yourObject = getIntent().getSerializableExtra("value")
or look here for Parcelable
Help with passing ArrayList and parcelable Activity
Data processed in Activity A does not need to process again in Activity B. If the data is computed in A and you send it to B computed, B receives it computed already.
Here are some ways to do it right: http://developer.android.com/guide/topics/data/data-storage.html
You can use Preference class, in which you can define its static instance. Than create variable according your desire datatype (even ArrayList). Make property for get and set of this variable.
Set the value on splash screen and get anywhere in application where you need.
Try this, if you need , I will upload code also.
I have written some code regarding that, it would help other activities to fetch data easily, use this when the data is not confidential,
public class HelperShared {
public static final String score = "Score";
public static final String tag_User_Machine = "tag_User_Machine",
tag_Machine_Machine = "tag_Machine_Machine",
tag_Draw_Machine = "tag_Draw_Machine",
tag_Total_Machine = "tag_Total_Machine";
public static SharedPreferences preferences;
public static Editor editor;
public HelperShared(Context context) {
this.preferences = context.getSharedPreferences(score,
Activity.MODE_PRIVATE);
this.editor = preferences.edit();
}
/*
* Getter and Setter methods for Machine
*/
public void setUserMachine(int UserMachine) {
editor.putInt(tag_User_Machine, UserMachine);
editor.commit();
}
public void setMachineMachine(int MachineMachine) {
editor.putInt(tag_Machine_Machine, MachineMachine);
editor.commit();
}
public void setDrawMachine(int DrawMachine) {
editor.putInt(tag_Draw_Machine, DrawMachine);
editor.commit();
}
public void setTotalMachine(int TotalMachine) {
editor.putInt(tag_Total_Machine, TotalMachine);
editor.commit();
}
public int getUserMachine() {
return preferences.getInt(tag_User_Machine, 0);
}
public int getMachineMachine() {
return preferences.getInt(tag_Machine_Machine, 0);
}
public int getDrawMachine() {
return preferences.getInt(tag_Draw_Machine, 0);
}
public int getTotalMachine() {
return preferences.getInt(tag_Total_Machine, 0);
}
}
if your question is "how can I load my data in a initial splash screen and then use it in all my others activity without reloading the splash screen?" Than I have better solutions for you.
Create a Class Memdata.java
public class Memdata{
private static Memdata instance = null;
private String userobject;
public static Memdata getInstance(){
if ( instance == null){
instance = new Memdata();
}
return instance;
}
public String getuserobject() {
return userobject;
}
public void setuserobject(String userobject) {
this.userobject= userobject;
}
}
on You Splash Screen' onCreate method, set the value
Memdata obj = Memdata.getInstance();
obj.setuserobject("hello");
Than in any activity, where you want to access this variable, just make its object and get value.
Like in MyActivity class
Memdata obj = Memdata.getInstance();
String str = obj.getuserobject()
You can define any type of variable according your requirement.
You can extend the base Application class and add member variables to it:
public class MyApp extends Application {
private String appLevelString;
public String getAppLevelString() {
return this.appLevelString;
}
public void setAppLevelString(String val) {
this.appLevelString= val;
}
}
You will have to update the manifest file as follows:
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:name="MyApp">
You can get and set data like this:
//For setting
((MyApp) this.getApplication()).setAppLevelString("Test string");
//For getting
String str = ((MyApp) this.getApplication()).getAppLevelString();

Categories

Resources