This is my code for a button. Whenever i click this the app shuts down!I am unable to understand why it's happening?
In my code, I am trying to check if values from dynamically created EditText field has been stored on my variable array values[] and bValues[];
I looked for many answers here on how to retrieve value from dynamic edittext fields. And I came up with this from my understanding.
Can anyone tell me where am I going wrong? And a corrected demo code will be of help!
public class MainActivity extends AppCompatActivity {
private static int a;
private static EditText ainput;
private static Button btn, set;
TextView equal_sign;
private static TableLayout tableLayout;
private static LinearLayout bMatrix;
List<EditText> allEds = new ArrayList<EditText>(a*a);
double[] values = new double[(allEds.size())];
List<EditText> bMatrixValues = new ArrayList<EditText>(a);
double[] bValues = new double[bMatrixValues.size()];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ainput = (EditText) findViewById(R.id.a);
btn = (Button) findViewById(R.id.btn);
set = (Button)findViewById(R.id.set);
tableLayout = (TableLayout) findViewById(R.id.table1);
equal_sign = (TextView) findViewById(R.id.equal_sign);
bMatrix = (LinearLayout) findViewById(R.id.bMatrix);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.parseInt(ainput.getText().toString());
tableLayout.removeAllViews();
createMatrix();
}
});
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < allEds.size(); i++){
values[i] = Double.parseDouble(allEds.get(i).getText().toString());
}
for (int j = 0 ; j < bMatrixValues.size(); j++){
bValues[j] = Double.parseDouble(bMatrixValues.get(j).getText().toString());
}
if (allEds.size() > 0 && bMatrixValues.size() > 0){
Toast.makeText(MainActivity.this, "Main Matrix Values inserted!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Insertion failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void createMatrix() {
int p = 1;
for (int i = 0; i < a; i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams lp = new
TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
row.setLayoutParams(lp);
EditText magicField;
for (int j = 0; j < a; j++) {
magicField = new EditText(MainActivity.this);
allEds.add(magicField);
magicField.setId((p));
magicField.setHint("et-" + (Integer.toString(p)));
magicField.setGravity(Gravity.CENTER);
magicField.setWidth(100);
row.addView(magicField, j);
p++;
}
tableLayout.addView(row, i);
}
bMatrix.removeAllViews();
equal_sign.setText("=");
equal_sign.setTextSize(30);
createBMatrix();
}
private void createBMatrix() {
int id = (a * a) + 1;
for (int s = 0; s < a; s++) {
final EditText b = new EditText(this);
bMatrixValues.add(b);
b.setId(id);
b.setHint("b-" + (Integer.toString(s + 1)));
b.setGravity(Gravity.CENTER);
b.setWidth(100);
bMatrix.addView(b);
id++;
}
}
}
And this is the output screen!
Matrix style edit text field gets created nicely. But when i give values to those fields and click on set value button app shuts down..
Related
I am newbie on Android Studio. I have a question.
I am making a match cards application.
After a failed match cards flipping back after 0,5 sec. But while this time, you can still check other cards. I want to disable that. I'm extends Button to a class. I'm posting both of this scripts. Thanks for your helps.
This is my Card Class.
public class kart extends Button {
boolean acikMi = false;
boolean cevrilebilir = true;
int arkaPlanID;
int onPlanID=0;
Drawable on;
Drawable d;
public kart(Context context, int id) {
super(context);
setId(id);
arkaPlanID = R.drawable.arka1;
if(id%8==1)
onPlanID = R.drawable.c1;
if(id%8==2)
onPlanID = R.drawable.c2;
if(id%8==3)
onPlanID = R.drawable.c3;
if(id%8==4)
onPlanID = R.drawable.c4;
if(id%8==5)
onPlanID = R.drawable.c5;
if(id%8==6)
onPlanID = R.drawable.c6;
if(id%8==7)
onPlanID = R.drawable.c7;
if(id%8==0)
onPlanID = R.drawable.c8;
d = AppCompatDrawableManager.get().getDrawable(context,arkaPlanID);
on = AppCompatDrawableManager.get().getDrawable(context, onPlanID);
setBackground(d);
}
public void cevir(){
if (cevrilebilir){
if(!acikMi){
setBackground(on);
acikMi = true;
}
else{
setBackground(d);
acikMi=false;
}
}
}
And this is my Java code.
public class GameScreen extends AppCompatActivity {
int sonKart = 0;
int skor = 0;
int hamle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Intent i = getIntent();
final String s = i.getStringExtra("ad");
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(s);
GridLayout gr = (GridLayout) findViewById(R.id.grid);
kart kartlar[] = new kart[16];
for (int j = 1; j <= 16; j++) {
kartlar[j - 1] = new kart(this, j);
kartlar[j-1].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hamle++;
final kart k = (kart)v;
k.cevir();
if (sonKart >0){
final kart k2 = (kart) findViewById(sonKart);
if (k2.onPlanID==k.onPlanID&&k2.getId()!=k.getId()){
k2.cevrilebilir=false;
k.cevrilebilir=false;
sonKart =0;
skor++;
TextView tv = (TextView) findViewById(R.id.textView3);
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv.setText("Score: "+skor);
tv2.setText("Total moves: "+hamle);
if (skor==8){
Intent i = new Intent(GameScreen.this,scoreboard.class);
i.putExtra("ham",hamle);
i.putExtra("isim",s);
startActivity(i);
//oyun bitti
}
}
else{
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
k2.cevir();
k.cevir();
}
},500);
sonKart =0;
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv2.setText("Total moves: "+hamle);
}
}
else{
sonKart = k.getId();
}
}
});
}
for (int j=0;j<16;j++){
int rg =(int) (Math.random()*16);
kart k = kartlar[rg];
kartlar[rg] = kartlar [j];
kartlar[j] = k;
}
for (int j = 0; j < 16; j++)
gr.addView(kartlar[j]);
}
}
to disable click on button
button.setEnabled(false);
I am working on Indoor positioning system with wifi fingerprinting in which I want to store level of specifics BSSID in arrryList I tried this code but it seems not to work
public class calibrate2 extends AppCompatActivity {
WifiManager wifimanager2;
Button cali;
Button reset;
//EditText Tx;
//EditText Ty;
TextView textView;
TextView textView2;
List<ScanResult> list;
Integer j,x,i=0;
ArrayList<String> Ap=new ArrayList<>();;
ArrayList<Integer> si=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calibrate2);
Ap = getIntent().getStringArrayListExtra("ap");
cali = (Button) findViewById(R.id.button);
reset = (Button) findViewById(R.id.button2);
textView= (TextView)findViewById(R.id.textView);
textView2= (TextView)findViewById(R.id.textView2);
// Tx = (EditText) findViewById(R.id.editText);
// Ty = (EditText) findViewById(R.id.editText2);
wifimanager2 = (WifiManager) getSystemService(Context.WIFI_SERVICE);
cali.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
wifimanager2.startScan();
list = wifimanager2.getScanResults();
for (j = 0; j < Ap.size(); j++) {
for (i = 0; i < list.size(); i++) {
if (list.get(i).BSSID == Ap.get(j)) {
si.add(list.get(i).level);
break;
}
}
for (j = 0; j < Ap.size(); j++) {
textView2.append(si.get(j).toString());
textView2.append(" /n");
}
}
}
}
);
}}
I guess the problem is in the for loop because activity is working perfectly but whenever I click button it goes to parent activity
I got the answer now with this changes it is working
` for (i = 0; i < list.size(); i++) {
if (Ap.get(j).contains(list.get(i).BSSID) {
si.add(list.get(i).level);
break;}}
for (j = 0; j <si.size(); j++) {
//change Ap.size()to si.size()
textView2.append(si.get(j).toString());
textView2.append(" /n");}
I'm in the beginning of my learning how to make apps. I want to make an app which should display randomized inputted tasks to do for the user. Firstly user should choose how many tasks would like to create and then write down tasks in EditText. I am able to create particular amount of EditText but I have no clue how to display all EditText input after pressing button. I have many versions of the code but non of them work. I got stuck and I need advice.
Here is one of my code version for the second activity.
public class TaskActivity extends AppCompatActivity {
LinearLayout containerLayout;
TextView receiverTV;
TextView tv;
TextView displayTaskTv;
EditText et;
Button btn;
Button randomTaskBtn;
int i = 0;
int size;
String inputEditText;
String inputTextView;
String stringsEt[];
String stringsTv [];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
containerLayout = (LinearLayout) findViewById(R.id.linear_layout);
receiverTV = (TextView) findViewById(R.id.receiver_textView);
Intent intent = getIntent();
int number = intent.getIntExtra("Number", defaultValue);
receiverTV.setText("You have chosen to add: " + number + " tasks!");
createEtTvBtn(number);
createBtn();
createTextView();
}
public void createEtTvBtn(int number) {
for (i = 1; i <= number; i++) {
tv = new TextView(this);
tv.setText("Task nr: " + i);
tv.setPadding(16, 16, 16, 16);
tv.setTextColor(Color.parseColor("#008b50"));
tv.setTextSize(20);
tv.setId(i + value);
containerLayout.addView(tv);
et = new EditText(this);
et.setHint("Enter task nr: " + i);
et.setId(i + value);
et.setLines(2);
containerLayout.addView(et);
btn = new Button(this);
btn.setText("Confirm task nr: " + i);
btn.setId(i + value);
containerLayout.addView(btn);
final List<EditText> allEditText = new ArrayList<EditText>();
final List<TextView>allTextView = new ArrayList<TextView>();
final List<Button>allButton = new ArrayList<Button>();
String[] stringsEditText = new String[(allEditText.size())];
String[] stringsTextView = new String[(allTextView.size())];
String[] stringsBtn = new String[(allButton.size())];
for(int i=0; i < allEditText.size(); i++){
stringsEditText[i] = allEditText.get(i).getText().toString();
}
for (int i=0; i < allTextView.size(); i++) {
stringsTextView[i] = allTextView.get(i).getText().toString();
size = allTextView.get(i).getText().toString().length();
}
for(int i=0; i < allButton.size(); i++){
stringsBtn[i] = allButton.get(i).getText().toString();
}
allTextView.add(tv);
allEditText.add(et);
allButton.add(btn);
allButton.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEditText = allEditText.get(0).getText().toString();
stringsEt = new String[] {allEditText.get(0).getText().toString()};
if (inputEditText.length() > 0) {
allTextView.get(0).setText(inputEditText);
allEditText.add(allEditText.get(0));
allEditText.get(0).setText("");
}
else if (inputEditText.length() ==0){
Toast.makeText(TaskActivity.this, "You need to write down your task", Toast.LENGTH_LONG).show();
}
inputTextView = allTextView.get(0).getText().toString();
stringsTv = new String[] {allTextView.get(0).getText().toString()};
if (inputTextView.length() > 0) {
allTextView.get(0).getText();
allTextView.add(allTextView.get(0));
}
}
});
}
}
private Button createBtn() {
randomTaskBtn = new Button(this);
randomTaskBtn.setText("Task");
containerLayout.addView(randomTaskBtn);
randomTaskBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double luckyTask = Math.random();
luckyTask *=size;
int luckyIndex = (int)luckyTask;
displayTaskTv.setText(stringsTv[luckyIndex]);
}
});
return randomTaskBtn;
}
private TextView createTextView() {
displayTaskTv = new TextView(this);
displayTaskTv.setTextSize(20);
displayTaskTv.setTextColor(Color.parseColor("#dd2626"));
displayTaskTv.setText("");
containerLayout.addView(displayTaskTv);
return displayTaskTv;
}
}
Thank you for any constructive advices.
I am sure my code is big mess. I wanted to created more methods but I didn't succeed.
This is what you should do
Step 1 -
Create multiple EditTexts and store each one of them in an ArrayList say myEditTextList.
Step 2- Take data from all edit texts
String str = ""
for(EditText et: myEditTextList) {
str += et.getText().toString();
}
Step 3- Display data in str wherever you want.
This is a sample try code. I am adding checkbox and textview in the table row by using loop. Everything is working fine except that whenever I am trying to take out(checkBox, Textview) from another method, I am not able to get it. I don't know how to solve this. I tried setId but I couldn't get the Id.
protected void onCreate(Bundle savedInstanceState) {
TableLayout tl = (TableLayout)findViewById(R.id.tableLayout1);
TableRow[] row = new TableRow[5];
TextView tv[] = new TextView[5];
CheckBox[] cb = new CheckBox[5];
Button clickTestRow;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int j = 0; j < 5; j ++){
row[j] = new TableRow(this);
tl.addView(row[j]);
tv[j] = new TextView(this);
cb[j] = new CheckBox(this);
tv[j].setText("This is text");
row[j].addView(cb[j]);
row[j].addView(tv[j]);
if(j == 0)
cb[j].setChecked(true);
}
clickTestRow = (Button) findViewById(R.id.clickTestRow);
clickTestRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TableLayout tlid = (TableLayout) findViewById(R.id.tableLayout1);
for(int i = 0; i < 5; i ++){
if(cb[i].isChecked()){
tlid.removeView(row[i]);
}
}
}
});
This is untested, but try this for now.
Key points here are
Fields for your views
Call setContentView before using findViewById
final variables for those that you are trying to use within an anonymous class (the onClickListener)
public class MainActivity extends Activity {
private TableLayout tl;
private Button clickTestRow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tl = (TableLayout)findViewById(R.id.tableLayout1);
clickTestRow = (Button) findViewById(R.id.clickTestRow);
final TableRow[] row = new TableRow[5];
final TextView tv[] = new TextView[5];
final CheckBox[] cb = new CheckBox[5];
for(int j = 0; j < 5; j ++){
row[j] = new TableRow(this);
tl.addView(row[j]);
tv[j] = new TextView(this);
cb[j] = new CheckBox(this);
tv[j].setText("This is text");
row[j].addView(cb[j]);
row[j].addView(tv[j]);
}
cb[0].setChecked(true);
clickTestRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < 5; i ++){
if(cb[i].isChecked()){
tl.removeView(row[i]);
}
}
}
});
}
}
I have 2 EditText fields set up for numeric inputs, a button to start a calculation on the 2 inputs when pressed, and a TextView to display the result of the calculation. For repeated calculations I want to clear the TextView result as soon as either EditText is changed.
Following the reply to "A better way to OnClick for EditText fields" given by 'avalancha', my program clears the result when the first EditText field is changed, but retains the previous answer if only the second EditText field is changed. Yet I have used the same source code for both fields.
Can someone explain why, and how to cure this? my code is appended:
public class DoublesActivity extends ActionBarActivity {
private EditText textBox1, textBox2;
private Button calcButton;
private Context context;
#Override
protected void onCreate(Bundle outState) {
super.onCreate(outState);
setContentView(R.layout.activity_doubles); // Sets the layout .xml file
context = this.getApplicationContext();
textBox1 = (EditText) findViewById(R.id.editText1); //textBox1 holds a reference to the editText1 object in the xml layout
textBox2 = (EditText) findViewById(R.id.editText2);
textBox1.setText("");
textBox2.setText("");
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
textBox2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v2, boolean hasFocus2) {
if (hasFocus2) {
textBox3.setText("");
}
}
});
textBox1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v1, boolean hasFocus1) {
if (hasFocus1) {
textBox3.setText("");
}
}
});
calcButton = (Button) findViewById(R.id.button1);
calcButton.setBackgroundColor(Color.CYAN);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CharSequence userNumber1 = textBox1.getText(); //userNumber1 is a CharSequence holding the text in textBox1
CharSequence userNumber2 = textBox2.getText();
Float handicap1 = Float.parseFloat(userNumber1.toString()); //convert to integer
Float handicap2 = Float.parseFloat(userNumber2.toString()); //convert to integer
Float handicapT = calculate(handicap1, handicap2);
CharSequence userNumber = String.valueOf(handicapT);
if (handicapT > 98.5) {
userNumber = "Non-valid h'cap 1!";
}
if (handicapT < -98.5) {
userNumber = "Non-valid h'cap 2!";
}
textBox3.setText(userNumber); // put result in the TextView
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userNumber = textBox3.getText();
outState.putCharSequence("savedText", userNumber);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userText = savedInstanceState.getCharSequence("savedText");
textBox3.setText(userText);
}
Float calculate(Float h1, Float h2) {
float[] handicapArray;
handicapArray = new float[29];
handicapArray[0] = 28;
handicapArray[1] = 26;
handicapArray[2] = 24;
handicapArray[3] = 22;
handicapArray[4] = 20;
handicapArray[5] = 18;
handicapArray[6] = 16;
handicapArray[7] = 14;
handicapArray[8] = 12;
handicapArray[9] = 11;
handicapArray[10] = 10;
handicapArray[11] = 9;
handicapArray[12] = 8;
handicapArray[13] = 7;
handicapArray[14] = 6;
handicapArray[15] = 5;
handicapArray[16] = 4.5F;
handicapArray[17] = 4;
handicapArray[18] = 3.5F;
handicapArray[19] = 3;
handicapArray[20] = 2.5F;
handicapArray[21] = 2;
handicapArray[22] = 1.5F;
handicapArray[23] = 1;
handicapArray[24] = 0.5F;
handicapArray[25] = 0;
handicapArray[26] = -0.5F;
handicapArray[27] = -1;
handicapArray[28] = -1.5F;
int index1 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h1 - handicapArray[i]) < 0.001) {
index1 = i;
break;
}
}
if (index1 == -1) {
EditText textBox1 = (EditText) findViewById(R.id.editText1);
textBox1.setText("");
}
int index2 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h2 - handicapArray[i]) < 0.001) {
index2 = i;
break;
}
}
if (index2 == -1) {
EditText textBox2 = (EditText) findViewById(R.id.editText2);
textBox2.setText("");
}
int indexT = (index1 + index2) / 2; // Correctly rounds indexT halves down.
Float result = handicapArray[indexT];
if (index1 == -1) {
result = 99F;
}
;
if (index2 == -1) {
result = -99F;
}
;
return result;
}
Use addTextChangedListener to clear textview.
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
resultTextView.setText("");
}
});
For example please use below link
android on Text Change Listener