I am quite a beginner and trying to access the instance variable of an object array in the child class but all I get is the initialized values instead of updated values. It is a little more complex but making it simple, the code can be put this way.
Seed.java
public class Seed {
int weight = 0;
}
Apple.java
public class Apple {
public Seed[] seed = new Seed[10];
}
MainActivity.java
Main Activity {
public static Apple[] apple = new Apple[2];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apple[0] = new Apple();
for (int i = 0; i < 10; i++)
apple[0].seed[i] = new seed();
assign();
//and here new activity childActivity starts
}
public void assign() {
for(int i =0; i < 10; i++)
apple[0].seed[i].weight = 10;
}
}
ChildActivity.java
ChildActivity extends mainActivity {
//display a layout with a button
//upon button click
display();
public void display() {
//output to textview
String.valueOf(apple[0].seed[0].weight);
}
gives me output of 0 instead of 10. I am not able to figure out whats wrong. I checked the values are being assigned properly in the mainActivity. I get no errors or crashes. Thanks for the help!
Related
I have two inner classes named CalculatorClass and UpdatePayment in MainActivity class.
In UpdatePayment class there is a for loop and I have a array of Buttons.
I want to add listener to each button in loop. Those buttons will initialize the CalculatorClass and get value of calculations.
Demo code is:
public static class MainActivity{
private interface UpdateEditText{
void onCallback(String s);
}
private class CalculatorClass extends Dialog{
UpdateEditText updateEditText;
public CalculatorInterface(#NonNull Context context, UpdateEditText updateEditText) {
super(context);
this.updateEditText = updateEditText;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
initialize();
}
initialize(){
.......................
s = "Some texts";
updateEditText.onCallback(s);
}
}
private class UpdatePayment extends Dialog{
private Button[] button = new Button[100];
private EditText[] editText = new EditText[100];
public CalculatorInterface(#NonNull Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update);
initialize();
}
initialize(){
.......................
for(int i = 0; i < MAXSize; i++){
button[i] = new Button(MainActivity.this);
editText[i] = new EditText(MainActivity.this);
//add buttons to view to layout
button[i].setOnclickListener(new View.OnClickListener(){
public void onClick(View v) {
CalculatorClass calculator = new
CalculatorClass(MainActivity.this,
new UpdateEditText() {
#Override
public void onCallback(String s) {
editText[i - 1].setText(s);
}
});
calculator.show();
}
);
}
}
}
}
Problem is the line editText[i].setText(s) work for the last editText what ever button I click, i.e, any button I click, it fills the editText[MaxSize -1]
What should I do?
How can I perform this action for all i?
Please help me, I tried a lot searching in internet, still I didn't get any solution.
Anonymous classes are very much treated like static variables in java.It's happenning because your i value after your activity is initialized is equal to 1 less than the length of the edit text array.
editText[indicies_of_button_clicke].setText(s)
How you will get the indicies of button clicked is by :
se the tag to button below this line "editText[i] = new EditText(MainActivity.this);", like this :
button[i].setTag(i)
to retreive the index of your actual button clicked inside button clicklisteners,
v.getTag()// this will give you an integer value which will be the indices of actual button clicked
//use this value to set your edit text value.
Solution:
After a whole night, I got answer, now I feel awwww, this was easy go!
I never came in this thought.
button[i].setId(i);
then call:
CalculatorClass calculator = new CalculatorClass(MainActivity.this, v.getId(),
new UpdateEditText() {
#Override
public void onUpdate(String s, int ID) {
Log.i("test", ID + "");
editText[ID].setText(s);
}
});
At the same time, #Rishabh Ritweek answered correctly.
Thanks to him.
in java when we use for loop and make new object from class constractor method of class is run 5 times for example:
for (int x=0; x<5; x++) {c1 = new CountTest();}
in android it is not work correctly!!!
this is the code:
package com.hamid.counttestapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView=(TextView)findViewById(R.id.textview);
textView.setText(Integer.toString(Counter()));
}
public int Counter()
{
CountTest c1 = new CountTest();
for (int x=0; x<5; x++) {
c1 = new CountTest();
}
return c1.getInstanceCount();
}
class CountTest
{
private int instanceCount = 0;
public CountTest()
{
instanceCount++;
}
public int getInstanceCount()
{
return instanceCount;
}
}
}
the constractor should run 4 times and value of instanceCount shoulde be 4.
but number 4 not see in the textview.
textview show number: 1
it means constractor not run 5 times correctly.
whats wrong..?
The constructor is executed 5 times, and 5 CountTest instances are created.
However, since instanceCount is an instance variable, each of the 5 instances of CountTest class has a different copy of that variable. All of them are initialized to 0 and then incremented to 1.
If you make it a static variable, you'll get your expected output. All the instance of the CountTest class would update the same variable.
Change
private int instanceCount = 0;
to
private static int instanceCount = 0;
I am pretty new at android/java development and I am trying to process onClick events in an array of view from a "library" class but I can't figure out how it should work.
What I have so far is :
For the library :
public class WordArea {
private ImageView[] imageViewArray;
public boolean createWordTemplate(Activity myActivity, int layoutId, int numberOfLetters, int[] imageArray) {
imageViewArray = new ImageView[10];
// .....
for (int i = 0; i < 10; i++) {
// ...
imageViewArray[i].setClickable(true);
layout.addView(imageViewArray[i], params);
imageViewArray[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thisIsWhereIwouldLikeTheCallbackToWork( v );
}
});
Then in my activity class I am defining objects like this :
private WordArea myWordArea = new WordArea();
And I would like to define in the activity class the method to be called by the setOnClickListener
Can anyone please help me with the code I should put in the library and in the activity class to make it work ?
I'm struggling to figure out why I can't pass an int value from one activity to another. The app will ask you to press a button to generate a random number from 1-100 which will be displayed below the button. There is also another button which will open a new activity simply showing the random number that was rolled... but I just get 0.
I've looked into similar questions asked but to no avail.
Here's my code from MainActivity
public class MainActivity extends ActionBarActivity {
int n;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ButtonRoll(View view) {
TextView textRoll = (TextView) findViewById(R.id.textview_roll);
Random rand = new Random();
n = rand.nextInt(100) + 1;
String roll = String.valueOf(n);
textRoll.setText("Random number is " + roll);
}
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
startActivity(getStats);
}
public int GetNumber (){ return n; }
}
Heres my 2nd class.
public class Stats extends Activity {
MainActivity statistics = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = statistics.GetNumber();
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
}
Is using getters the wrong way to get data from another class when using activities? Thanks for your time.
You should pass your data as an extra attached to your intent. To do this you need to first determine a global key to be used. You could do something like this in your MainActivity
public static final String SOME_KEY = "some_key";
then modify your OpenStats method to
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
getStats.putExtra(SOME_KEY, n);
startActivity(getStats);
}
and then in Stats.class onCreate method
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = getIntent().getIntExtra(MainActivity.SOME_KEY, -1);
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
You obviously should make sure that you are calling ButtonRoll at least once or that you set n so that you aren't passing a null int.
Also, as note, convention states that methods should use lower camel case formatting. That is, the first word is completely lower case and the first letter of subsequent words is upper case. That would change your methods
OpenStats() -> openStats()
ButtonRoll() -> buttonRoll()
Classes/objects are upper camel case, just to help avoid confusion.
i create preference screens dynamically according to my dynamic array. this is done in a for loop. to every screen objects, i add onclick listeners. but first one is only working. what is the problem?
here my code.
MenuActivity.java
public static ArrayList<Details> device_list;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
createPreference();
}
private void createPreference() {
devicePref = (PreferenceScreen)getPreferenceScreen().findPreference("Manage Devices");
devicePref.removeAll();
if (MainActivity.device_list.size()!=0) {
for (int i = 0; i < MainActivity.device_list.size(); i++) {
PreferenceScreen screen= getPreferenceManager().createPreferenceScreen(this);
screen.setTitle(device_list.get(i).getName());
screen.setKey(device_list.get(i).getCust_id());
screen.setSummary(.device_list.get(i).getNic()+" "+device_list.get(i).getNumber());
screen.setOnPreferenceClickListener(new DevicePreferenceListner());
devicePref.addPreference(screen);
}
}else {
Toast.makeText(MenuActivity.this, "There is No any users", Toast.LENGTH_LONG).show();
}
}
private class DevicePreferenceListner implements OnPreferenceClickListener{
#Override
public boolean onPreferenceClick(Preference preference) {
//do some stuff....
return true;
}
}
when i run this it creates preference screens according to device_list array elements. but onclick listener work only for first screen. what i did wrong?
thank you.
In your case, only one object of PreferenceScreen exists. You should use a list of PreferenceScreen:
List <PreferenceScreen> prefScreens = new ArrayList<PreferenceScreen> ();
for (int i = 0; i < MainActivity.device_list.size(); i++)
{
prefScreens.add(new PreferenceScreen(getPreferenceManager().createPreferenceScreen(this)));
prefScreens.get(i).setOnPreferenceClickListener(new DevicePreferenceListner());
}