Why can't I make the ArrayList static? - android

I have the following code.
public class Start extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
ArrayList<String> aPlayerList = getIntent().getStringArrayListExtra("playerList");
static ArrayList<Integer> aScores = getIntent().getIntegerArrayListExtra("scores");
...
I get an error when trying to make the ArrayList<Integer> aScores static: Non-static method getIntent() cannot be referenced from a static context , and I don't know how to fix this.
If it helps, this is how the intent was passed:
Bundle bund = new Bundle();
bund.putStringArrayList("playerList", playerList);
bund.putIntegerArrayList("scores", scores);
Intent intent = new Intent(Players.this, Start.class);
intent.putExtras(bund);
startActivity(intent);
Any help would be appreciated, and if you could add the code that would fix it that would be great. Thanks,

Because your syntax is wrong.
You can't make a variable inside a method static what would be the use of this? Static means that the field is related to the class so you can access it without any reference (ClassName.staticField).
Variables inside methods are related to the method, so you can't access them outside it so how static could be used here?
Are you sure you don't get confused with final? Which is a valid here.
To resolve your problem, you just need to make static ArrayList<Integer> aScores as field of the class so you can access it anywhere in your code. Then edit your onCreate method to this
aScores = getIntent().getIntegerArrayListExtra("scores");
so it will save the array list inside aScores field.

That is because getIntent() is a non static method and should not be referenced to a static field.
solution:
Remove the static of your arrayList.

Static methods get created only once, so you can't reference getIntent() because Java doesn't know which instance of the method you are referencing.
Check here for more information on how static methods work.

Related

Getting instance of MainActivity

Hi I am kind of new to android, still learning. And my problem is that, for example I have a method which was created in the MainActivity and I need to call it from another class.
Is it a good practice to get the instance of the MainActivity so that I may be able to call the method in the MainActivity from another class?
This is an example:
public class MainActivity extends AppCompatActivity {
private static MainActivity inst;
public static MainActivity instances()
{
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showToast (String text){
Toast.makeText(inst, text, Toast.LENGTH_SHORT).show();
}
Then this is the other class:
public class broadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
MainActivity instance = new MainActivity();
instance.showToast(AnyText);
}
}
I saw this type of coding while looking at tutorials and wondered if it's a good practice or maybe there might be a better way? Since I get the warning of Do not place Android Context Classes in static classes
Thanks in advance for any insight or help! :D
I guess You want to make A singleton of Activity Class
but as Mention in All Pattern Design
using Singleton
If and Only If its only way to Make A Global Variable
Singleton is based on Lazing Initialing and Load On Memory
so I guess If you cant to Interact With Activiy You can Use
BroadCast Or Intents
You can call method from another class like this:
MainActivity instance = new MainActivity();
String data = instance.data();
and create data method in that class:
public String data() {
return mangaId;
}
Is it a good practice to get the instance of the MainActivity so that
I may be able to call the method in the MainActivity from another
class?
You totally can do this but you don't need to make it static and use a constructor. Just create a new instance like follows and you'll access the public methods
MainActivity mainActivity = new MainActivity();
mainActivity.showToast(text);
About the warning
It suggests avoiding having context fields defined as static. The warning itself explains why: It's a memory leak. If you make it static it will be accessible anywhere in your app and some methods can hold the reference to this context for a really long time and it won't be garbage collected. It will lead to a outofmemory exception and the app could crash. But here you're trying to invoke showToast() from broadcastreceiver so you can just get rid of static references. And it you need them in the future you safe ways to inject context
You cannot create instances of an Activity using the new operator.
You have to use an Intent to let an Activity to be created.
So you cannot get a reference to an instance of your activity.
The only methods you can use of your activity class are static ones.

Android create static ArrayList

im trying to remove values from an arrayList im my android app, but they keep re-appearing.
My arrayList is in a separate class,
in my Main Activty I create an instance of that class and remove a value from the array.
I exit the Main Activity and return the value re-appears.
My Question is how can I can some kind of static instance of the array class???
//ArrayClass
public class ArrayClass {
public final static ArrayList<String> words = new ArrayList<String>();
public ArrayClass() {
words.add("WORD");
words.add("WORD");
words.add("WORD");
}
//Main Class
ArrayClass wordc = new ArrayClass();
#Override
protected void onCreate(Bundle savedInstanceState) {
wordc.removeWord(0);
}
Orest is correct you do want a singleton pattern, but remember when you access the class's methods you always need to use the getInstance() method.
For example a method within the Class:
public String getWord(index i) {
.......
}
Should be called statically as follows
ArrayClass.getInstance().getWord(i);
NOT like this
wordc.getWord(i);
This guarantees that there is one and only one instance (thus the singleton)
I might be confused on what you are doing but to access the static Array you don't want to create an instance of the class. Everytime you do that you are running the constructor which, in the example code, populates your static Array each time with 3 values.
I don't see exactly what you are trying to accomplish so maybe you could explain that a little better but I'm guessing this really isn't what you want your constructor doing. I think you want to access the Array itself statically
//Main Class
ArrayClass wordc = new ArrayClass();
#Override
protected void onCreate(Bundle savedInstanceState) {
wordc.removeWord(0); //don't need this
ArrayClass.words.remove(0); // would remove the element at index 0
}
But this still wouldn't solve your problem. You need a method inside your ArrayClass class that adds items to your Array. Doing it in your constructor will add these items each time you create a new instance of your class.
If this doesn't answer your question then maybe you can explain your assignment a little better.
Have you tried the Singleton patter? You will have one static reference of ArrayClass and it's internal state won't be violated by activity lifecycle.
public class ArrayClass {
private static ArrayClass instance;
public static ArrayClass getInstance() {
if(instance == null) instance = new ArrayClass();
return instance;
}
//...rest goes as is.

Need to instantiate an Android activity to pass to another method

I am trying to call this method:
public static void trackFunXStartActivity(Activity a)
{
s.startFunXActivity(a);
}
I'm trying to call it using this code in my LayoutsActivity.java:
public void onStart() {
TrackFunX.trackFunXStartActivity(LayoutsActivity);
}
but I'm not sure how to create or reference the Activity that I can pass to trackFunXStartActivity(Activity a). I don't think I can pass LayoutsActivity as an Activity.
How do I go about instantiating or reference an activity in LayoutsActivity.java to pass to trackFunXStartActivity.
I'm a Android newbie and have done some searches on StackOverflow but didn't see anything to help with this questions.
Thanks
take a static context for the LayoutsActivity like
static Context context;
and in the oncreate method use
context = LayoutsActivity.this
and finally you can use this context in the class where you need

Concept of introduce class, object?

i'm new here so still very blur with some certain things here.
& i'm a bit confuse with following codes.
public class SmsActivity extends ListActivity {
private String[] mSmsReceiver;
public SmsActivity(){
mSmsReceiver = new SmsReceived();
setListAdapter(new ArrayAdapter<String>(this, R.layout.main,mSmsReceiver));
my understanding: (should be wrong)
line 1: Class SmsActivity under a superclass ListActivity
line 2: i introduce a string array term name:mSmReceiver
line 3: calling method SmsActivity()
line 4: inside SmsActivity method, mSmsReceiver(a string array) call method SmsReceived
line 5: ArrayAdapter(in string form, loaded with the info. of mSmsReceiver) loaded into setListAdapter
My question:
pls correct my understanding upon code above.
line 5, what is this refers to?
(i checked on internet & books, it always says context. but i'm totally no idea what is context exactly means, anyone can explain what is context refering here?)
full codes:
import...
....
public class SmsActivity extends ListActivity {
private String[] mSmsReceiver;
public SmsActivity(){
mSmsReceiver = new SmsReceived();
setListAdapter(new ArrayAdapter<String>(this, R.layout.main,mSmsReceiver));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//---method is call when listitem is clicked---
listView.setOnItemClickListener(new OnItemClickListener() {edit later});
}
private class SmsReceived extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{..... }
}
}
Basically this is a definition of a class named SmsActivity.
You are right about line 1 and line 2. More precisely, mSmReceiver is a private number of class SmsActivity.
Line 3 should be the constructor which I am not sure because I'm not an android developer and I heard it use onCreate instead in Activity. But anyway it wouldn't be calling the method just definition of it. The constructor will be used to initialize the class.
And line 4 mSmsReceiver(a string array) call method SmsReceived. Not the case, it would be initialize mSmsReceiver with an object, which is an instance of class SmsReceived.
Line 5 this refers to the class SmsActivity. In classes this almost always refers to the class it's in. And this provide a context so you can use this.someMumber or this.someFunction.
The keyword "this" in Java is basically a reference to the Class that its in. For example:
public class MyClass {
MyClass myVar = this;
}
This will put an instance of the class MyClass in that variable. It gives you an instance of whatever class your in. If you call it in a method:
public void myMethod() {
MyClass m = this;
}
This will give you an instance of whatever class invoked myMethod. Weather its an instance of MyClass or an instance of a subclass of MyClass. Whatever instance used to invoke the method will be placed in the m variable.
So when you call "this" in an Activity it gives you an instance of that Activity.

is it possible to fetch the object value without calling a new activity?

I know that stuff of calling the new activity and pass the object value from one activity to another by using putExtra and getExtra function. but i want to pass the value without calling and start the new activity. Is it possible ?
If yes then let me know how i can do it ?
You can also use the Application class for declaring global variables
class Globalclass extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class TempActivity extends Activity {
#Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
UPDATED :
Checkout this nice Tutorial about how to do that.
Application Class Using as Global
for this you can use static variable or SharedPreferences or if you heavy data then you can use SQlite.
You can take the help of database like SQLite or you may go for Constant class concept where you can make a public static variable and store your data in one activity and access in other activity.Hope this will help you.
There're a lot of ways to pass a value to an activity:
You can use an Intent with FLAG_ACTIVITY_REORDER_TO_FRONT. In this case onNewIntent() method will be called for already started activity.
You can use static fields or static methods to pass new data to your activity. But it's not a good method really because sometimes application is terminated even if it's foreground and all static data is lost.
You can send new data to an activity using broadcast messages. In this case the activity must register a BroadcastReceiver.
I think it's not very difficult to make up a few more ways to pass arguments.
You may want to use handler's handleMessage() and pass the object in a message .
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
}
};
You can then call handler.handleMessage(msg), you can assign any object to msg.onj

Categories

Resources