AIDE: No access to variable C and Understanding Default Code? - java

I am pretty new to this but I have a couple of questions which may seem silly but I would really appreciate an answer. They are located right below the code block.
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View.*;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new OnClickListener() {
public void onClick(View p1) {
((TextView)findViewById(R.id.txtview)).setText(getDiag(40));
}
});
Button c = (Button) findViewById(R.id.button2);
b.setOnClickListener(new OnClickListener() {
public void onClick(View p1) {
((TextView)findViewById(R.id.txtview)).setText(getDiag(5));
}
});
}
public String getDiag(int n){
String spaces = "";
String finalstring = "";
for(int i = 0; (i <= n); i++){
spaces += " ";
finalstring += spaces + "*" + "\n";
}
return finalstring;
}}
So, to be clear about what my questions are:
1) What is this whole default method created by AIDE? Is it always required or can I also just write my usual java and run my methods without all the UI?
2) I have a problem somewhere with brackets, everything works fine until I added button c. I have no idea where exactly to place it, with the current code AIDE tells me it has no acess to the variable c. And where is the ")" on line 25 coming from?

you can code it yourself, however you want
There is no access to Button c click because u made a small mistake:
Replace b into c at setOnClickListener:
Button c = (Button) findViewById(R.id.button2);
b.setOnClickListener(new OnClickListener() {
public void onClick(View p1) {
((TextView)findViewById(R.id.txtview)).setText(getDiag(5));
}
});
Should look like:
Button c = (Button) findViewById(R.id.button2);
c.setOnClickListener(new OnClickListener() {
public void onClick(View p1) {
((TextView)findViewById(R.id.txtview)).setText(getDiag(5));
}
});

To answer question 1:
The default structure provided is the methods that give the lifecycle of an Android Application. They are defined to provide the flow for your App.
You can use service to write your java code without UI.
You can modify your button placement in the AndroidManifest.xml and check that you indeed have a button2.
Can you also provide a more detailed error.
I cannot see your line 25 but if you are talking about the onclickListener it is the signature for an anonymous class/interface implementation.

Related

Android Studio: OnClickListener grayed out and won't implement

First time, long time. I have tried every which way to get the OnClickListener adapter work and every time I try to implement it is grayed out using the method below. It has been occurring across mulitple different projects.
'
btn_add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
}
});
'
Obviously, when I run the code it gives a nullpointerexception.
Using the code I've included below one listener, AddListener works and ViewAllListener does not. I get a nullpointerexception for the ViewAllListener again. I was following along with a tutorial and ran into the same problem. My work around was to use similar code to what I submitted below. It fixed it for that project, but now I'm having it in a completely different project. Except this time it is only with one listener and not the other. I'm stumped. For a different project I tried the " implements View.OnClickListener" attached after the extends AppCompatActivity. I still ran into the same problem with the OnClickListner grayed out and throwing a nullpointerexception when run. Any help would be greatly appreciated.
`
import androidx.appcompat.app.AppCompatActivity;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
Button btn_add_horse_ll, btn_viewAll_LL;
private final OnClickListener AddListener = new OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Success " + success, Toast.LENGTH_SHORT).show();
}
};
private final OnClickListener ViewAllListener = new OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dataBaseHelper = new DatabaseHelper(MainActivity.this);
ShowHorsesOnListView(dataBaseHelper);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_add_horse_ll = findViewById(R.id.btn_add_horse_ll);
btn_viewAll_LL = findViewById(R.id.btn_viewAll_LL);
btn_add_horse_ll.setOnClickListener(AddListener);
btn_viewAll_LL.setOnClickListener(ViewAllListener);
}
public OnClickListener getAddListener() {
return AddListener;
}
public OnClickListener getViewAllListener(){
return ViewAllListener;
}
`
Here's the xml:
`
<LinearLayout>
<Button android:id="#+id/btn_add_horse_ll"/>
</LinearLayout>
<LinearLayout>
<Button android:id="#+id/btn_viewAll_LL"/>
</LinearLayout>
`
I'm not sure what else to say or what other questions to ask, but it keeps telling me I have too much code. I have tried starting over from a new program and still end up with the same problem.
btn_add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
}
});
Where have you defined btn_add in your code ? That is what is causing the error

Why does my Android Quiz App crash when submitting the answer & do not print the questions?

My question is sort of double barrelled, I am developing a simple Quiz app using android studio. To me the code seems fine and there are no error messages being shown when I compile the app. However, when I run the app the Questions(strings) aren't displayed in the UI and when I hit the submit answer button the app just crashes. Below is a sample of the code I am implementing. Any help or advice will be greatly appreciated. Thank you
package com.example.shaun.quiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public int currentQuestion;
public String[] questions;
public String[] answers;
Button answerButton;
Button questionButton;
public TextView questionView;
public TextView answerView;
public EditText answerText;
public void main() {
questions = new String[]{"1+2= ?", "1+1= ?",}; /*Array of Hard Coded Questions*/
answers = new String[]{"3", "2",}; /*Array of Hard Coded Answers to indexed to match the questions*/
currentQuestion = -1; /*This will index the questions to be used*/
answerButton = (Button) findViewById(R.id.AnswerButton);
questionButton = (Button) findViewById(R.id.QuestionButton);
questionView = (TextView) findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
answerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer();
}
});
questionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showQuestion();
}
});
}
public void showQuestion() {
currentQuestion++;
if (currentQuestion == questions.length)
currentQuestion = 0;
questionView.setText(questions[currentQuestion]);
questionView.setText("");
answerText.setText("");
}
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(answers[currentQuestion]));
}
public void checkAnswer()
{
String answer = answerText.getText().toString();
if(isCorrect(answer))
answerView.setText("Correct!"); /*answerView, text view set to print the string in the event of the correct answer*/
else
answerView.setText("Sorry, the Correct answer is "+answers[currentQuestion]); /*answers[currentQuestion] answers reads the answer to the current question in use */
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main();
}
}
You never call the methods showQuestion() (unless from the button) so the index currentQuestion is still to -1 when the Activity is created.
So when you check the answers, you are trying to access answers[-1] leading to a ArrayIndexOutOfBoundsException. You should call showQuestion() at the end of main() to show the first question and incrementing the currentQuestion to be in the bounds of the array.
PS : And you should removed questionView.setText(""); in showQuestion() to show the text.
You are clearing questionView textview from showQuestion() method. This is the reason why the question is not display.
And because of question not shown in it, and whenever you try to select answer, it just puts a nullPointerException as the question related to the answer doesn't exist at all.

how to use java onclick shuffle array

I am learning how to use strings and onlclick in java. I have written a programme below which shuffle three names and then outputs them into three buttons.
When I click on Paul, I want the message to be displayed in message box. Since Paul will be in a button each time. I am puzzled on how to attach my message to Paul.
Paul moves around due to the use of array. I understand this is a tough question, but I also know, there are some very clever ppl out there who love a challenge.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void generate(View view) {
String [] names = new String[3];
names[0] = "Bob";
names[1] = "Paul";
names[2] = "Mike";
Button btn_a = (Button) findViewById(R.id.a);
Button btn_b = (Button) findViewById(R.id.b);
Button btn_c = (Button) findViewById(R.id.c);
TextView message = (TextView)findViewById(R.id.message);
Arrays.asList(names);
Collections.shuffle(Arrays.asList(names));
btn_a.setText(names[0]);
btn_b.setText(names[1]);
btn_c.setText(names[2]);
}
public void a1(View view) {
}
public void b1(View view) {
}
public void c1(View view) {
}
}
This is a trick practical implementation in Java where a single listener is used for multiple buttons, rather than one listener for each button, so that each button's content determines what happens, not each button's listener. Helps for dynamic button grids (i.e. an 8x8 chessboard) to not define 64 listeners and code them all.
I don't have an Android IDE on hand, so this is pseudo-code, but you should be able to get the gist from this.
//Create a Universal Listener for all our buttons
OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText().toString(); //get the button's name
if(text.equals("Paul")) {
//do anything for Paul ONLY in here
}
}
});
btn_a.setOnClickListener(listener); //give all the buttons the same listener, but only Paul's listener will do anything when you click on it
btn_b.setOnClickListener(listener);
btn_c.setOnClickListener(listener);
Using info from: http://developer.android.com/reference/android/widget/Button.html and https://stackoverflow.com/a/5620816/2958086

Android Layout fails to open

I have this code in one of the java file of my application.
public class Board_Play1 extends Activity {
int d,a=0,b=0,turn=2;
Random random = new Random();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.board_play1);
while(a!=100 && b!=100)
{
if(turn%2==0)
{
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
d=random.nextInt(6)+1;
EditText diceno = (EditText) findViewById(R.id.editText1);
diceno.setText(String.valueOf(d));
}
});
}turn++;
}
}
}
I come to this java file from another java file. All the problem I get is when this file doesn't have any while loop as in code it runs fine. But with including the while loop on navigating to this layout turns screen black and no further process can be done. If we press back button we have a pop out message saying Your application isn't responding. Do You want to close? Yes No.
Why is that happening. All things I included in while loop are perfect. What is causing for this problem?
I think you have an infinite loop. the condition in your while loop is always true because a and b values are never incremented.
And the reason why you're seeing black screen is that this infinite loop is blocking the Main UI Thread.
Seems that this is an infinite loop to me.
int a=0, b=0;
These values never change in your code and you are using them in your while loop's conditional.
Try something like:
while(a!=100 && b!=100)
{
if(turn%2==0)
{
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
d=random.nextInt(6)+1;
EditText diceno = (EditText) findViewById(R.id.editText1);
diceno.setText(String.valueOf(d));
}
});
}
turn++;
// a = somevalue based on what you're trying to do.
// b = somevalue based on what you're trying to do.
}

Force closes caused by onClickListener

I made just one activity that opens another activity. Everything was working right until i setted up onClickListener. Now my app force closes when it launch. Without these two lines application launches correctly:
BUeasycounter.setOnClickListener(this);
BUrps.setOnClickListener(this);
Here is my full source:
package com.dano.learning;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Menu extends Activity implements View.OnClickListener{
Button BUeasycounter;
Button BUrps;
#Override
protected void onCreate(Bundle MyBundle) {
super.onCreate(MyBundle);
setContentView(R.layout.activity_main);
initializeVars();
// next 2 lines cause the problem
BUeasycounter.setOnClickListener(this);
BUrps.setOnClickListener(this);
}
public void initializeVars(){
Button BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
Button BUrps = (Button) findViewById(R.id.BUrps);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.BUeasycounter:
Intent openEasyCounter = new Intent("com.dano.learning.EASYCOUNTER");
startActivity(openEasyCounter);
break;
case R.id.BUrps:
Intent openRPS = new Intent("com.dano.learning.EASYCOUNTER");
startActivity(openRPS);
break;
};
}
}
Maybe i just typed something wrong but I cant find mistake in my source for more than two days. Thank you for your help.
There is no exception stack in question, but based on code I see one issue is:
Button BUeasycounter;
Button BUrps;
Both are pointing to null which could be throwing NullPointerException when you do
BUeasycounter.setOnClickListener(this);
BUrps.setOnClickListener(this);
Remove new variable in initializeVars method.
Example:
public void initializeVars(){
BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
BUrps = (Button) findViewById(R.id.BUrps);
}
Note: Java naming convention suggest that use small letter as first letter for variable name.
remove smi-colon after swich case :
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.BUeasycounter:
Intent openEasyCounter = new Intent("com.dano.learning.EASYCOUNTER");
startActivity(openEasyCounter);
break;
case R.id.BUrps:
Intent openRPS = new Intent("com.dano.learning.EASYCOUNTER");
startActivity(openRPS);
break;
} //>>>> from here remove semi-colon
and change initializeVars method as :
public void initializeVars(){
BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
BUrps = (Button) findViewById(R.id.BUrps);
}
public void initializeVars(){
Button BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
Button BUrps = (Button) findViewById(R.id.BUrps);
}
You define two button in this method but these are local variable whose scope lies between this block.
You can not access outside from this. You have initialize the local variable but instance button variable
still have null.To get solution from NPE you should write as
public void initializeVars(){
BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
BUrps = (Button) findViewById(R.id.BUrps);
}
From above method it assign the reference in instance variable its scope till this class exist.
and last remove semi colon from end of switch block.

Categories

Resources