why constractor of java class not work on android? - java

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;

Related

I tried using a handler, but it said 'cannot resolve symbol"Handler"'

What do i do to be able to use a handler to update my TextView every 2 secs because right now it comes up with 'cannot resolve symbol"Handler"'
int noStart = 20;
int minus = 5;
public void number(View view) {
final TextView tx = (TextView) findViewById(R.id.number);
if(noStart<0){
new Handler().postDelayed(new Runnable() {
public void run() {
noStart -= minus;
tx.setText(String.valueOf(noStart));
}
}, 2000);
}
}
Check your activity imports and add this line to the class:
import android.os.*
In my case, i refer to a constant of class Handler in outer calss, see as below:
import static *.MyHandler.MSG_WHAT_PING_NETWORK;
public class OuterClass {
// use MSG_WHAT_PING_NETWORK...
// ...
}
class MyHandler extends Handler {
public static final int MSG_WHAT_PING_NETWORK = 99;
// ...
}
remove the import in outer class can solve the problem.

Why Can't i update a variable of class from another class in android(Java)?

I want to update this num variable from different classes through this Methods .
but it show '0' when i display it
public class ResultNum extends AppCompatActivity{
private int num;
public int ResultNum1(){
return num;
}
public void yesMethod(int i){
num = i+num;
}
Here is Another class
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.yesMethod(2);
}
});
and also I've some other classes as well which passes different numbers
here's code for displaying number
TextView t = (TextView) findViewById(R.id.text_number);
int x = result.ResultNum1();
t.setText(""+x);
i also tried
TextView t = (TextView) findViewById(R.id.text_number);
t.setText(""+result.ResultNum1());
so What exactly i need to do now?
As already stated, you should either declare int num as static or make sure that all your methods across application use the same instance of ResultNum class.

Simple Encrypt Decrypt String with array in Android

My problem seems easy, I am trying to encrypt a string in android.
What the program should do
The objective of the program is, put a word or a letter in textbox1, click on button encrypt and textbox2 should to show the symbol in the same position in second array of the letter that you put in.
For example I write letter A (array 1 [0]) must show symbol $ (array 2 [0]) if a click on ENCRYPT button, if I put a symbol and click on DECRYPT must show the letter which is equivalent in position of array
Need help. Sorry for grammar and edit question, first time and no English speaker, i tried to make it more simple.
Arreglo Class, just for declare 2 arrays.
package PaqueteArreglo;
public class Arreglo {
public String [] encrypt = new String[3];
public String [] decrypt = new String[3];
}
Main Activity
package com.example.encrypt;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import PaqueteArreglo.Arreglo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
//Instance the class with the arrays
PaqueteArreglo.Arreglo ins = new Arreglo();
public Button button1,button2;
public EditText text1, text2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
ins.encrypt[0] = "a";
ins.encrypt[1] = "b";
ins.encrypt[2] = "c";
ins.decrypt[0] = "$";
ins.decrypt[1] = "%";
ins.decrypt[2] = "&";
}
private void initialize(){
text1 = (EditText)findViewById(R.id.txtWord);
text2 = (EditText)findViewById(R.id.txtResult);
button1 = (Button)findViewById(R.id.btnEncrypt);
button1.setOnClickListener(this);
button2 =(Button)findViewById(R.id.btnDecrypt);
button2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String word = String.valueOf(this.text1.getText());
if (view.getId() == R.id.btnEncrypt)
{
String demo = "";
int lon = 0;
lon = word.length();
for (int i = 0; i < lon; i++ )
{
if (ins.encrypt[i].equalsIgnoreCase(String.valueOf(word.charAt(i))))
{
demo = demo + ins.decrypt[i];
text2.setText(demo);
}
}
}
}
}
There are two solutions to your problem using two different approach:
1- Using your defined structure (which is not optimized by the way) you need to put two nested loop for checking:
for (int i = 0; i < lon; i++ )
{
for(int j = 0; j<ins.encrypt.length;j++)
{
if (ins.encrypt[j].equalsIgnoreCase(String.valueOf(word.charAt(i))))
{
demo = demo + ins.decrypt[j];
}
}
}
text2.setText(demo);
2- Using much better data structure like HashMap:
Change your Arreglo to the following:
public class Arreglo {
public HashMap<Character, Character> encrypt = new HashMap<>();
public HashMap<Character, Character> decrypt = new HashMap<>();
}
Now change the way you add your data like:
ins.encrypt.put('a','#');
ins.decrypt.put('#','a');
...
and finally do the encryption like:
for (int i = 0; i < lon; i++ )
{
demo = demo + ins.encrypt.get(word.charAt(i));
}
text2.setText(demo);
The second implementation is more efficient

Android: Passing int value from one activity to another

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.

Java [Android] - accessing instance variable of an object array in child class

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!

Categories