I am trying to create something like that: After clicking a button, the program should show four random numbers ( between 1 and 9), but with some particularities. Together and after a set of conditions (operations), the final result is 22. I had already written the code, but I think it is too big for the usage, and there are some little things I wanted to change. For example, instead of clicking the button several times until the right set of numbers appear, I would like it to automatically show those four "magic" numbers in the first click. I have no idea how to do it:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void button_action (View v){ int TF = 22;
Random a = new Random();
int i1 = a.nextInt(10 - 1) + 1;
TextView tv = (TextView) findViewById(R.id.textView1);
Random b = new Random();
int i2 = b.nextInt(10-1)+1;
TextView tv2 = (TextView) findViewById(R.id.textView2);
Random c = new Random();
int i3 = c.nextInt(10-1)+1;
TextView tv3 = (TextView) findViewById(R.id.textView3);
Random d = new Random();
int i4 = d.nextInt(10-1)+1;
TextView tv4 = (TextView) findViewById(R.id.textView4);
int soma = i1 + i2 + i3 + i4;
int mult0 = i1 * i2 * i3 * i4;
int mult1 = (i1*i2*i3)+i4;
int mult2 = (i1*i2)+i3+i4;
int mult3 = i1 * (i2 + i3 + i4);
int mult4 = i2 * (i1+i3+i4);
int mult5 = i3 * (i1+i2+i4);
int mult6 = i4 * (i1+i2+i3);
int mult7 = (i1*i3)+i2+i4;
int mult8 = (i1*i4)+i2+i3;
int mult9 = (i2*i3)+i1+i4;
int mult10 = (i2*i4)+i1+i3;
int mult11 = (i4*i3)+i1+i2;
int mult12 = (i1*i3*i4)+i2;
int mult13 = (i1*i2*i4)+i3;
int mult14 = (i4*i2*i3)+i1;
if (soma == TF){
tv.setText(String.valueOf(i1));
tv2.setText(String.valueOf(i2));
tv3.setText(String.valueOf(i3));
tv4.setText(String.valueOf(i4));}
if (mult0 == TF){
tv.setText(String.valueOf(i1));
tv2.setText(String.valueOf(i2));
tv3.setText(String.valueOf(i3));
tv4.setText(String.valueOf(i4));}
if (mult1 == TF){
tv.setText(String.valueOf(i1));
tv2.setText(String.valueOf(i2));
tv3.setText(String.valueOf(i3));
tv4.setText(String.valueOf(i4));}
if (mult2 == TF){
tv.setText(String.valueOf(i1));
tv2.setText(String.valueOf(i2));
tv3.setText(String.valueOf(i3));
tv4.setText(String.valueOf(i4));}
if (mult3 == TF){
tv.setText(String.valueOf(i1));
tv2.setText(String.valueOf(i2));
tv3.setText(String.valueOf(i3));
tv4.setText(String.valueOf(i4));}
if (mult4 == TF){
tv.setText(String.valueOf(i1));
tv2.setText(String.valueOf(i2));
tv3.setText(String.valueOf(i3));
tv4.setText(String.valueOf(i4));} ... }
}
Any suggestions?
Related
The error I'm getting :
Process: com.example.numerology, PID: 4012
java.lang.ArrayIndexOutOfBoundsException: length=14; index=14
at com.example.numerology.MainActivity$3.onClick(MainActivity.java:90)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
My code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e1 = findViewById(R.id.name);
final EditText e2 = findViewById(R.id.date);
final EditText e3 = findViewById(R.id.month);
final EditText e4 = findViewById(R.id.year);
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
char[] n = e1.getText().toString().toCharArray();
int date = Integer.parseInt(e2.getText().toString());
int month = Integer.parseInt(e3.getText().toString());
int year = Integer.parseInt(e4.getText().toString());
int nn = 0;
int driver = date, conductor = date + month + year;
int temp, k = 0;
Intent i1 = new Intent(MainActivity.this, Main2Activity.class);
i1.putExtra("NN", nn);
i1.putExtra("Driver", driver);
i1.putExtra("Conductor", conductor);
startActivity(i1);
}
});
This is the major part of the code I'm using, I think the problem is related to the character array.
This is how I'm using the char array:
if (n[i] == 'f' || n[i] == 'F' || n[i] == 'p' || n[i] == 'P') {
nn += 8;
}
So this activity does pop up on the screen but when I press the button to jump to the next activity the app crashes leaving the error I specified above.
Gonna need some help fixing this, Thank you.
Array indexes start from 0 and end at length-1. Your code below is accessing it wrong as you are using <= with length, thus your last access for i will be length and not length-1. So change your loop
for (i = 1; i <= e1.getText().toString().length(); i++)
to
int len = e1.getText().toString().length();
for (i = 0; i < len ; i++)
I am trying to create an app that requires a login. Just to test to see how it works, I made a login button to go to a separate layout where you press a button to randomize numbers. The login button works fine and it brings me to another layout, but it is when I click the button on the separate layout that my app crashes.
here is my code:
private TextView R1;
private TextView R2;
private TextView R3;
private TextView R4;
private TextView R5;
private TextView R6;
private Animation R1_roll_rotate;
private Animation R2_roll_rotate;
private Animation R3_roll_rotate;
private Animation R4_roll_rotate;
private Animation R5_roll_rotate;
private Animation R6_roll_rotate;
private Button Randomize_Button;
private Animation Button_Rotate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Randomize_Button= (Button) findViewById(R.id.Randomize);
R1= (TextView) findViewById(R.id.RandomOne);
R2= (TextView) findViewById(R.id.RandomTwo);
R3= (TextView) findViewById(R.id.RandomThree);
R4= (TextView) findViewById(R.id.RandomFour);
R5= (TextView) findViewById(R.id.RandomFive);
R6= (TextView) findViewById(R.id.RandomSix);
Button_Rotate= AnimationUtils.loadAnimation(Main_Activity.this, R.anim.Button_Rotate);
R1_roll_rotate = AnimationUtils.loadAnimation(Main_Activity.this, R.anim.RandomOne_roll_rotate);
R2_roll_rotate = AnimationUtils.loadAnimation(Main_Activity.this, R.anim.RandomTwo_roll_rotate);
R3_roll_rotate = AnimationUtils.loadAnimation(Main_Activity.this, R.anim.RandomThree_roll_rotate);
R4_roll_rotate = AnimationUtils.loadAnimation(Main_Activity.this, R.anim.RandomFour_roll_rotate);
R5_roll_rotate = AnimationUtils.loadAnimation(Main_Activity.this, R.anim.RandomFive_roll_rotate);
R6_roll_rotate = AnimationUtils.loadAnimation(Main_Activity.this, R.anim.RandomSix_roll_rotate);
public void onClick(View view) {
int randomnum1 = r.nextInt(70);
int randomnum2 = r.nextInt(70);
int randomnum3 = r.nextInt(70);
int randomnum4 = r.nextInt(70);
int randomnum5 = r.nextInt(70);
int randomnum6 = r.nextInt(27);
int num1 = randomnum1;
int num2 = randomnum2;
int num3 = randomnum3;
int num4 = randomnum4;
int num5 = randomnum5;
int num6 = randomnum6;
String randomnum7 = String.valueOf(randomnum1);
String randomnum8 = String.valueOf(randomnum2);
String randomnum9 = String.valueOf(randomnum3);
String randomnum10 = String.valueOf(randomnum4);
String randomnum11 = String.valueOf(randomnum5);
String randomnum12 = String.valueOf(randomnum6);
try {
Randomize_Button.startAnimation(Button_Rotate);
R1.startAnimation(R1_roll_rotate);
R2.startAnimation(R2_roll_rotate);
R3.startAnimation(R3_roll_rotate);
R4.startAnimation(R4_roll_rotate);
R5.startAnimation(R5_roll_rotate);
R6.startAnimation(R6_roll_rotate);*/
for (int i = num1; i > 0 && i == num1; i++) {
String ii = Integer.toString(i);
R1.setText(ii);
}
for (int j = num2; j > 0 && j == num2; j++) {
String jj = Integer.toString(j);
R2.setText(jj);
}
for (int k = num3; k > 0 && k == num3; k++) {
String kk = Integer.toString(k);
R3.setText(kk);
}
for (int d = num4; d > 0 && d == num4; d++) {
String dd = Integer.toString(d);
R4.setText(dd);
}
for (int s = num5; s > 0 && s == num5; s++) {
String ss = Integer.toString(s);
R5.setText(ss);
}
for (int g = num6; g > 0 && g == num6; g++) {
String gg = Integer.toString(g);
R6.setText(gg);
}
for (int g = num1; g == num2; g++) {
g = r.nextInt(70);
String gg = Integer.toString(g);
R1.setText(gg);
}
for (int d = num1; d == num3; d++) {
d = r.nextInt(70);
String dd = Integer.toString(d);
R1.setText(dd);
}
for (int a = num1; a == num3; a++) {
a = r.nextInt(70);
String aa = Integer.toString(a);
R1.setText(aa);
}
for (int w = num1; w == num4; w++) {
w = r.nextInt(70);
String ww = Integer.toString(w);
R1.setText(ww);
}
for (int q = num1; q == num5; q++) {
q = r.nextInt(70);
String qq = Integer.toString(q);
R1.setText(qq);
}
for (int y = num2; y == num3; y++) {
y = r.nextInt(70);
String yy = Integer.toString(y);
R2.setText(yy);
}
for (int o = num2; o == num4; o++) {
o = r.nextInt(70);
String oo = Integer.toString(o);
R2.setText(oo);
}
for (int p = num2; p == num5; p++) {
p = r.nextInt(70);
String pp = Integer.toString(p);
R2.setText(pp);
}
for (int x = num3; x == num4; x++) {
x = r.nextInt(70);
String xx = Integer.toString(x);
R3.setText(xx);
}
for (int c = num3; c == num5; c++) {
c = r.nextInt(70);
String cc = Integer.toString(c);
R3.setText(cc);
}
for (int b = num4; b == num5; b++) {
b = r.nextInt(70);
String bb = Integer.toString(b);
R4.setText(bb);
}
} catch (Exception e){
Toast.makeText(Main_Activity.this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Does anyone know why? If so, your help would be deeply appreciated! Thanks.
The possible reason what I can figure out reading your question is most probably you would have forgot the add the button in your another layout.
Since, the Button View would be null in this case so once you click, it would throw NullPointerException like this
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setEnabled(boolean)' on a null object reference
First of all check in your another layout whether the button view is added or not.
Then in Activity class check whether button view that you have initialized using the correct id which should match against the xml one.
These could be the reason for the crash you encountered.
Hope this helps.
Add a try-catch block in button click like..
try{
//Your Code for randomize number.
}
catch(Exception e)
{
Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show();
}
This will show exception in toast and your app won't crash.
What I want is that by default C is 0 but when the user adds 2 then it should display 2 and then when the user adds 4 it should be 6 but instead it displays 4
Any help would be appreciated!
public void addCash(View view) {
//Intent intent = new Intent(this, Main.class);
EditText val1 = (EditText) findViewById(R.id.num);
int b = 0;
int a = 0;
int c = 0;
int d = 0;
a = Integer.parseInt(val1.getText().toString());
if (c == 0) {
c = a + b;
}
else {
c = c + a;
}
TextView result = (TextView) findViewById(R.id.outPut);
result.setText(""+c);
//startActivity(intent);
}
variable c is local to this function and every time function is called it initialize c = 0 .
So every time only if condition will run.
else condition will never executed.
you can declare c as global ....
Initialize your variable c with the value of the textview like this:
TextView result = (TextView) findViewById(R.id.outPut);
int c = Integer.parseInt(val1.getText().toString());
Edit: if the TextView by default is not set to 0 then you should consider doing an additional check.
Initialize "c" as a global member variable of your activity.Because instance of this will remain throughout the activity whereas if you initialize it as local vairable every time when you call method new variable instance is created
This as the global instance inside your activity
private int c = 0;
These "a",b","d" be initialzed again and again when call addcash method
public void addCash(View view) {
//Intent intent = new Intent(this, Main.class);
EditText val1 = (EditText) findViewById(R.id.num);
int b = 0;
int a = 0;
int d = 0;
a = Integer.parseInt(val1.getText().toString());
if (c == 0) {
c = a + b;
}
else {
c = c + a;
}
TextView result = (TextView) findViewById(R.id.outPut);
result.setText(""+c);
Also replace below line of code with c = c + a as "b" will be always zero according to your code
if (c == 0)
{
c = a + b;
}
For more information check this link
http://www.cafeaulait.org/course/week3/11.html
As the other answers already stated, you are using local variables, which are initialized at each method call.
class SomeActivity {
private int c = 3; // Instance variable being initialized to 3. When you
// leave out the "= 3" part, then it is initialized
// to 0.
public void addCash(View v) {
// Now if you add something to c, it will persist between multiple
// method calls
EditText inputField = (EditText) findViewById(R.id.num);
EditText outputField = (TextView) findViewById(R.id.outPut);
c += Integer.parseInt(inputField.getText().toString());
outputField.setText(String.valueOf(c));
}
}
I'm new to android and I am currently having this problem on onClick():
I have dynamically created textViews within a TableLayout() and each textviews have onClickListener. The code is like this:
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor("#c04485ed"));
String a = view.getTag().toString();
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
if(uTxt.length() == 4){
if(checkAns(uTxt, list)){
Log.e("OUTPUT: " , uTxt.getText().toString().toLowerCase() + " IS ON THE ARRAY!");
}
else if (!checkAns(uTxt, list))
{
Log.e("OUTPUT: " , uTxt.getText().toString() + " IS NOT ON THE ARRAY!");
}
}
}
});
I also initialized a method called checkAns() and it goes like this:
private boolean checkAns(TextView uTxt, List<String> list) {
String word = uTxt.getText().toString().toLowerCase();
if (list.contains(word)) {
return true;
}
else {
return false;
}
}
The purpose of that method is to catch the created word and check if the formed word is on the array.
But that method always returns false. Is there anything wrong with my logic?
Any help, comments, and suggestions are welcome. :)
EDIT:
#k3b ask me where the list is populated. So here is the full code of the textView grid that i created:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TableLayout table = (TableLayout) findViewById(R.id.mainLayout);
table.setTag(1);
final Typeface font = Typeface.createFromAsset(getAssets(), "kg.ttf");
final Typeface font2 = Typeface.createFromAsset(getAssets(), "futura.ttf");
final String[] wordArray = new String[Category.size];
final TextView uTxt = (TextView)findViewById(R.id.userTxt);
for(int i = 0; i < Category.size; i++){
wordArray[i] = listahan[i];
}
final List<String> list = Arrays.asList(wordArray);
for (int i = 0; i < input.length; i++) {
final LinearLayout rowLayout = new LinearLayout(this);
rowLayout.setOrientation(LinearLayout.HORIZONTAL);
rowLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
final TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.setTag(i);
int k = 0;
for (int j = 0; j < input.length; j++) {
final TextView text = new TextView(this);
Character temp = input[i][j];
text.setText(temp.toString());
text.setPadding(20, 20, 20, 20);
text.setTag(i + " " + j);
text.setTextSize(txtSize);
text.setTypeface(font);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor("#c04485ed"));
String a = view.getTag().toString();
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
if(uTxt.length() == 4){
if(checkAns(uTxt, list)){
Log.e("OUTPUT: " , uTxt.getText().toString().toLowerCase() + " IS ON THE ARRAY!");
}
else if (!checkAns(uTxt, list))
{
Log.e("OUTPUT: " , uTxt.getText().toString() + " IS NOT ON THE ARRAY!");
}
}
}
});
text.setGravity(Gravity.CENTER);
row.addView(text);
}
Thanks for all the help guys. I managed to fix the error. It seems that the code that initialized my array of words is not properly coded! Thanks guys!
I'm making an application, in this application I need the width and height of the display device. Initially I made a calculation of the width and height in one class and then instantly displayed. But to make it look more organized, I separate them in a separate class. This code in the class:
public class DisplayMeasurement extends Activity{
public int widthScreen = 0;
public int heightScreen = 0;
#SuppressWarnings("deprecation")
public void DisplayHeightWidthMeasurement(){
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2){
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
//int sepertiga = Measuredwidth/3;
//akhir ngukur layar
set(Measuredwidth,Measuredheight);
}
public void set(int Measuredwidth, int Measureheight){
this.widthScreen = Measuredwidth;
this.heightScreen = Measureheight;
}
public int getWidthScreen(){
return widthScreen;
}
public int getHeightScreen(){
return heightScreen;
}
}
then this is a piece of code on mainActivity:
DisplayMeasurement screenValue = new DisplayMeasurement();
int WidthScreen = screenValue.getWidthScreen();
int HeightScreen = screenValue.getHeightScreen();
TextView text1 = (TextView) findViewById(R.id.text1);
TextView text2 = (TextView) findViewById(R.id.text2);
text1.setText("lebar" + WidthScreen);
text2.setText("tinggi" + HeightScreen);
But that I get is the value 0. Is there anyone who has experienced the same thing, or are there who know about this problem.
Sorry, I'm kind of new to Android but I'll give it a go.
I'm not sure why you're trying to organise code by creating a new Activity which seems to over-complicate things.
public class DisplayMeasurement {
public int widthScreen = 0;
public int heightScreen = 0;
public void DisplayMeasurement(Context context){
Point size = new Point();
WindowManager w = (WindowManager) mContext.getSystemService(mContext.WINDOW_SERVICE);
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2){
w.getDefaultDisplay().getSize(size);
widthScreen = size.x;
heightScreen = size.y;
} else {
Display d = w.getDefaultDisplay();
widthScreen = d.getWidth();
heightScreen = d.getHeight();
}
}
public int getWidthScreen(){
return widthScreen;
}
public int getHeightScreen(){
return heightScreen;
}
}
And then in your main activity;
DisplayMeasurement screenValue = new DisplayMeasurement(this);
int WidthScreen = screenValue.getWidthScreen();
int HeightScreen = screenValue.getHeightScreen();
TextView text1 = (TextView) findViewById(R.id.text1);
TextView text2 = (TextView) findViewById(R.id.text2);
text1.setText("lebar" + WidthScreen);
text2.setText("tinggi" + HeightScreen);
Not sure if it will work though, haven't tested it.
Also, I'm not sure why (have been only coding for 6 months) - but how is DisplayHeightWidthMeasurement() meant to be ever called, when you never call for it. All you do is:
DisplayMeasurement screenValue = new DisplayMeasurement();
and so your method: DisplayHeightWidthMeasurement, which actually has the logic to get the width and height is never called. You would need to call that first, otherwise it would just return 0, which is what you initialised.
You never call the function DisplayHeightWidthMeasurement() so the method in it set() is not called yet, so the values of height and width are zero just as you set, just as #TheIT said it is not a good way to instantiate an Activity, you can just define a Class that get the width and height of the diplay rather than use an Activity.