How can I get an object's attributes?
I created an object that has two fields, first one called Title containing the string value "title1" and second one called Description containing the string value "description1". I would like to get the strings inside.
The method item.toString() gets me the two strings one after the other. Is there a way to get the strings separatively?
Just create accessor methods for each field.
Assuming you have declared your fields like this:
private String title;
private String desciption;
create the accessor methods in your class definition like this:
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
then you just call these methods to get the appropriate value.
Class Declaration
public class Class_Name {
private String Category;
private String Category_Type;
public Class_Name () {
super();
}
public Class_Name(String Category, String Category_Type) {
super();
this.Category = Category;
this.Category_Type = Category_Type;
}
/*public Class_Name (String Category_Type) {
this.Category_Type = Category_Type;
}*/
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public String getCategory_Type() {
return Category_Type;
}
public void setCategory_Type(String Category_Type) {
this.Category_Type = Category_Type;
}
}
In the class where you should use this Object to store and retrieve values.
//Create an object for this class
private Class_Name data;
// To save values
data.setCategory(sCategory);
data.setCategory_Type(sType);
// To retrieve values
String sCategory = data.getCategory();
String sType = data.getCategory_Type();
Related
I've already tried to use
String mystring = getResources().getString(R.string.mystring);
And I found the same theme in this article How can I convert the android resources int to a string. eg.: android.R.string.cancel?. But it doesn't work in my situation.
This is my code:
public class Film{
private int image;
private String name;
private String schedule;
private String description;
public Film() {
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
...
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class FilmList {
public static ArrayList<Film> getFilms(){
ArrayList<Film>films=new ArrayList<>();
Film film=null;
film =new Film();
film.setName(getResources().getString(R.string.name1));
film.setImage(R.drawable.img1);
film.setDescription(getResources().getString(R.string.desc1));
films.add(film);
film =new Film();
film.setName(getResources().getString(R.string.name2));
film.setImage(R.drawable.img2);
film.setDescription(getResources().getString(R.string.desc2));
films.add(film);
return films
}
}
If you don't have access to a Context (e.g. via an Activity, Service, ContentProvider, or BroadcastReceiver), you cannot get a string resource.
If you have a class that is not one of the above and it needs to get a string resource, you must either have pass a Context to that class so it can retrieve the resource, or pass that class an already-resolved resource.
Make an application class and add a hold its reference in a static varialble. then you can access context anywhere in the app
public class MyApp extends Application {
private static AppLWP instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
Then you can access this instance for context anywhere in the app
public static ArrayList<Film> getFilms(){
ArrayList<Film>films=new ArrayList<>();
Film film=null;
film =new Film();
film.setName(MyApp.instance.getResources()
.getString(R.string.name1));
film.setImage(R.drawable.img1);
film.setDescription(MyApp.instance.getResources()
.getString(R.string.desc1));
films.add(film);
film =new Film();
film.setName(MyApp.instance.getResources()
.getString(R.string.name2));
film.setImage(R.drawable.img2);
film.setDescription(MyApp.instance.getResources()
.getString(R.string.desc2));
films.add(film);
return films
}
}
First, provide context to the class Film via the activity you are calling the object of Film.
If you call from Main Activity you will have to do something like this:
public class MainActivty extends AppCompatActivity {
private static MainActivty obj;
onCreate() {
//usual functions
obj = MainActivity.this;
}
}
Once you have the context, simply try this:
String mystring = context.getString(R.string.mystring);
Or, if you floowed my MainActivty method:
String mystring = MainActivty.obj.getResources().getString(R.string.mystring);
I will try to be brief:
I have three classes that have to interact in this:
The server, which receives the message (in a thread).
The contact, which stores messages in its class (in each object).
The chat activity belonging to each user, which has to show the
messages of the corresponding object, the idea is that it is a RecyclerView.(an activity)
The server receives a message, this message would be added to the chat of the specific contact and then the RecyclerView must be updated.
This is the basic Contact class code:
public class Contact implements Serializable {
private String name;
private String ip;
//Here would be a variable that contains the chat strings
public Contact (String name, String ip){
this.name = name;
this.ip = ip;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
And then there is the activity of the chat that is launched when selecting a specific user and it contains a RecyclerView where I want the messages to be.
My problem is that, how to make the messages that are stored in the
variable of a specific object appear in the list.
From already thank you very much.
you can use data class instead of serialization
public class Data {
private String text;
private String uid;
private String tnviews;
private String numberlikes;
public Data(String text,String tnviews,String numberlikes,String uid) {
this.text = text;
this.tnviews = tnviews;
this.numberlikes = numberlikes;
this.uid = uid;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
/////////// VIEWS
public String getViews() {
return tnviews;
}
public void setViews(String tnviews) {
this.tnviews = tnviews;
}
//////// likes
public String getLikes() {
return numberlikes;
}
public void setLikes(String numberlikes) {
this.numberlikes = numberlikes;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
you can Update RecyclerView Adapter Data
mAdapter.notifyDataSetChanged();
Reference link
I am currently building an app to retrieve information for a remote server. the data received are JSON and I am build a list of Data using the class below :
public class RedditData {
private RedditTopic data;
public RedditTopic getData() {
return data;
}
}
and RedditTopic class is defined as below:
public final class RedditTopic {
private static final String TAG = RedditTopic.class.getSimpleName();
private String author;
private String thumbnail;
private String title;
private String num_comments;
private long created_utc;
private String data;
private String name;
public RedditTopic(){};
public String getData() {
return data;
}
public String getAuthor() {
return author;
}
public String getThumbnail(){
return thumbnail;
}
public String getTitle(){
return title;
}
public String getComments(){
return num_comments + " comments";
}
public long getCreated_utc(){
return created_utc;
}
public String getRedditName(){
return name;
}
}
both of these classes are used to translate a JSON into an Object formatted data.
I do not want to really change them to make them Parceable to avoid impacting the extraction of JSON.
I have added :
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> SAVE");
savedInstanceState.putParcelableArrayList("RedditList", myListOfData );
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> RESTORE");
List<RedditData> myListOfData = savedInstanceState.getParcelableArrayList("RedditList");
}
Android complain because I need to implement Parceable in my class RedditData and I assume probably in the RedditTopic Class as well because RedditData returned a List of RedditTopic.
Is there a better way to do it? keep the List as I have it without requiring the Parceable option.
I do not have a List of String, it's a list of object.
Any idea?
Regards
Make your model objects parcleable.
There is a great extension, https://plugins.jetbrains.com/plugin/7332-android-parcelable-code-generator that will generate the neccesary parcelable methods for your class.
I highly recommend it.
I have different packages in my app like this.
CansTypeObject class looks like this
public class CansTypeObject {
String productId;
String productName;
String productPrice;
String productReturnPrice;
String productImage;
}
Now, I want to access these strings from MainActivity
CansTypeObject object = new CansTypeObject();
But I cant. If I move the CansTypeObject class to the same package as that of MainActivity, I can access them. What is the solution for this?
The default scope is package-private. Use the public modifier on the String declaration
public String productId;
The only reason of this behavior is that you declared yours class Strings as package-protected strings. In Java this means, that this fields will be accessible only for classes in the same package.
There are several solutions for your problem.
The first (and the worst) - declare your fields as public strings, like this:
public String myField;
The second - create getters for your fields and declare your strings as private fields, like this:
private String myField;
public String getMyField() {
return myField;
}
Then, use this getters on your class object.
Hope, it helps.
You can define getter-setter method for the CansTypeObject class as follows for accessing them easily:
public class CansTypeObject {
String productId;
String productName;
String productPrice;
String productReturnPrice;
String productImage;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getProductReturnPrice() {
return productReturnPrice;
}
public void setProductReturnPrice(String productReturnPrice) {
this.productReturnPrice = productReturnPrice;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
}
for creating getter-setter method you can use shortcut key for
MAC - command + N
Windows - Alt + Insert
Another way is to open the class for which you have to make getter setter and then right click and from the context menu select Generate option
I'm making a model for daily Forecast but I'm having some trouble with creating this model.
It has regular information (date, description...) but I need it to have various Strings of information in it for every 3 hours...(temperatures, wind speed, wind direction etc)
And that's where I don't know how to do it..maybe with an Array of some sort but not sure.
So far, here is what I have:
public class DayForecast implements Serializable{
private String date;
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Thx!
Try using ArrayList<HashMap<String,String>>. With this you can implement the same with less hassle and in organized manner.
Example usage:
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> data = new HashMap<String,String>();
data.put("description", your_string_description);
data.put("date", your_string_date);
data.put("other", your_string_other_information);
list.add(data);
And to get your data:
list.get(0).get("description"); //will return the string description in position 0
list.get(0).get("date"); //will return the string description in position 0 you can convert it to date if needed
note that the get(0) is the position in your arraylist since with this you can add more items let's say description.
It doesn't sound like an array of Strings would do it, since you mentioned temperature, wind-speed, wind-direction etc. I would create another model for that and store instances of it within the current one.
e.g.
public class WeatherCondition {
private double mTemperature;
private double mWindSpeed;
private String mDirection;
public WeatherCondition(double temperature, double windSpeed, String direction) {
mTemperature = temperature;
mWindSpeed = windSpeed;
mDirection = direction;
}
// ... setter and getter methods ...
}
and
public class DayForecast {
private String mDate;
private String mDescription;
private SparseArray<WeatherCondition> mWeatherConditions = new SparseArray<WeatherCondition>();
public WeatherCondition getWeatherCondition(int timeInHours) {
// return null if no weather condition was set
WeatherCondition weatherCondition = mWeatherConditions.get(timeInHours);
// or you could add some other logic here, if you would want the next available weather condition,
// but make sure to reflect that in the method name
return weatherCondition;
}
public void setWeatherCondition(int timeInHours, WeatherCondition weatherCondition) {
mWeatherConditions.append(timeInHours, weatherCondition);
}
// ... other setter and getter methods
}