I'm currently working on a project that has multiple stages to set up a certain thing. In stage one, the user provides a Title, Description, and a required int value. I need to do two things with this data:
Take the title, and set it as the ActionBar title. This is not hard by any means. I've simply set the variable that the Title value was stored in as an extra on the intent, and retrieved it in the new activity, and set it using the .setTitle(); method on the ActionBar.
Here's the one I need help with...
I need to get that integer value transferred over so I can use it as the number returned by the SectionsPagerAdapter, so when it calls getCount(); it returns the value.
I can get the value inside of the same Class as the Title value, but cannot seem to get it in the SectionsPagerAdapter.
Any help is appreciated!
Alternately you can extend SectionsPagerAdapter and include a setter for that value or use a convenience constructor.
Something like this:
public class CustomPagerAdapter extends PagerAdapter {
private int mPageCount;
/**
*
* #param pageCount
*/
public CustomPagerAdapter(int pageCount) {
this.mPageCount = pageCount;
}
#Override
public int getCount() {
return mPageCount;
}
}
I do not know clearly your problem, but before you change page or when you have value, you can use this class:
Class SavedDave extends Application(){
private static String data;
//Contructor
....
public void SetData(String value){
this.data = value;
}
public String getData(){
return data;
}
}
By this class, you can set and get your value every where when application running, is it solve your problem?
Suppose your method in activity is named getTitle();
From adapter call it like context.getTitle();
where context would be one you pass to the constructor of adapter
private final Context context;
public DataPagerAdapter( Context context )
{
this.context = context;
}
Use Shared Preferences. This is the recommended way to do it in Android.
#SharedPref
public interface ExamplePrefs {
// The name will have default value of "Anonymous"
#DefaultString("Anonymous")
String name();
// The field age will have default value 42
#DefaultInt(42)
int age();
// The field address will have default value of "MyAddress"
#DefaultString("MyAddress")
String name();
// The field lastUpdated will have default value 0
long lastUpdated();
}
For your use case just create a class SectionsPagerPref as follows :
#SharedPref
public interface SectionsPagerPref {
#DefaultInt(0)
int getCount();
}
Related
I have a model class in Java which I converted to data class in kotlin
public class VideoAssets implements Serializable {
#SerializedName("type")
#Expose
String type;
#SerializedName("mpeg")
#Expose
List<Mpeg> mpeg = null;
#SerializedName("hls")
#Expose
String hls;
#SerializedName("widevine")
#Expose
WideVine wideVine;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Mpeg> getMpeg() {
return mpeg;
}
public void setMpeg(List<Mpeg> mpeg) {
this.mpeg = mpeg;
}
public String getHls() {
hls = Macros.INSTANCE.replaceURl(hls);
return hls;
}
public void setHls(String hls) {
this.hls = hls;
}
public WideVine getWideVine() {
return wideVine;
}
public void setWideVine(WideVine wideVine) {
this.wideVine = wideVine;
}
}
As you see I want to change the value of variable hls when I retrieve it.
I created the data class as below
data class VideoAssets(#SerializedName("mpeg") #Expose
var mpeg: List<Mpeg> = emptyList(),
#SerializedName("hls")
#Expose
var hls: String,
#SerializedName("widevine")
#Expose
val wideVine: WideVine? = null) : Serializable
I am struggling here as how should I update the get method for data class.
After searching and taking reference from Override getter for Kotlin data class
I even created a non data class which doesn't seem to work
class VideoAssets(#SerializedName("mpeg") #Expose
var mpeg: List<Mpeg> = emptyList(),
#SerializedName("hls")
#Expose
val hlsUrl: String? = null,
#SerializedName("widevine")
#Expose
val wideVine: WideVine? = null) : Serializable {
val hls: String? = hlsUrl
get() = field?.let { Macros.replaceURl(it) }
}
Whenerver I try to retrieve videoAssets.getHls() it returns null while it should return the new value. The object videoAssets.gethlsUrl() has the value but not `videoAssets.getHls()' is always null.
Can someone point me what I am missing?
Here's your code:
val hls: String? = hlsUrl
get() = field?.let { Macros.replaceURl(it) }
So what this is doing, is creating a property called hls and giving it a backing field (a variable) called field. It initially sets that to whatever value for hlsUrl was passed into the constructor (might be null).
The getter code takes that value for field, and if it isn't null it calls that replaceURl function and returns the result, otherwise it returns null.
So if you set hlsUrl to null, field will always be null and the hls getter will always return null. Even if you update hlsUrl later (whicb I'm assuming you're doing, the code runs fine for me if I pass in a value to the constructor) the value of field is fixed at initialisation.
Also your Java code runs differently - when that gets the new value of hls, it stores that and uses it in the function call of the next get. You're never changing the value of field so your Kotlin code uses the initial value every time.
Technically you don't need the backing field since you're always effectively calling hlsUrl?.let { Macros.replaceURl(it) }. In that case you could make hlsUrl var and update that, or you can add a setter to your hls property and set the backing field when you get the new value
Here's the Kotlin page on properties, in case you haven't seen it!
I have the method getPlan and I try to modify an object (attribute in my class)
class XYZ
/**
* Plan.
*/
private Plan plan;
#Override
public final Plan getPlan() {
subjects.addAll(plan.getSubjects());
...
return new Plan("1", subjects.size(), subjects);
}
#Override
public final Graph createGraph() {
Plan fPlan = getPlan();
...
return graph;
}
In the second method createGraph, I try to get the modified object (fPlan), but it's in the initial state (Plan plan). I hope you understand the situation.
Thanks in advance!
Either your method should not return a Plan, because Plan plan is an instance variable already. Plus you don't instantiate Plan plan anyway, so I guess you have to pick one of below pieces of code:
First piece: we make Plan plan an instance variable, and edit, modify and use that and only that. That means in this class, we don't have to return an Plans, as we have access to Plan plan in this instance of xyz.
class XYZ
private Plan plan;
#Override
public final void instantiatePlan() {
subjects.addAll(plan.getSubjects());
...
plan = new Plan("1", subjects.size(), subjects);
}
#Override
public final Graph createGraph() {
plan = instantiatePlan();
...
return graph;
}
second option: we remove the instance variable Plan plan, and in createGraph(), we call getPlan() with returns a Plan which we can modify and edit there. According to what I guess your context is, I'd go for the first option though.
class XYZ
#Override
public final Plan getPlan() {
subjects.addAll(plan.getSubjects());
...
return new Plan("1", subjects.size(), subjects);
}
#Override
public final Graph createGraph() {
Plan fPlan = getPlan();
...
//edit fPlan here.
return graph;
}
EDIT: Seeing your comment, I understand even less of your problem. First of all, in getPlan() you call getSubjects() on Plan plan, but it's not even instantiated, so it'll throw an NPE immediately. Second: let a method do what the name tells you: thus, getPlan() should just be return plan;, no more, no less, no editing, modifying in that method. I'd suggest making a constructor of class XYZ with params Plan plan:
public XYZ(Plan mPlan) {
this.plan = mPlan;
}
Or initializing it in the constructor:
public XYZ(ArrayList<Subject> subjects) {
this.plan = new Plan("1", subjects.size(), subjects);
}
Please tell where you want plan to be what.
I have several hypothetical 2 - dimensional tables, from which I am to fetch data. I need to make a method that will take in the table id and the "coordinates" of the desired item, and return the item. So far, I have tried making it with multi-layered switches, but I am wondering whether there is any better way to go about this, as the switch code seems too long to be the optimal solution. Any help would be greatly appreciated.
An idea of what my code looks like:
switch(tableId) {
case "table 1":
switch(top) {
case "whatever":
switch(side) {
// et cetera
case "table 2":
// etc
}
Use polymorphism.
Create an interface SearchableTable:
public interface SearchableTable<T> {
T getItem(int x, int y);
}
If these tables are under your control, let them implement this interface. Otherwise, wrap the tables with your own wrapper-classes like so:
public class SearchableTableWrapper implements SearchableTable<MyItemType> {
private final Table wrappedThirdPartyTable;
public SearchableTableWrapper(Table wrappedThirdPartyTable) {
this.wrappedThirdPartyTable = wrappedThirdPartyTable;
}
public MyItemType getItem(int x, int y) {
...
}
}
Now, in the general class where you want to implement a general method that accepts a table id and indices of the item, accept the table itself and invoke its getItem method, like so:
public class TableUtils {
public static <T> T getItem(SearchableTable<T> table, int x, int y) {
return table.getItem(x, y);
}
}
If you have to get table id instead of table, just keep a Map from table id to the relevant SearchableTable, like so:
public class TableUtils {
private static Map<Long, SearchableTable> tableIdToSearchableTable;
public static <T> T getItem(SearchableTable<T> table, int x, int y) {
return table.getItem(x, y);
}
}
This map can be loaded with the actual SearchableTables in several ways, either via static initializer block or static addTable method or you could turn TableUtils to be non-static at all, whatever fits you best.
The main thing here is to use polymorphism.
EDIT
You don't need an enum. Your Table1 from your comment should look like this:
public class Table1 implements SearchableTable<String> {
public String getItem(int x, int y) {
// use x and y to fetch the item friom the 2-dimensional data structure
}
}
You have to rewrite everything in a more object oriented way, one smart way to do it in Java cold be the use of some 'tuned' enums :
enum activity { WHATEVER, SOMETHINGELSE } //Use the same principle as in the enum below ...
enum tables {
TABLE1(activity.WHATEVER),
TABLE2(activity.SOMETHINGELSE),
private activity activity;
tables(activity activity) {
this.activity = activity;
}
public activity activity() {
return this.activity;
}
}
After creating all the needed enum for each needed level, you can use the following "trick" to avoid the long and multilevel switch conditional statement :
String tableId = ...
//Load the table
tables table = tables.valueOf(tableId);
//Call the related attached activity ...
table.activity();
Of course the enum element must have the same name as the variable name that you want to intercept(the same name that you would have put into the check condition of the if or switch statement).
Another similar result can be achieved using a map instead of an enum ...
Take a look at the Command Pattern, for further information .
I have a Play! framework with two actions which contain redundant code. So I factored this code into a private static method, but It doesn't work anymore then.
public static void show(long itemId, String listId) {
render(getItem(itemId, listId));
}
private static Item getItem(long itemId, String listId) {
// otherwise duplicate code ...
return item;
}
If I inline the code contained in getItem into the show action everything is fine:
// this works
public static void show(long itemId, String listId) {
Item item = // duplicate code ...
render(item);
}
Why can I not call other static methods within a Play! controller?
Solution
Thanks to 'Codemwnci' I've implemented the following solution:
public static void show(long itemId, String listId) {
renderArgs.put("item", getItem(itemId, listId));
render();
}
I prefer renderArgs because it makes the intention more clear than a local variable.
When you pass a local variable into the render method, the name of the local variable is used when passed through to the Groovy view. In your example, you are not passing a local variable, therefore Play does not know what name to give the item you have specified.
You have a couple of options. You can do either
Set the return from getItem to a local variable (item), and pass item into the view
Set the return from getItem into the renderArgs map, and specify your own name.
Option 1 is probably the most sensible.
Here's a really simple class:
static public class Bean1
{
final private String name;
final private Bean1 parent;
private int favoriteNumber;
public String getName() { return this.name; }
public Bean getParent() { return this.parent; }
public int getFavoriteNumber() { return this.favoriteNumber; }
public void setFavoriteNumber(int i) { this.favoriteNumber = i; }
}
What I would like to do is to bind some UI components to a BeanAdapter<Bean1> (see com.jgoodies.binding.beans.BeanAdapter) so that if the BeanAdapter points to Bean1 bean1, then I can display
bean1.name (blank if null)
bean1.parent.name (blank if null or if bean1.parent is null)
bean1.favoriteNumber
The fields name and favoriteNumber are easy, but I'm confused about how to display the parent name. It looks like BeanAdapter only lets me bind to properties which exist directly in Bean1. But this is poor modularity and it forces me to add getter/setter functions every time I want to bind to a new aspect of the bean.
What I would like to do is write a helper class which knows how to access a bean, and am confused how to get it to work properly with Bean1 and BeanAdapter.
I'm sorry if this question is not more clear, I don't know the vocabulary and am a little hazy on the concepts of binding.
The problem here is that binding works in both ways: from model to ui, and from ui to model.
In your case, how would you deal with someone entering information for the first time in a textfield that's binded to parent.name? Would you create a parent on the fly? Would you give an error?
If you know what to do in that situation (e.g. create a parent with that name), you could use a com.jgoodies.binding.value.AbstractConverter to convert a Bean1 to a String:
public class ParentNameConverter extends AbstractConverter {
/**
* Converts a value from the subject to the type or format used
* by this converter.
*
* #param subjectValue the subject's value
* #return the converted value in the type or format used by this converter
*/
public Object convertFromSubject(Object subjectValue) { ... }
/**
* Sets a new value on the subject, after converting to appropriate type
* or format
*
* #param newValue the ui component's value
*/
public void setValue(Object newValue) { ... }
}
You can use this converter the same way you use a normal ValueModel:
Bindings.bind(uifield,"value",
new ParentNameConverter(beanAdapter.getValueModel("parent")));