I need to fill data in 50 instances of DataPack.class let's say in class A, but I need to read out that data in some class B. Class DataPack looks like this:
public class DataPack {
int fNumber;
int dateTime;
int Year, fMonth, fDay;
int fTimeHours, fTimeMin, fTimeSec;
int fSize;
char[] name = new char[18];
char[] surname = new char[18];
}
In class A I would create DataPack[] mDataPack = new DataPack[50]; and then fill data in each array member. But for reading in class B, this data array will need to be global.
Is this possible to solve this in that way? Or exists better solutions?
Thanks for help!
Make a ClassicSingleton.java class like below and use that any of function or data member in any of class.
How to make Singleton Class ?
public class ClassicSingleton {
private static ClassicSingleton instance = null;
public ArrayList<String> name = new ArrayList<String>(); // Member
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
public String getName()
{
String myName="Chintan Khetiya";
return myName;
}
public ArrayList<String> getNameformarray() {
name.add("Android");
name.add("IPhone");
name.add("Windows");
return name;
}
}
How to use function and member of the Singleton class ?
ClassicSingleton CS= new ClassicSingleton();
CS.getInstance();
String myName=CS.getname(); // Output will be >> Chintan Khetiya
String like=CS.getNameformarray().get(1); // Output will be >> Android
same way you can use the data member here as publicly by static reference of object.
This is best ans stranded way to use.
Try this solution
Make a BaseActivity extending Activity
Extend your other activities to BaseActivity
Create DataPack array instance in BaseActivity
When saving DataPack details, save it in BaseActivity.
Android has a special class called the Application class. If you declare any variable there it can be accessed through out your application. Its like a global singleton.
public class DataPack {
int fNumber;
int dateTime;
int Year, fMonth, fDay;
int fTimeHours, fTimeMin, fTimeSec;
int fSize;
char[] name = new char[18];
char[] surname = new char[18];
}
public class A extends Application
{
DataPack[] mDataPack = new DataPack[50];
}
Now go to manifest and make the following change:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="com.yourAppName.DataPack">
Then you can go to any activity and use this global singleton like:
DataPack pack = (DataPack)getApplication();
//get the array using <pack.mDataPack> in a loop.
Advantages of using a singleton:
*The application state remains the same even if there is a change in screen orientation.
Related
New to Java. I'm trying to create a class to convert to JSON string to send as POST request using GSON. This class was created within a public class Called BertClient:
private class BertJsonRequest {
private Integer id;
private List<String> texts;
public BertJsonRequest(int x, String text) {
this.id = x;
this.texts = new ArrayList<>();
this.texts.add(text);
}
}
How I use that:
BertJsonRequest rawRequestBody = new BertJsonRequest(1, text);
Gson gsonToJson = new Gson();
String requestBody = gsonToJson.toJson(rawRequestBody);
For the line where I'm creating new BertJsonRequest My IDE tells me that BertClient.this cannot be referenced from a static content.
I wonder what that means.
Am I building the constructor correctly?
I think I'm not. I just want to be able to pass in a String so that constructor can create a List of String using that String.
Your class access modifier is set to private. Try setting the access modifier to public instead.
public class BertJsonRequest {
private Integer id;
private List<String> texts = new ArrayList<>();
public BertJsonRequest(int x, String text) {
id = x;
texts.add(text);
}
}
What I understood by reading your comments on other's answers was, that your BertClientRequest probably is an inner class.
In case it really is an inner class, and you try to call it in a static method of your containing class, it becomes apparent that you cannot instantiate your inner class as that inner class is not static.
public class BertClient {
private class BertClientRequest {
/* some code */
}
static void aStaticMethod() {
// ...
// Inner class BertClientRequest is unknown to your static method as it is not static,
// thus giving you a compile time error
BertClientRequest rawRequest = new BertClientRequest(1, text);
// ...
}
}
The fix would be in this case to change your inner class to static:
private static class BertClientRequest
I guess your BertJsonRequest is a inner class of BertClient. You can't instantiate BertJsonRequest outside of BertClient. You can make BertJsonRequest class static for this to work.
I want to declare a static string array using an array in strings.xml.
private static final String[] tip_types = getResources().getStringArray(R.array.tip_types_array);
but you cannot use getResources() 'in a static context'. Is there a way to do this or must I not use a static variable?
Obviously
private final String[] tip_types = getResources().getStringArray(R.array.tip_types_array);
works, but then the declared array is not static.
To fetch resources (including strings) you always need a context. When you create a static field, even within an Activity, you cannot access the instance fields and therefore there's no context available.
You have two options to solve the problem:
Method 1
You can create an Application class that stores the application context in a static field upon creation and get your string array using the application context.
private final static String[] tip_types = YourApplicationClass.getAppContext().getResources().getStringArray(R.array.tip_types_array);
Method 2
You can create a getter for your static variable where you pass a context. Like a singleton you check if the array is already resolved, and return it right away or fetch is using the supplied context. This has the advantage of lazy initialisation, the array is only created when it's actually needed.
private static String[] tip_types;
private static String[] getTipTypes(Context context) {
if(tip_types == null) {
tip_types = context.getResources().getStringArray(R.array.tip_types_array);
}
return tip_types;
}
The first one, you need declare a NfcApplication custom class which extend from Application class:
public final class NfcApplication extends Application {
private static NfcApplication sApplication;
public static NfcApplication getInstance() {
return sApplication;
}
#Override
public void onCreate() {
super.onCreate();
sApplication = this;
}
#Override
public void onTerminate() {
super.onTerminate();
sApplication = null;
}
}
The second one, then you can call the context by this way
private static final String[] ARRAY_LIST = NfcApplication.getInstance().getResources().getStringArray(R.array.label_unit_array_str);
I'm new here so please forgive possible mistakes :)
I'm writing a game as a final project for my coding classes. And...I'm really stuck. I want to create one object of certain class BUT later on I need to pass there different data from different other classes so I can save all data at the end of using a program.
For example I create an object in MainFrame and get a name of a user from there. Then I go to NextFrame and get age of a user etc etc.
I'd appreciate the answers in as simple english as possible, I'm not fluent :)
I'm using netbeans btw.
Thanks a lot !
Simply try the Singleton Design Pattern.
Simple Example for that:
class SingletonClass {
private static SingletonClass instance = null;
private String customAttribute;
public SingletonClass() {
//default constructor stuff here
}
//important singleton function
public static SingletonClass getInstance() {
if(instance == null)
instance = new SingletonClass();
return instance;
}
// getter and setter
}
now, in your frame or any other class you just do the following:
SingletonClass myObject = SingletonClass.getInstance();
when this function is called for the first time, a new Object is created. Later, it returns the first created. With the help of the Singleton Pattern you can easily save data in one object across multiple classes.
for more information about Singleton:
http://en.wikipedia.org/wiki/Singleton_pattern
hope this helps.
just pass the object to the class you want to, and use it accordingly in a method that you want to ! Here is an example with two classes:
class oneClass {
void oneMethod() {
Class1 myClass1 = new Class1();
Class2 myClass2 = Class2 Class2();
myClass2.setMyClass1(myClass1);
}
}
class Class2 {
Class1 myClass1;
//...
void setMyClass1(Class1 myClass1) {
this.myClass1 = myClass1;
}
//...
void doSomething() {
// do something with instance variable myClass1
}
}
In your case Class1 can be MainFrame and Class2 can be NextFrame or however you want to call them...
As you can see from my code, you pass the class myClass1 to myClass2 using the following line of code : myClass2.setMyClass1(myClass1); and then you can work in this object any way you want
Just send the object of your MainFrame class using a method to wherever you want. The object will contains all data from whenever you change it from different method.
If you need a single object MainFrame all over the class then you may consider of using singleton pattern for creating the object.
to save things to a file(or stream) you can use interface serializable:
import java.io.Serializable;
import java.util.ArrayList;
public class Test implements Serializable {
public ArrayList<Object> urDiferentKindOfThings = new ArrayList<Object>();
public boolean add(Object o) {
if (o != null) {
urDiferentKindOfThings.add(o);
return true;
}
return false;
}
}
Now, just add anything (Object!) that you want to save, then at the end of your game just save the object of type TEST that should contain all your stuff (you may need to read about serializable as it make life easy)
Good Look
You pass class instances into a managing class
public class Game {
private MainFrame mainframe = null;
private NextFrame nextframe = null;
public Game(){
this.mainFrame = new MainFrame();
this.nextFrame = new NextFrame();
}
public Game(MainFrame mainFrame, NextFrame nextFrame){
this.mainframe = mainFrame;
this.nextframe = nextFrame;
}
public String getName(){
return mainFrame.getName();
}
public int getAge(){
return nextFrame.getAge();
}
}
public class MainFrame {
private String name = "John"
public String getName(){
return name;
}
}
public class NextFrame{
private int age = 25;
public int getAge(){
return age;
}
}
class a{
function dosomething(){
//code goes here
}
}
class b{
a firstobject=new a();
c secondobject=new c(a objtopass); //passing object of a to c
function donext(){
//next code
}
}
class c{
a receivedobj=null;
public c(a objtoreceive){
//constructor
receivedobj=objtoreceive;
}
function doAdd(){
//function code
}
}
For example I have a MovieDatabase class that contains a list of Movie objects. In my main code, I initialize all the objects in the MovieDatabase. However I wish to call this MovieDatabase in another class to access the library. How would I do this?
Do I add in get methods in my main code and return it? Or is there another way (eg. changing the list of objects to protected/public?)
Thanks!
Code's supposed to be 3 seperate classes, Main, MovieDatabase & Movie.
An instance of movieDatabase is initialized in Main. Upon construction, it calls loadMovieList() and populates the list from a text file. However I wish to call the same instantiation of movieDatabase from another class in order to access the movies, so that I do not have to repeat the loading.
public class Main {
public static void main(String[] args) {
MovieDatabase movieDatabase = new MovieDatabase();
}
public class MovieDatabase {
ArrayList<Movie>movieList = new ArrayList<Movie>();
String fileAddress = "D:/Users/Mine/School/Java/CZ2002_Assignment/src/MovieDatabase/movieDatabase.txt";
public MovieDatabase()
{
numOfMovie=0;
loadMovieList();
}
public int getNumOfMovie() {
return numOfMovie;
}
public void addMovieToList(Movie movie) {
movieList.add(movie);
numOfMovie++;
}
public Movie selMovieByID(int movieID) {
int index=-1;
for (Movie m : movieList) {
index++;
if (m.getMovieID() == movieID)
break;
}
return selMovieByIndex(index);
}
public Movie selMovieByIndex(int index) {
return movieList.get(index);
}
public void loadMovieList()
{
//loads through text file
addMovieToList(new Movie(tempMovie));
System.out.println("Movie Database loaded");
}
public class Movie{
private int movieID;
private String movieName;
private int movieDuration; //in minutes;
private String movieRating; //G; PG; PG13; NC16; M18; R21;
private boolean has3D;
private boolean status;
}
If you have a class that depends on a NameLibrary, you should inject it via the constructor or a set method.
Firstly, its difficult to assess what issues you truly have without any code to show us.
However you mention main method, as in
public static void main(String args[]){};
this main method is designed specifically to run the application, your compiler needs that specific method, it is not designed to be used as an accessor method
e.g.
public int getValue(){
return value;}
this is not the only reason you can't access the main method variable. main doesn't have a return type (due to the use of void) plus the idea of SCOPE (each method has a scope, any method that contains a variable can see that variable, but nothing outside of it can directly see it without a return type) you use scope to limit what can be accessed or what cannot be accessed outside of the methods or classes (thats why class variables usually will have private, in order to limit accessibility)
Create a getter-method which returns the list inside your NameLibrary. if your other class extends from NameLibrary you can call this getter-method with the object reference to your NameLibrary class.
If you want int x to be accessible from other classes, you write:
public class myClass{
public int x = 0;
}
To access it from other classes, you simply write:
myClass.x ... (do something)
I have a main form (RandomSend) and another form called (_user)
in the randomsend form I declare a public static variable:
public class RandomSend extends javax.swing.JFrame {
......
public static String userGender; // this variable I want to change from another form (_user)
....
}
and in the RandomSend class I declared _user instance that try to change userGender value
_user setGender = new _user();
setGender.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
setGender.setAlwaysOnTop(true);
setGender.setVisible(true);
In the _user form (class) I trying to change userGender vale:
public class _user extends javax.swing.JFrame {......
....
RandomSend.userGender="male";
....}
when I check the value from within _user , the value of RandomSend.userGender is "male"
but from my main form the value is null...
new new
My attempt According to answer number 1
public class RandomSend extends javax.swing.JFrame {
/**
*
*/
private static String userGender;
.....
.....
// show dialogbox to select gender...
_user setGender = new _user();
setGender.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
setGender.setAlwaysOnTop(true);
setGender.setVisible(true);
....
....
// setter
public static void setUserGender(String gender)
{
if(gender.toLowerCase().equals("female") ||gender.toLowerCase().equals("male"))
userGender = gender;
else userGender= "Unknown!!";
}
//getter
public static String getUserGender()
{
return userGender;
}
and in the other class (frame) :
public class _user extends javax.swing.JFrame {
....
....
RandomSend.setUserGender("male");
..
..
..
}
but the Randomsend.userGender doesn't change!
You make changes to an objects member values via the use of getter and setter functions that you define on that object. To use your example you'd end up with something like:
public class RandomSend extend javax.swing.JFrame {
// This should be preferred for values that can mutate (non-final) to prevent
// modification without the owning class being alerted the value is changing
private static String userGender;
public static void setUserGender(String value) {
userGender = value;
}
public static String getUserGender() {
return userGender;
}
}
Using this example you would change the value by calling RandomSend.setUserGender("male") and you would read this value by calling RandomSend.getUserGender().
Some Additional Notes
I just wanted to point out some additional things that I noticed about your sample. Using static values in the manner that you are is not necessarily the best idea. You're locking the use of the class down in the wrong way. You should maintain an instance of a User class or some other kind of class that manages information specific to a user, such as gender. By managing an instance instead of static values on a class you're making it easier for you to handle other users within the application if that need ever rose up. If you are sure you never need to support more than the current user, then you can still use instances but implement it with a singleton pattern.
That would look something like:
public class SingletonExample {
private static SingletonExample instance = null;
// Declared private to prevent new SingletonExample
// outside of this class
private SingletonExample {}
public static SingletonExample getInstance() {
if (instance == null) {
instance = new SingletonExample();
}
return instance;
}
}
You would use this class by fetching an instance like SingletonExample.getInstance() and then operate on that instance. Using this methods guarantees that in all points in your project you're accessing the same instance of the same object making "global" in a sense.
Another note I would like to make is try and use final values or better yet, an enum instead of strings for things like gender which you will most likely use as values. I say this because in order to properly compare genders you have to do:
if (RandomSend.userGender.equals("male")) {
// ...
}
If you instead created a Gender class with constants like:
public Gender {
public static final int MALE = 1;
public static final int FEMALE = 2;
}
And comparisons (provided value changes in the proper classes)
if (RandomSend.userGender == Gender.MALE) {
// ...
}
And no more wasted string literals being passed around. This is such a good idea that Java has an entire construct unique to providing this solution called enums. You would define a Gender enum like so:
public enum Gender {
MALE,
FEMALE;
}
And then you declare you userGender as a Gender value and your comparisons are the same as if you built the enum yourself from a class with constant values. These changes can, in the long run, make your projects more manageable and easier to maintain.