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).
Related
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.
I am currently working on an app that will use many objects as information holders (music things - artist, song, id of album cover img, and another id of 2nd img).
I decided that it would be the best to create "Track" class and use it to make objects and store them in ArrayList.
I created the class, I created the list, but I'm having trouble with accessing it (I want to change the ImageViews and TextViews basing on current Track object).
Here's the Track Class: (Track.java separate)
public class Track {
private String mNameArtist;
private String mNameTrack;
private int mTabResource;
private int mCoverResource;
public Track(String nameArtist, String nameTrack, int tabResourceId, int coverResourceId){
mNameArtist = nameArtist;
mNameTrack = nameTrack;
mTabResource = tabResourceId;
mCoverResource = coverResourceId;
}
public String getArtistName() {
return mNameArtist;
}
public String getTrackName() {
return mNameTrack;
}
public int getTabResourceId() {
return mTabResource;
}
public int getCoverResourceID() {
return mCoverResource;
}}
And here's ArrayList declaration: (PlayActivity.java, inside onCreate method)
ArrayList<Track> Tracks = new ArrayList<Track>();
Tracks.add(new Track("Artist Name", "Track Name", R.drawable.tabtemplate, R.drawable.testcover));
Tracks.add(new Track("Pink Floyd", "Comfortably Numb Solo 1", R.drawable.CNS1Tab, R.drawable.pink_floyd_the_wall));
There are more positions, but you get the idea.
Everything seems to work fine up to this point.
When I want to access it inside another method (even in the same PlayActivity.java) nothing happens or I see errors. I tried many different approaches but every single one fails. For example:
Track.getTabResource(); // can't even use the method.
Tracks.get(3); // does not work as well.
I just can not use objects or that arraylist inside my methods. The "Tracks array" won't even show up in Android Studio when typing. Track does, but I can't access positions from Array.
So to sum up, is there any other way I can use my Objects (ArrayList) items inside other classes and methods?
Thank you for your help in advance.
Create List as instance variable and access through Object of that class.
public class PlayActivity {
List<Track> tracks = new ArrayList<Track>();
public void onCreate() {
tracks.add(new Track("Artist Name", "Track Name", R.drawable.tabtemplate, R.drawable.testcover));
tracks.add(
new Track("Pink Floyd", "Comfortably Numb Solo 1", R.drawable.CNS1Tab, R.drawable.pink_floyd_the_wall));
}
public List<Track> getAllTracks() {
return Collections.unmodifiableList(tracks);
}
public Track getTrack(int index) {
return tracks.get(index);
}
}
I'm coding an Android app with Firebase and want to write an object to the database:
public class newEvent {
public String whoEv;
public String whereEv;
public String whenEv;
public String whatEv;
public newEvent() {}
public newEvent(String whoEv, String whereEv, String whenEv, String whatEv) {
this.whoEv = whoEv;
this.whereEv = whereEv;
this.whenEv = whenEv;
this.whatEv = whatEv;
}
}
This works, but as you can see they are all 'just' strings. What i want is to have the first argument to be a List, Firebase doesnt allow String[] uploads/writings.
The reason is to be able to pass more names into the whoEv as separated Strings/Objects. (to give each name a boolean if they are coming or not).
Now to the exact problem:
public newEvent(List<String> whoEv, String whereEv, String whenEv, String whatEv) {
this.whoEv = whoEv;
this.whereEv = whereEv;
this.whenEv = whenEv;
this.whatEv = whatEv;
}
When i use this, i have no clue how to write the proper code:
newEvent test = new newEvent(List<String>("derp","max"), "Amsterdam", "31/12/2016", "NewYears Eve");
The above obviously doesnt work. Expression expected or unexpected token. What am i missing or doing wrong? Already thanks for reading this!
Edit: Total idiot idea to use List<String>if i want to pass boolean values with the strings... Dont got clue what to use instead though.
Fixed it:
newEvent test = new newEvent("Meppel", "31/12/2016", "Oudjaarsdag", new String[]{"derp", "Sir", "max"});
And in the class as:
`public class newEvent {
public ArrayList<String> wie;
public String waar;
public String wanneer;
public String wat;
public newEvent() {}
public newEvent(String waar, String wanneer, String wat, String... wie) {
this.wie = new ArrayList<>(Arrays.asList(wie));
this.waar = waar;
this.wanneer = wanneer;
this.wat = wat;
}
List is an Interface, you can't directly use it with out a implementation class. You can use one of default jdk provided classes which implements List interface. example ArrayList, LinkedList.
Go through this link on List Implementations and you will understand how you can pass a list of string as argument.
Is it Java? May be you need add the word "new" before List...
And don't forget List is an interface type, so here need use some inheritance class. ArrayList for example
This is not about BrainF*ck. Please refer to the last section for the "ultimate" question.
I am terribly sorry, if that has been asked before, but I just couldn't find a page where this has been asked before.
I basically have a java project set up, that let's you write BrainF*ck code and then execute it. For those who don't know, BrainF*ck is a very simple programming language that only uses one-character commands.
I have set it up to where all the implemented letters have individual classes that extend to a Token superclass.
public abstract class Token {
private final char token;
public Token(char c) {
this.token = c;
}
public final char getToken() {
return token;
}
public abstract void tokenCalled();
}
So as an example, for the Token '+' I would have the class set up like this.
public class PlusToken extends Token {
public PlusToken() {
super('+');
}
#Override
public void tokenCalled() {
//increment value by 1
}
}
This works all fabulously well.
Now for my project, I wanted the user to be able to create his own classes and put them in a pre-existent folder where my program will loop through the classes and include those Tokens into my projects. I have an arraylist set up that contains all the Tokens, so the only problem I'm having is: How do I read those classes, check if they are instances of Token and save those in my arraylist to use them?
This is about Java's reflection. Keywords for search: "java reflect all subclasses", and you will find a lot.
How do you find all subclasses of a given class in Java?
The "ClassPathScanningCandidateComponentProvider" answer may meet your need.
But in my opinion, there are simpler word-arounds. Something like following will simplely do the job:
public abstract class Token {
public static HashMap<Character, Class<Token>> all = new HashMap<Character, Class<Token>>();
private final char token;
public Token(char c) {
this.token = c;
all.put(c, this.getClass());
}
public final char getToken() {
return token;
}
public abstract void tokenCalled();
}
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();