I'm a novice programmer and I'm trying to learn Android coding using Eclipse.
This is my first time using StackOverflow.
Just for tutorial purposes, I want to make a simple Animal Encyclopedia.
So in my Home class, there are some buttons: "Dog", "Cat", "Bird", etc. When I click the button, it will bring me to the same layout but of course with different content.
So I created a class named AnimalData that holds the
ArrayList<Integer> to store R.drawable.xxx and ArrayList<String>
to store the text that I will put below the picture (like "Bulldog"
or "Husky")
Then I created a class named ChangeContent to set all those drawable
and text to the XML
But whenever I click the button, it results in Stopped Unexpectedly Error
Below are the shortened Home class, The "crash-maker" isn't here. I have checked the whole code line per line using Thread.sleep(2000), so if my app crashes before 2 second, the error is before the sleep() code and vice versa.
public class Home extends Activity implements OnClickListener{
Button dog, cat, bird;
AnimalData ad;
ChangeContent cc;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
//set the findViewById for all the buttons
//set onClickListener() to all the buttons
}
public void onClick(View v) {
switch (v.getId()){
case R.id.bDog:
drawable.add(R.drawable.xxx);
drawable.add(R.drawable.yyy);
title.add("Bulldog");
title.add("Husky");
break;
case R.id.Cat:
//same
break;
case R.id.bBird:
//same
break;
}
ad.setDrawable(drawable);
ad.setTitle(title);
Intent i = new Intent("animal.ChangeContent"); //from Manifest
startActivity(i);
}
}
The AnimalData is just a typical getter setter, so I will just skip the code for that
The error is right after ChangeContent started because even when I put the sleep() on the first line of constructor, it doesn't have any effect.
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private ArrayList<Integer> drawable;
private ArrayList<String> title;
public ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
Sorry for the long question, I tried to make it as short as possible
Can you guys help me figure the error out?
Thanks before
You are trying to get arraylist from intent, whereas you are not putting putStringArrayList and putIntegerArrayList methods.
putIntegerArrayListExtra(String name, ArrayList<Integer> value)
putStringArrayListExtra(String name, ArrayList<String> value)
so Change calling activity to following:
Intent i = new Intent(Home.this, ChangeContent.class); //from Manifest
i.putIntegerArrayListExtra("drawables", drawable);
i.putStringArrayListExtra("titles", titles);
startActivity(i);
and get data from intent in onCreate method by following methods:
getIntegerArrayListExtra, and getStringArrayListExtra
you also can do following by making contentChanged method to static, by this you wont need to do much changes in your application code, just do following:
public class ChangeContent extends Activity {
TextView title1, title2;
ImageView pic1, pic2;
private static ArrayList<Integer> drawable;
private static ArrayList<String> title;
public static ChangeContent(AnimalData data){
drawable = new ArrayList<Integer>();
title = new ArrayList<String>();
drawable = data.getDrawable();
title = data.getTitle();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animal_info);
//findViewById for the TextView and ImageView
//setText() for TextView and setImageResource() for ImageView
}
}
See the answer by RajaReddy P here:
https://stackoverflow.com/a/9937854
In the send class use:
Intent intent = new Intent(PhotoActivity.this,PhotoActivity1.class );
intent.putIntegerArrayListExtra("VALUES", image);
startActivity(cameraIntent);
.. and in the receiver class use:
Intent i = getIntent();
ArrayList<Integer> img = i.getIntegerArrayListExtra("VALUES");
Your approach is wrong -
public Home(){
ad = new AnimalData();
cc = new ChangeContent(ad);
drawable = new ArrayList<Integer>();
title = new ArrayList<String>()
}
ChangeContent is a Activity class so, you don't pass parameter like this.
Passsing class should be serializable and use it -
startActivity(new Intent(this, ChangeContent.class)
.putExtra("key", ad);
And in your ChangeContent class extract the class from Intent
So, change your code design and go ahead.
Best of luck.
Related
I am a new android programmer.
I have 4 activities: A B C D.
The order is A -> B -> C -> D -> A and A -> D using buttons.
I want to save data in ArrayList that is in activity D.
The problem is that when I move from D to A and come back to D, the data in the ArrayList didn't save.
Code for D activity here:
public class SchedulerActivity extends AppCompatActivity {
public String name = "";
public String number = "";
public String date = "";
public String hour = "";
public ArrayList<EventClass> scheduler = new ArrayList<>();
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scheduler);
Bundle extras = getIntent().getExtras();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SchedulerActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}
});
if (extras != null) {
String sender = extras.getString("sender");
if(sender.compareTo("Hours") == 0) {
name = extras.getString("name");
number = extras.getString("number");
date = extras.getString("date");
hour = extras.getString("hour");
Date real_date = new Date();
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
try {
real_date = formatter1.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
scheduler.add(new EventClass(real_date, name, number, "", hour));
for (EventClass event : scheduler){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final TextView t = new TextView(this);
t.setText(event.toString());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout.addView(t, params);
}
}
else{
for (EventClass event : scheduler){
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button btn = new Button(this);
final TextView t = new TextView(this);
t.setText(event.toString());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
linearLayout.addView(btn, params);
}
}
}
}
I want to change my ArrayList when C->D occurs and print it and when D->A occurs I just want to print it. I know that I can with SharedPreferences but for the first step, I want to do this with ArrayList.
What's the best way to do this?
Creating static objects is not a good approach. So you can use android activity stack in-place of using static Arraylist. Android activities are stored in the activity stack. Going back to a previous activity could mean two things.
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
Keep track of the activity stack. Whenever you start a new activity with an intent you can specify an intent flag like FLAG_ACTIVITY_REORDER_TO_FRONT or FLAG_ACTIVITY_PREVIOUS_IS_TOP. You can use this to shuffle between the activities in your application.
The scheduler is a non-static field in the SchedulerActivity which means that its existance is tied to the instance of the activity. When the activity instance is destroyed, and that might happen for example when the screen orientation is destroyed or you move to another activity, so are all its non-static fields. You can change that by adding a static keyword before your field:
public static ArrayList<EventClass> scheduler = new ArrayList<>();
Now, your field is tied to the class itself, not the instance, whitch means it wont be destroyed along with the instance. But it also means that it is shared between all instances and must be referenced with the class name outside of the class body:
EventClass event = SchedulerActivity.scheduler.get(0)
A good approach is saving your data in a local database, like Room. You need to save before go to new activity, and get it back on OnResume().
This class extends my main Activity.
public class Numbers extends MainActivity{
public ArrayList<ImageView> getNumbers () {
ArrayList<ImageView> numbers = new ArrayList<>();
ImageView one = (ImageView) findViewById(R.id.one);
numbers.add(one);
return numbers;
}
And I've done some digging but can figure out why my variable "one" is coming back null.
My MainActivity has a ContentView set.
This is the content of my onCreate in MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView start = (ImageView) findViewById(R.id.start);
sceneRoot = (ViewGroup) findViewById(R.id.scene_root);
questionView = findViewById(R.id.questionView);
startView = findViewById(R.id.startView);
gameOverView = findViewById(R.id.gameOver);
animSlide = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide);
animSlide.setAnimationListener(this);
animZoom = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_fade);
animZoom.setAnimationListener(this);
set.addTransition(new Fade())
.addTransition(new Slide(Gravity.RIGHT));
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getQuestion();
TransitionManager.beginDelayedTransition(sceneRoot, set);
startView.setVisibility(View.GONE);
questionView.setVisibility(View.VISIBLE);
}
});
}
public void getQuestion (){
time = (TextView) findViewById(R.id.timeBar);
time.startAnimation(animSlide);
}
I don't call getNumbers() until after start has been clicked and the animation has started.
public void onAnimationStart(Animation animation){
if(animation == animSlide) {
final Questions questions = new Questions();
Numbers n = new Numbers();
for (int i = 0; i < n.getNumbers().size(); i++) {
n.getNumbers().get(i).setVisibility(View.GONE);
n.getNumbersTen().get(i).setVisibility(View.GONE);
}
n.getNumbers().get(0).setVisibility(View.VISIBLE);
EDIT:
If anyone was wondering, I got it to work by extending the class as a Fragment instead of my MainActivity. Then I just used the fragment in my xml.
Because you extended an Activity class doesn't mean setContentView gets called for that class also. It will only do so if properly started and you call super.onCreate(bundle) from your own implementation of onCreate within Numbers
Basically, you should never new any Activity. It has no life-cycle, and therefore no content view, so findViewById just won't work.
Numbers n = new Numbers();
You could not extend anything and have a data-only class around your list of images.
public class Numbers {
private List<ImageView> numbers = new ArrayList<ImageView>();
public Numbers() {}
public void addNumber(ImageView v) { numbers.add(v); }
public List<ImageView> getNumbers() { return numbers; }
}
And from MainActivity you can find and add as you want.
Number n = new Numbers();
n.addNumber((ImageView) findViewById(R.id.one));
However, I don't know if that is useful, really...
Maybe a Fragment would serve a better purpose if you want a "sub-view" of your Activity, but it's hard to tell.
I am creating an android dictionary app with sounds... I have listview, when an item is selected, a new activity open, inside the new activity contains 4 textviews and an image button, the textviews function perfectly but the image button was not. The audio files are placed in raw folder. How can I put the specific sounds of an item that was clicked?
Here's the code:
MainActivityJava
public class MainActivity extends AppCompatActivity {
ListView lv;
SearchView sv;
String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
"kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
"dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
"idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};
int[] sounds= new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
ArrayAdapter<String> adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
sv = (SearchView) findViewById(R.id.searchView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tagword =tagalog[position];
String[] definition = getResources().getStringArray(R.array.definition);
final String definitionlabel = definition[position];
String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
final String cuyunodefinition = cuyuno[position];
String[] english = getResources().getStringArray(R.array.english);
final String englishdefinition = english[position];
Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
intent.putExtra("tagword", tagword);
intent.putExtra("definitionlabel", definitionlabel);
intent.putExtra("cuyunodefinition",cuyunodefinition);
intent.putExtra("englishdefinition", englishdefinition);
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
DefinitionActivity.java
public class DefinitionActivity extends AppCompatActivity {
MediaPlayer mp;
String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definition);
TextView wordtv = (TextView) findViewById(R.id.wordtv);
TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
TextView englishtv = (TextView) findViewById(R.id.englishtv);
ImageButton playbtn = (ImageButton) findViewById(R.id.playbtn);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
tagalogword = extras.getString("tagword");
wordtv.setText(tagalogword);
worddefinition = extras.getString("definitionlabel");
definitiontv.setText(worddefinition);
cuyunoword = extras.getString("cuyunodefinition");
cuyunotv.setText(cuyunoword);
englishword = extras.getString("englishdefinition");
englishtv.setText(englishword);
}
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
you can pass the raw id in the intent extra and play it on meadiaPlayer
What you want to accomplish is pretty simple.
you can ofcourse pass the id.
But I created this method for your case you can paste it in your activity or class and make a call to it. In my case, I put this method in a class that holds all the common functions, methods, strings, etc. The choice is yours :
public static void playDisSound(Context c, int soundID){
//Play short tune
MediaPlayer mediaPlayer = MediaPlayer.create(c, soundID);
mediaPlayer.setOnCompletionListener( new OnCompletionListener(){
#Override
public void onCompletion( MediaPlayer mp){
mp.release();
}
});
mediaPlayer.start();
}
And this is how to use it in your case :
Example I want to play an audio track from :
int[] sounds= new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
So I just do :
//TODO ~ pls. remember to define context inside "onCreate" as
//call this before "onCreate"
Context context;
//And do this inside "onCreate" :
context = getApplicationContext();
OR
context = MainActivity.this;
//Then here comes the solution, just make a call to the playDisSound method with the id , in this case the "sounds[postion_referencer_i]"
playDisSound(context, sounds[postion_referencer_i]);
//And now on the question of what your "position_referencer_i" would be .... it also depends on how you intend to pass the id.
Are your going to make a match between the position picked and the position of the sound. It depends on you. But I would have created a set of integers to signify which try I want to play and do a matching simple calculation between the position picked for the item clicked to arrive at the position_referencer_id.
//But simply : note that in your array if I want to play for example "R.raw.baliw" I would just call :
playDisSound(context, R.raw.baliw);
I hope this works perfectly for you. So if I elaborated too much. Do let me know if you may need to stream the sound so I would just paste/send you a very cool method I have been using here in an app am working.
//FINALLY PLS. Remember this : this method would play the sound alright but it wont hesitate to play the sound all over again if you repeat the process. So do remember to check if the sound did play and finished before allowing the user to repeat, if not it could lead to repeated or kind of two speakers playing from the same song but at different time. (And the user may start to think that there is problem with the app. Pls. be very logical and sensitive in using this method)
In solving that, you can disable the button or the UI element that initiates the sound playing until the sound has finished playing, by way of monitoring duration of the track (which I am sure you should know and inculcate into your logic or by simply listening if sound is already playing)
All the best. Era. :)
I've got 2 activities and a class that extends Application where I'm trying to store global variables with a kind of setter getter functions.
The main activity sets some views and a chart; then calls the second activity which should be setting values to be used afterwards on the previous chart.
Then pressing backbutton and returning to the previous activity onRestart is called and the chart is refreshed.
The problem is I lose my theorically global variables somewhere. Debugging i realized that the functions work perfectly fine while im adding values in the second activity but when I return to the first activity globalXCount returns '0' again. Why is that?
I think im missunderstanding some point regarding lifecycles.
I attach some fragments of the code.
First activity:
public class MainActivity extends Activity {
Global glObj = new Global();
CombinedChart mChart;
private int itemcount;
float displayed;
private final List<String> mMonthList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
mChart = (CombinedChart) findViewById(R.id.mchart);
populateHeaderList();
setChartSettings();
Intent intent = new Intent(MainActivity.this, QandA.class);
startActivity(intent);
}
#Override
protected void onRestart() {
super.onRestart();
itemcount = ((Global) this.getApplication()).getGlobalXCount();
displayed = itemcount/20;
populateHeaderList();
setChartSettings();
}
Second activity:
public class QandA extends Activity {
Global glObj = new Global();
ViewFlipper flipper;
private float lastX;
...
}else{
//TODO If all information if correctly filled
trainedmins = et1.getText().toString();
localLineValue = Integer.parseInt(trainedmins) * Integer.parseInt(statusQ1);
//Add values to lines
glObj.setLineXvalues(localLineValue);
// TODO Add new Bar value //
//Add 1 more value to count
glObj.addGlobalXCount();
}
...
Global class:
public class Global extends Application {
//TODO
public Integer globalXCount;
private List<Integer> lineXvalues = new ArrayList<>();
private List<Integer> barXvalues = new ArrayList<>();
//////
public Integer getGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
return this.globalXCount;
}else{
return this.globalXCount;
}
}
public void addGlobalXCount() {
if (this.globalXCount == null){
this.globalXCount = 0;
}else{
this.globalXCount = this.globalXCount + 1;
}
}
Thanks in advance.
First of all, register your custom Application context in AndroidManifest.xml within the <application>-tag.
<application
android:name="<your_package>.Global" ...>
Access the global application context within your activities like this:
Global glObj = (Global) getApplicationContext();
glObj.addGlobalXCount();
Do not create a new instance with new! Always retrieve the instance via getApplicationContext().
Furthermore, I would suggest you to initialize your class field glObj within the onCreate()-method of your Activities.
I have built a fortune cook app that previously currently has values hardcoded into an array
FortuneActivity.java
package juangallardo.emofortunecookie;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
package juangallardo.emofortunecookie;
import java.util.Random;
public class FortuneBox {
public String[] mFortunes = {
"What is the point?",
"Sometimes it is best to just sleep in.",
#98 other fortunes...
};
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
The problem is that now I want to add a Spanish version. So I realize that i should add that array into the strings.xml.
I looked up string resources on the Android developer page. and it gave me the idea to add this to my code
strings.xml
<string-array name="emo_fortunes">
<item>What is the point?</item>
<item>Sometimes it is best to just sleep in.</item>
</string-array>
But now I am stuck on where to add this part that has the part about Resources, etc.
I followed along to a tutorial from Treehouse about strings but my app kept crashing.
Basically the change that I made was to make the original array into
FortuneBox.java
# above unchanged from previous code
public String[] mFortunes;
# below unchanged from previous code
FortuneActivity.java
# same imports as before
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
Resources resources = getResources();
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
These were my errors, but not sure where to go from here as I am new to Android and I have not touched Java since college.
log
FortuneActivity.java
FortuneBox.java
Mikki has the right answer, but it is a little confusing. In your code above, you are using the same name for two different variables: mFortuneBox. This is the root of your trouble:
private FortuneBox mFortuneBox = new FortuneBox();
...
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Change the second one to a different name, like this, and the errors go away:
final String[] fortunes = resources.getStringArray(R.array.emo_fortunes);
However, you still aren't using these fortunes from the array anywhere. You can actually delete fortunes from your Activity and move it to your FortuneBox class instead. This is slightly tricky, though, as you need to know what the context is to get a string array resource in your other class. The context is the Activity, so you need to pass this along as a parameter when you create your FortuneBox object.
I'd recommend a slight restructuring. Below are the two files that should work for you:
FortuneActivity.java
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
mFortuneBox = new FortuneBox(this);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
public class FortuneBox {
public String[] mFortunes;
public FortuneBox(Context context) {
Resources resources = context.getResources();
mFortunes = resources.getStringArray(R.array.emo_fortunes);
}
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
Your problem is simple. You can not access a non-final from an inner class (in this case your OnClickListener).
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Try just changing the line to look like this one above.
Hope it helps.
The mFortuneBox variable in the previous way you have used is an object of FortuneBox class and hence this call mFortuneBox.getFortune() works.
In the later changed code, you have made mFortuneBox variable a reference to an Array of strings. But still tried calling mFortuneBox.getFortune(). 'getFortune()' is a method of FortuneBox class right, so you can call it with an object of Forune Box class itself.
Try doing this:
final String[] fortuneArray = resources.getStringArray(R.array.emo_fortunes);
and
private FortuneBox mFortuneBox = new FortuneBox();
Now call mFortuneBox.getFortune(fortunearray) sending it this array to the getfortune method.
Now let the getFortune() method randomly pick one from this array passed and return the random string picked