Another "Cannot make static reference..." Question - android

I am trying to write an Activity that has some views, a fillView() method that sets the views (which is not static because it must utilize getContentResolver), and a static method that makes a random choice from a cursor and then runs the fillView() method.
I had problems with this due to fillView not being static and pickRandom being static, so I tried to initialzize an instance of the class, but now it crashes on the line instance.fillView();
Sample code below. Any help would be appreciated. Perhaps there is a much easier way to accomplish what I am trying to do.
Thanks,
Josh
public class myView extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.myView);
fillView();
}
public void fillView(){
//creates views, runs cursor and applies results to the view created
}
public static void pickRandom() {
// runs cursor, picks random entry, next I want to apply the result to
// view, so I run...
myView v = new myView();
v.fillView();
}

Make a static instance variable and set in in oncreate:
private static myView instance;
oncreate()
instance = this;
static pickrandom()
instance.fillView();

in your pickRandom you try to create new instance of your class. Instead of this you should do the following:
this.fillView();
I don't see any purpose you have your pickRandom static.
If, however, you need it for some reason you can pass a reference to your view like this:
public static void pickRandom(myView v) {
// runs cursor, picks random entry, next I want to apply the result to
// view, so I run...
v.fillView();
}

Related

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.

How to pass data from one class to another, when Bundle can't be used?

I have two Classes. Class A is an Activity that has integer variables that need to be used in Class B (not an Activity). I have been able to use Bundles to transfer data of variables from one Activity to another Activity before. The problem is that this time, Class B is not an Activity and extends ImageView so that the draw() function can be used. Because of this, I am unable to use normal Activity functions, such as Bundle-Intents or SharedPreferences to transfer data in primitive variables from Class A to my Class B. I receive an error saying that "getIntent() is undefined for type".
So my question is, how can Class B use the variables in Class A if I am unable to bundle? Is there another way?
Someone said they did not understand my question so hopefully the below example will help demonstrate better.
public Class1 extends Activity {
//so Class1 has some primitive data, and is an Activity w/layout
int var1;
int var2;
Bitmap bitmap;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
}
}
A different class needs to draw onto canvas, but also needs to use the
information in var1 and var2 to be able to draw properly. But how to obtain that information?
public Class2 extends ImageView {
/*I am unable to use normal Activity functions, so I
*cannot onCreate, for example. I also cannot bundle,
*getIntent(), or use getSharedPreferences(). So how do I get var1
*and var2 value? */
}
Update: I was able to get this to work using getters. I attempted this before, but it was not returning the correct values. If anyone else ever gets stuck with this similar issue, remember to setup your variables with "static". I'm still learning all the differences, but without static my getter was not working. Once I added static to my variables, everything worked out. So that's one observational tip (even without fully understanding the logic as to why). Thank you to all the responders for your tips.
You can do this in different way.
First of all you can use static variable to do this. Such that you can declare a variable in class A public static String variable; and from class B you can get the value of this variable like this way ClassA.variable.
Another way you can use by passing a context of class A to B and then use SharedPreference.
Or create a new class which extends android Application. From class A you can set different variable value in application class. Now you can retreive those values from Application class. Hope this can help you.
Some code Sample using static variable
public Class1 extends Activity {
public static int var1 =20;
public static int var2 = 30;
}
Now get the variable value from class two
public Class2 extends ImageView {
Class1.var1;
Class.var2;
}
Second way using getter.
public Class1 extends Activity{
int var1 =10;
int var2 =20;
public int getVar1() {
return var1;
}
public int getVar2() {
return var2;
}
}
Now you can get the variable value in Class2
public Class2 extends ImageView {
Class1 class1= new Class1();
class1.getVar1;
class1.getVar2;
}
Also you can use SharedPreference. Hope it can help you. Thanks.
Various options exist:
The Activity can pass the information to Class B:
class B {
public void tellMeInformat(int usefulNumber) {
// Do something
}
}
Or, you can pass the Activity to the ImageView:
class A {
initiation {
B mySpecialImageView = /* Set it upo */;
B.setParentActivity(this);
}
}
class B {
private myA = null;
public void setParentActiviy {
myA = A;
}
private void doSomething {
int usefulNumber = A.getUsefulNumbner();
// Do something
}
}

How can I access views of an activity from a non activity class?

I am trying of access a view from a non activity class, but I am not sure how to do it
After looking at some other sources, I understand I must pass the Context like this
public Manager(Context c) {
context = c;
}
but when I try c.findViewById() it doesnt work. How do you do this?
Try this
public Manager(Activity a) {
Activity = a;
}
then do
a.findViewById
If you make your view a public static variable, you can access it from anywhere in your application.
for example:
In your Activity class, use
public static TextView mTextView = null;
In its onCreate(), initialize the TextView.
Now from any other class, you can always use:
myActivity.mTextView
to access the TextView

How to send the events to activity from other class?

I am trying to send the events from one Java class to Activity.
Scenario is, Will be having some data in the native, native will call the callback function which is in java code, This class processes data, after the processing i need to update the UI. I want to update the UI at one place in the Activity handler. (Dont want to use runOnUiThread() everywhere).
I was not able to send the events properly with the below approaches.
1st Approach:
1) Define functions for posting messages in to the queue and call these functions.
2) To call the above mentioned functions (point 1) we need context, if i maintain the static variable for maintaining the context and returning it, if the activity is created twice we wont able to get the write context for the first activity.
public class Activity1 {
protected static Context myContext = null;
protected Handler myHandler = null;
#override
public void onCreate() {
myContext = this;
myHandler = new Handler();
}
public static Context getMyContext() {
return myContext;
}
public void postEvent1() {
myHandler.sendMessage();
}
}
2nd Approach:
1) Making the handler as a static variable and returning this with the help of static function. - Not a good design to expose the internal variables.
2) Cons will be like above, when a second activity is created.
public class Activity1 {
protected static Handler myHandler = null;
#override
public void onCreate() {
myHandler = new Handler();
}
public static Context getMyHandler() {
return myHandler;
}
}
Is it possible to get the activity context without using the static variables and static functions?
Please share the knowledge if anyone knows. :)
Thanks & Regards,
SSuman185
I used a container class HashMap for storing the contexts with the key.
I used the name of the class as the key.
When the second activity is trying to register with class containing hashmap, it will reply with context of the already stored activity (null if not).
So like this I am able to store the contexts' of the classes and avoid loosing of the first activity context if I am creating the second one.
Please add if any one gets better solution.

Having difficulty with a global variable in android application

Hey I am having trouble declaring, changing, and using a global variable. I tried the whole "make a class that extends your application and put variables there" thing but I'm not sure how to implement it. Here is my class with the variable in it.
public class MyApp extends Application {
public int listPos;
}
I then tried to access and change int listPos here.
public class Browse extends ListActivity{
MyApp app = ((MyApp)getApplicationContext());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] coffeeTypes = getResources().getStringArray(R.array.coffeeTypes);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listview, coffeeTypes));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
app.listPos = position;
startActivity(new Intent(Browse.this, CoffeeTypes.class));
}
});
}
}
Then I tried to access the variable in the following activity to determine the outcome of an if else statement
public class CoffeeTypes extends Activity{
MyApp app = ((MyApp)getApplicationContext());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(app.listPos == 0){
Toast.makeText(this, "WEEEEEEE!0", Toast.LENGTH_LONG).show();
}
else if(app.listPos == 1){
Toast.makeText(this, "RAWR!1", Toast.LENGTH_LONG).show();
Anyone have any idea what I am doing wrong?
You can use soorya's answer with some modifications. I would personally still use your myApp class but change listPos to static and access it that way. Doing it this way lets you use the Application class onCreate method to initialize values if needed (though it won't be needed in this example) or other Android methods.
public class MyApp extends Application {
public static int listPos;
}
//~~ Elsewhere:
MyApp.listPos = 5; //etc
But this isn't the best way to handle your type of problem.
You should be passing the list position information (or the id of the item clicked or however you are handling your data) via the Intent.
Instead of having a global variable to track this information, keep it local to just the Intent:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//app.listPos = position;
Intent intent = new Intent(Browse.this, CoffeeTypes.class);
intent.putExtra("position", position);
startActivity(intent);
//startActivity(new Intent(Browse.this, CoffeeTypes.class));
}
This passes the position data to the new Activity via the intent. In your CoffeeTypes Activity you should start with something along the following:
//in onCreate...
int incomingPosition = getIntent().getIntExtra("position",-1));
if(incomingPosition != -1) { //do stuff }
This will read the "position" data from the incoming Intent so you can use it. The -1 above is the default value if nothing is added.
One final warning: you might want to be careful sending the list position back and forth, depending on how your application is set up if new items are added/items are deleted the list position might no longer refer to the item you thought it did. If these coffee types/whatever you are using have a separate unique ID that might be more appropriate to avoiding the above situation, consider using that instead.
I'm not sure if it's a visibility issue with the android OS, are you able to make an public functions that may be able to act as getters for the variable?
int getListPos(){ return this.listpos; }
I know that you can pass variables between contexts, you may have to do that.
Perhaps a temporary workaround to get you moving could be creating a static class of accessible variables too?
Create a class like this
class globalClass
{
static int lastPos;
}
You can set values using
globalClass.lastPos = value;
and get function is
int myVal = globalClass.lastPos;
i do Application variable classes by making the variables private, and then create public get() and set() methods to change the variables. you can try that, but it seems like you are doing it right, technically
one reason why it might be going wrong is because you are implementing the stuff in onCreate and not onStartCommand. if you are testing this function with the wrong assumptions/knowledge of the Activity cycle, it could go wrong

Categories

Resources