Access string from another class - android

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

Related

Converting the string resources to strings

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);

Update a RecyclerView from another class

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

com.google.firebase.database.DatabaseException

When I start the activity, it is showing the error:
Class com.rcpl.agni.Artist does not define a no-argument
constructor.If you are using ProGuard, make sure these constructors
are not stripped.
protected void onStart() {
super.onStart();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//artistList.clear();
for(DataSnapshot artistSnapshot : dataSnapshot.getChildren()){
Artist artist = artistSnapshot.getValue(Artist.class);
Toast.makeText(MainActivity.this, artist.getArtistName(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Artist.java
package com.rcpl.agni;
/**
* Created by Dell-pc on 23-01-2018.
*/
public class Artist {
String artistId;
String artistName;
String artistGenre;
public Artist(String artistId, String artistName, String artistGenre) {
this.artistId = artistId;
this.artistName = artistName;
this.artistGenre = artistGenre;
}
public String getArtistId() {
return artistId;
}
public String getArtistName() {
return artistName;
}
public String getArtistGenre() {
return artistGenre;
}
}
To solve this, you just need to add the public no-argument constructor to your Artist class.
public Artist() {}
Remember, when the Firebase Realtime Database SDK deserializes objects coming from the database, it requires that any objects to a have a public no-argument constructor. This is needed to instantiate that particular object. All the fields within the object are set by using public setter methods or direct access to public members.
If you don't use a public no-arg constructor, the SDK doesn't know how to create an instance of the class. Most serialization libraries will have the same requirement.
I believe the error is pretty self-explanatory. You just need to add an empty constructor to your Artist class:
package com.rcpl.agni;
/**
* Created by Dell-pc on 23-01-2018.
*/
public class Artist {
String artistId;
String artistName;
String artistGenre;
public Artist(){}
public Artist(String artistId, String artistName, String artistGenre) {
this.artistId = artistId;
this.artistName = artistName;
this.artistGenre = artistGenre;
}
public String getArtistId() {
return artistId;
}
public String getArtistName() {
return artistName;
}
public String getArtistGenre() {
return artistGenre;
}
}
Firebase requires this constructor in order to use it when you call artistSnapshot.getValue(Artist.class);
add the non-argument in the Data class
Run the app with a clear logcat:

Save a List of custom object in savedInstanceState

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.

how to get object's attributes

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();

Categories

Resources