So I am running a tutorial app, and it all works except when I try to run the bellow class, however I don't get errors in the code so I was wondering if anyone could help if there is maybe something wrong with the code.
Also on a side not when programming for example you type say: android: in the xml or something. in java how come I don't get the drop down menu with all the options of what can go after?
code:
package com.example.learn.tam;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class textplay extends Activity implements View.OnClickListener{
Button chkCommand;
ToggleButton passToggle;
EditText input;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
holder();
passToggle.setOnClickListener(this);
chkCommand.setOnClickListener(this);
}
private void holder() {
Button chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bResults:
String check = input.getText().toString();
display.setText(check);
if(check.contentEquals("left")){
display.setGravity(Gravity.LEFT);
}
else if(check.contentEquals("center")) {
display.setGravity(Gravity.CENTER);
}
else if(check.contentEquals("right")){
display.setGravity(Gravity.RIGHT);
}
else if(check.contentEquals("blue")){
display.setTextColor(Color.BLUE);
}
else if(check.contentEquals("WTF")){
Random crazy = new Random();
display.setText("WTF!!!!");
display.setTextSize(crazy.nextInt(75));
display.setTextColor(Color.rgb(crazy.nextInt(265),crazy.nextInt(265),crazy.nextInt(265)));
switch(crazy.nextInt(3)){
case 0:
display.setGravity(Gravity.LEFT);
break;
case 1:
display.setGravity(Gravity.CENTER);
break;
case 2:
display.setGravity(Gravity.RIGHT);
break;
}
}
else{
display.setText("Invalid");
display.setGravity(Gravity.CENTER);
display.setTextColor(Color.WHITE);
}
break;
case R.id.tbPassword:
if (passToggle.isChecked() == true){
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}else{
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
break;
}
}
}
Change:
private void holder() {
Button chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
To
private void holder() {
chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
By declaring a new variable with the same name, you were hiding the class field. Due to this, the class level chkCommand remained null, and gave you an exception when you tried to use chkCommand.setOnClickListener(this);.
Related
I'm new to Android. I'm developing an app which gives all the possible combination number based on the user input and separated it by comma.
For example the user input is: 1234
The output should be list all the possible number combination from "1234" like
"1234,1243,1324,1342,1423,1432,2134,etc.."
And there's also another EditText that limit the output by setting it to 1 or 2 or 3 or 4(max).
For example the user input is: 2
The output should be list all the possible number combination from "1234" by "2" digits
"12,13,14,21,23,24,31,32,34,41,42,43"
This is my MainActivity.java
package com.example.androidtest1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
EditText et_input1, et_output1;
Button b_generate, b_clear;
CheckBox checkBox1;
Random r;
int min,output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText mEdit = (EditText) findViewById(R.id.et_output1);
mEdit.setEnabled(false);
r = new Random();
et_input1 = (EditText) findViewById(R.id.et_input1);
et_output1 = (EditText) findViewById(R.id.et_output1);
b_generate = (Button) findViewById(R.id.b_generate);
b_clear = (Button) findViewById(R.id.b_clear);
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
b_generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (et_input1.length()==0){
et_input1.setError("Insert numbers");
}else if(checkBox1.isChecked()){
min = Integer.parseInt(et_input1.getText().toString());
output = (min);
et_output1.setText("" + output + "*");
et_input1.setError(null);
}
else{
et_input1.setError("Check the checkbox");
}
}
});
b_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
et_output1.getText().clear();
et_input1.getText().clear();
return;
}
});
}
}
For some reason I can't get text from EditText with OnClickListener for my button. I want to get these values and place them into data[] and then transfer it to my main activity. For some reason it breaks on if statement in onClick() method. I've checked all the ids of layout elements and that's not the problem.
Here is the source code for my fragment:
package com.xivi0n.materialcalculator;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class FirstFragment extends Fragment implements View.OnClickListener {
RadioGroup rd;
CheckBox cb;
Button calculate;
OnHeadlineSelectedListener sendData;
private EditText yEditText;
private EditText xEditText;
private RadioGroup type;
float data[] = new float[6];
public FirstFragment() {
// Required empty public constructor
}
public interface OnHeadlineSelectedListener {
public void onArticleSelected(float data[]);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
sendData = (OnHeadlineSelectedListener)context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
rd = (RadioGroup) v.findViewById(R.id.isolationOptions);
cb = (CheckBox)v.findViewById(R.id.isolationCB);
xEditText = (EditText) v.findViewById(R.id.xValue);
yEditText = (EditText) v.findViewById(R.id.yValue);
type = (RadioGroup) v.findViewById(R.id.typeOf);
calculate = (Button) v.findViewById(R.id.calculateButton);
cb.setOnClickListener(this);
calculate.setOnClickListener(this);
return v;
}
public void onClick(View v) {
if (v==cb) {
if (cb.isChecked()) {
rd.setVisibility(View.VISIBLE);
} else {
rd.setVisibility(View.INVISIBLE);
}
} else if (v==calculate){
if ((xEditText.getText().toString()!="") && (yEditText.getText().toString()!="")){
data[0] = (float)1;
data[1] = Float.parseFloat(xEditText.getText().toString());
data[2] = Float.parseFloat(yEditText.getText().toString());
data[3] = (float) type.indexOfChild(getActivity().findViewById(type.getCheckedRadioButtonId()));
if (cb.isChecked()){
data[4] = (float)1;
data[5] = (float) rd.indexOfChild(getActivity().findViewById(type.getCheckedRadioButtonId()));
} else {
data[4] = (float)0;
data[5] = (float)0;
}
sendData.onArticleSelected(data);
} else {
Toast.makeText(getActivity(), "Invalid input, check all the parameters!", Toast.LENGTH_LONG).show();
}
}
}
}
Switch on the id of the view:
public void onClick(View v) {
switch (v.getId()){
case R.id.isolationCB:
//do something
break;
case R.id.calculateButton:
//do something else
}
}
Use .equals to compare strings.
Instead of ((xEditText.getText().toString()!= "")) use (!(xEditText.getText().toString().equals("")); as the condition of if statement.
This is my MainActivity. I want when I hit "roll" button dices to "roll" - change until my cycle finish and I want to see that change. But when I run the code and hit the button I see only the end result. Tried increasing the delay of "TimeUnit", but it only slows down my app, I don't see dices "rolling". Where am I wrong and is my code in the wright direction, or am I missing something important? I am still learning Android coding :)
package com.example.rado.diceroller;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}
public void myButtonListenerMethod() {
Button button = (Button) findViewById(R.id.rollButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < 3; i++) {
try {
Random rand = new Random();
int rollResult = rand.nextInt(6) + 1;
TextView diceResult = (TextView) findViewById(R.id.rollResult);
diceResult.setText(Integer.toString(rollResult));
ImageView img = (ImageView) findViewById(R.id.diceImage);
TimeUnit.MILLISECONDS.sleep(10);
switch (rollResult) {
case 1:
img.setImageResource(R.drawable.dice1);
break;
case 2:
img.setImageResource(R.drawable.dice2);
break;
case 3:
img.setImageResource(R.drawable.dice3);
break;
case 4:
img.setImageResource(R.drawable.dice4);
break;
case 5:
img.setImageResource(R.drawable.dice5);
break;
case 6:
img.setImageResource(R.drawable.dice6);
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
Your problem is that Android renders view changes after execution finish. So you can wait as many time as you want with TimeUnit.MILLISECONDS.sleep, the only result you will get will be that Android freezes himself for a bit, then restart the for loop. But he starts to render only when the execution is finished and he can say that he isn't wasting time and cpu to render something that the user will never see.
So you can't accomplish your goal in this way. You could try something like this:
package com.firegloves.test;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private int rolledTimes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}
public void myButtonListenerMethod() {
Button button = (Button) findViewById(R.id.rollButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setTimeout();
}
});
}
private void setTimeout() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (rolledTimes < 6) {
// roll your dice
rollDice();
// set timeout again
setTimeout();
} else {
rolledTimes = 0;
}
}
}, 100);
}
private void rollDice() {
rolledTimes++;
Random rand = new Random();
int rollResult = rand.nextInt(6) + 1;
TextView diceResult = (TextView) findViewById(R.id.rollResult);
diceResult.setText(Integer.toString(rollResult));
ImageView img = (ImageView) findViewById(R.id.diceImage);
switch (rollResult) {
case 1:
img.setImageResource(R.drawable.dice1);
break;
case 2:
img.setImageResource(R.drawable.dice2);
break;
case 3:
img.setImageResource(R.drawable.dice3);
break;
case 4:
img.setImageResource(R.drawable.dice4);
break;
case 5:
img.setImageResource(R.drawable.dice5);
break;
case 6:
img.setImageResource(R.drawable.dice6);
break;
}
}
}
when using the ab.jar in eclipse I get the following error when trying to run the bot.
“Could not find class ‘org.alicebot.ab.Bot’, referenced from method…”. The chat class is being imported but the bot class cannot be imported.
Here is my code:
import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends Activity {
String usertext; String response;
String botname="MAVIS";
Bot mavis=new Bot(botname);
Chat chat= new Chat(mavis);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout ll1 = (LinearLayout) findViewById(R.id.ll1);
final LinearLayout ll2 = (LinearLayout) findViewById(R.id.ll2);
final ScrollView scv = (ScrollView) findViewById(R.id.sv);
final Button btn = (Button) findViewById(R.id.button1);
final EditText medit = (EditText) findViewById(R.id.editText1);
btn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
TextView tvu=new TextView(v.getContext());
TextView tvb=new TextView(v.getContext());
TextView tvut=new TextView(v.getContext());
TextView tvbt=new TextView(v.getContext());
TextView tvdivider1=new TextView(v.getContext());
TextView tvdivider2=new TextView(v.getContext());
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tvu.setLayoutParams(lparams);
tvb.setLayoutParams(lparams);
tvut.setLayoutParams(lparams);
tvbt.setLayoutParams(lparams);
tvdivider1.setLayoutParams(lparams);
tvdivider2.setLayoutParams(lparams);
usertext = medit.getText().toString();
if(usertext.trim().length() != 0){
ll1.addView(tvu);
ll1.addView(tvb);
ll2.addView(tvut);
ll2.addView(tvbt);
ll1.addView(tvdivider1);
ll2.addView(tvdivider2);
response=chat.multisentenceRespond(usertext);
tvu.setText("User");
tvb.setText(botname);
tvbt.setText(" : "+ response);
tvut.setText(" : "+ usertext);
medit.setText(" ");
tvdivider1.setText(" ");
tvdivider2.setText(" --------------------");
}
else{
//do nothing
}
}
});
scv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
scv.post(new Runnable() {
public void run() {
scv.fullScroll(View.FOCUS_DOWN);
}
});
}
});
}
}
I have imported the external library and defined the classpath for it. I have also copied the ab.jar in my project folder and even defined the classpath for it. But nothing seems to be working. Am I doing this wrong or are there more libraries that are needed for this to work. Anybody have a solution to my problem?
Your bot name here is MAVIS..did you change the folder name from the bots.zip???else change it..or simply use the predefined bot names(alice2 etc).
Thankz
I have this activity with question and 4 possible answers, and after each user answer it reloads itself with another question. I placed a textView in the bottom right corner with start value of 1/10 (rezultat.setText(counter+"/10");). I want to increase that value to 2/10, 3/10 and so on, after each question, but I don't know where to put counter++; in my code, and I tried everywhere. Here's my code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class Kviz extends Activity implements View.OnClickListener{
Runnable mLaunchTask = new Runnable() {
public void run() {
startActivity(getIntent());
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
finish();
}
};
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4;
TextView question, proba, rezultat;
int counter = 1;
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
mHandler.postDelayed(mLaunchTaskFinish, 1200);
mHandler.postDelayed(mLaunchTask,1000);
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
}else{
mHandler.postDelayed(mLaunchTaskFinish, 2200);
mHandler.postDelayed(mLaunchTask,2000);
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.POGRESANODGOVOR");
startActivity(i);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.kviz);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKviza);
rezultat = (TextView) findViewById(R.id.tvBrojPitanja);
question = (TextView) findViewById(R.id.tvPitanje);
bOdgovor1 = (Button) findViewById(R.id.bOdgovor1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovor2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovor3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovor4);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
rezultat.setTypeface(dugmad);
question.setTypeface(pitanje);
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData();
question.setText(c.getString(1));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
Collections.shuffle(labels);
bOdgovor1.setText(labels.get(0).option);
bOdgovor1.setTag(labels.get(0));
bOdgovor1.setOnClickListener(clickListener);
bOdgovor2.setText(labels.get(1).option);
bOdgovor2.setTag(labels.get(1));
bOdgovor2.setOnClickListener(clickListener);
bOdgovor3.setText(labels.get(2).option);
bOdgovor3.setTag(labels.get(2));
bOdgovor3.setOnClickListener(clickListener);
bOdgovor4.setText(labels.get(3).option);
bOdgovor4.setTag(labels.get(3));
bOdgovor4.setOnClickListener(clickListener);
rezultat.setText(counter+"/10");
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void onClick(View v) {
}
}
what is the mean of "each user answer it reloads itself with another question." ? Are you using different Activities for diff question ?
You can use same activity for all the questions, when user press any of answer's button, just call a method
public void nextQuestion() {
counter++;
question.setText("");
bOdgovor1.setText("");
bOdgovor2.setText("");
bOdgovor3.setText("");
bOdgovor4.setText("");
//reset your next question and all four options here
rezultat.setText(counter + "/10");
}
It's hard to test from here, but it looks like adding counter++ before the line
Answer ans = (Answer) v.getTag();
Should work fine, as this sets counter to increment whenever the button that seems to be responsible for answering questions is clicked. Remember that you'll also need to call
rezultat.setText(counter+"/10");
Again, to update the text to reflect the new value of counter.
To expand my problem a little bit. I did manage to count questions with counter class, it goes to 2/10, but because I reload my activity after each question, my textView also reloads to 1/10. I think that's the main cause of my problem.