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.
Related
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..
I am making a math quiz where a mathematical question will be asked in the form of a formula. I put my questions in an ArrayList:
public class DEasy extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1;
private Button answerBtn2;
private Button answerBtn3;
private Button answerBtn4;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 10;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
{"x", "1", "0", "x", "-1"},
{"x²", "2x", "x", "2/x²", "2x²"},
{"64", "0", "1", "64", "8"},
{"x² + 5x", "2x + 5", "7x", "2x", "½x + 5"},
{"19x", "19", "x", "0", "x + 19"},
{"642", "34", "97", "5x-2", "1"}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deasy);
countLabel = (TextView) findViewById(R.id.countLabel);
questionLabel = (TextView) findViewById(R.id.questionLabel);
answerBtn1 = (Button) findViewById(R.id.answerBtn1);
answerBtn2 = (Button) findViewById(R.id.answerBtn2);
answerBtn3 = (Button) findViewById(R.id.answerBtn3);
answerBtn4 = (Button) findViewById(R.id.answerBtn4);
for (int i = 0; i < quizData.length; i++) {
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]);
tmpArray.add(quizData[i][1]);
tmpArray.add(quizData[i][2]);
tmpArray.add(quizData[i][3]);
tmpArray.add(quizData[i][4]);
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
countLabel.setText( getString(R.string.question) + " " + quizCount + ".");
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
ArrayList<String> quiz = quizArray.get(randomNum);
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
quiz.remove(0);
Collections.shuffle(quiz);
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
answerBtn4.setText(quiz.get(3));
quizArray.remove(randomNum);
}
public void checkAnswer(View view){
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if (btnText.equals(rightAnswer)){
alertTitle = "Correct";
rightAnswerCount++;
}
else {
alertTitle = "Wrong";
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer: " + rightAnswer);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT){
Intent intent = new Intent(getApplicationContext(), DResult.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
}
else{
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
}
As you can see I tried to make the formula x^2, this wil not be shown as x with a small exponent 2 but as x^2. This x^2 is not what I want. How can I used for example html in this arraylist to achieve this goal. Or is there another way?
Thanks aton!
Here in replacement of "^" we can use this: "∧".
So now replace code at where you accessing this string array in Adapter as:
Html.fromHtml(quizArray[][])
Thanks and happy coding
EDITED:
Here change it as:
questionLabel.setText(Htm.fromHtml(quiz.get(0)));
Just it will work
I am working on a simple Grading app project with 3 activities, the first one is storing some data in a database and i am replicating that data in both the first activity and the third activity.
The second activity is doing an average calculation and showing the results on that same page, but i want that result to also be shown on the third page. I tried using intents but when i click the button to go to the third page it forces close. What am i doing wrong.
I am trying to show this results in a textview
This is the Second Activity code:
public class AverageActivity extends AppCompatActivity {
EditText editmanner, editinstances, editshortstance, editstrikes, editboxingskills, editknocks, editkicks, editResults;
Button btnResults, btnnewresults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.average_page);
editmanner = (EditText) findViewById(R.id.editText8);
editinstances = (EditText) findViewById(R.id.editText9);
editshortstance = (EditText) findViewById(R.id.editText10);
editstrikes = (EditText) findViewById(R.id.editText11);
editboxingskills = (EditText) findViewById(R.id.editText12);
editknocks = (EditText) findViewById(R.id.editText13);
editkicks = (EditText) findViewById(R.id.editText14);
editResults = (EditText) findViewById(R.id.editText15);
btnResults = (Button) findViewById(R.id.button10);
btnnewresults = (Button) findViewById(R.id.botonresultnuevo);
btnResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int first;
if (editmanner.getText().toString().equals("")) {
first = 0;
} else {
first = Integer.valueOf(editmanner.getText().toString());
}
int second;
if (editinstances.getText().toString().equals("")) {
second = 0;
} else {
second = Integer.valueOf(editinstances.getText().toString());
}
int third;
if (editshortstance.getText().toString().equals("")) {
third = 0;
} else {
third = Integer.valueOf(editshortstance.getText().toString());
}
int fourth;
if (editstrikes.getText().toString().equals("")) {
fourth = 0;
} else {
fourth = Integer.valueOf(editstrikes.getText().toString());
}
int fifth;
if (editboxingskills.getText().toString().equals("")) {
fifth = 0;
} else {
fifth = Integer.valueOf(editboxingskills.getText().toString());
}
int sixth;
if (editknocks.getText().toString().equals("")) {
sixth = 0;
} else {
sixth = Integer.valueOf(editknocks.getText().toString());
}
int seventh;
if (editkicks.getText().toString().equals("")) {
seventh = 0;
} else {
seventh = Integer.valueOf(editkicks.getText().toString());
}
int results;
first = Integer.parseInt(editmanner.getText().toString());
second = Integer.parseInt(editinstances.getText().toString());
third = Integer.parseInt(editshortstance.getText().toString());
fourth = Integer.parseInt(editstrikes.getText().toString());
fifth = Integer.parseInt(editboxingskills.getText().toString());
sixth = Integer.parseInt(editknocks.getText().toString());
seventh = Integer.parseInt(editkicks.getText().toString());
results = (first + second + third + fourth + fifth + sixth + seventh) / 7;
editResults.setText(String.valueOf(results));
}
});
}
public void knowtheresults(View view) {
switch (view.getId()) {
case R.id.botonresultnuevo:
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
Bundle miBundle = new Bundle();
miBundle.putString("nombre", editResults.getText().toString());
miintent.putExtras(miBundle);
startActivity(miintent);
break;
}
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Summary")) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
}
}
}
And This is the Third activity code:
public class ResultActivity extends Activity {
TextView texto;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
texto = (TextView) findViewById(R.id.editText15);
Bundle mibundle=this.getIntent().getExtras();
if(mibundle!=null){
String dato = mibundle.getString("nombre");
texto.setText(dato);
}
mDatabaseHelper = new DatabaseHelper(this);
displayDatabaseInfo();
}
private void displayDatabaseInfo() {
// To access our database, we instantiate our subclass of SQLiteOpenHelper
// and pass the context, which is the current activity.
DatabaseHelper mDbHelper = new DatabaseHelper(this);
// Create and/or open a database to read from it
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Perform this raw SQL query "SELECT * FROM pets"
// to get a Cursor that contains all rows from the pets table.
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
TextView displayView = findViewById(R.id.textViewR1);
try {
displayView.setText("The Student...\n\n");
displayView.append(COL1 + "--" +
COL2 + "--" +
COL4 +
"\n");
// Figure out the index
int idColumnIndex = cursor.getColumnIndex(COL1);
int nameColumnIndex = cursor.getColumnIndex(COL2);
int rankColumnIndex = cursor.getColumnIndex(COL4);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currenRank = cursor.getString(rankColumnIndex);
displayView.append(currentID + "--" +
currentName + "--" +
currenRank + "\n");
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
public void knowtheresults(View view) {
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Start Page")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (button_text.equals("Back...")) {
Intent intent = new Intent(this, AverageActivity.class);
startActivity(intent);
}
}
}
Remove Bundle from your code and use following code
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
miintent.putString("nombre", editResults.getText().toString());
startActivity(miintent);
In you third Activity
String number = getIntent().getStringExtra("nombre");
I'm trying to make a feature for my app where the user can make a selected text Bold but I also want to make it so that if the selected text is already bold, then the text shall be set to normal again, a kind of an undo-function.
I have tried over 100 of combinations without any succses!
CharacterStyle csBold = new StyleSpan(Typeface.BOLD);
CharacterStyle csNormal = new StyleSpan(Typeface.NORMAL);
int start = editText.getSelectionStart();
int end = editText.getSelectionEnd();
SpannableStringBuilder ssb = new SpannableStringBuilder(editText.getText());
ssb.setSpan(csBold, start, end, 1);
SpannableStringBuilder ssb2 = new SpannableStringBuilder(editText.getText());
ssb2.setSpan(csNormal, start, end, 1);
switch(item.getItemId()) {
case R.id.bold:
while(editText.isSelected()){
if(editText.getSelectionStart() + editText.getSelectionEnd() == ssb.getSpanStart(start) + ssb.getSpanEnd(end)){
editText.setText(ssb2);
return true;
}else{
editText.setText(ssb);
return true;
}
}
Update ANSWER
Edittext editext;
Button bold_btn , normal_btn , itlac;
CharacterStyle styleBold , styleItalc;
boolean bold = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
styleBold = new StyleSpan(Typeface.BOLD);
styleNormal = new StyleSpan(Typeface.NORMAL);
styleItalc = new StyleSpan(Typeface.ITALIC);
underLine = new UnderlineSpan();
editext = (Editext) findViewById(R.id.editext);
bold_btn = (Button) findViewById(R.id.button1);
italic_btn = (Button) findViewById(R.id.button2);
italic_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String wholeText = username.getText().toString();
int start = username.getSelectionStart();
int end = username.getSelectionEnd();
SpannableStringBuilder sb = new SpannableStringBuilder(wholeText);
sb.setSpan(styleItalic, start, end, 0);
username.setText(sb);
}
});
........
.....
bold_btn.setOnClickListener(BoldbuttonListener);
normal_btn.setOnClickListener(normalbuttonListener);
}
View.OnClickListener BoldbuttonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
bold = !bold;
String wholeText = username.getText().toString();
int start = username.getSelectionStart();
int end = username.getSelectionEnd();
CharacterStyle passedStyle;
SpannableStringBuilder sb = new SpannableStringBuilder(wholeText);
if(bold) {
passedStyle = styleNormal;
}else {
passedStyle = styleBold;
}
sb.setSpan(passedStyle, start, end, 0);
editext.setText(sb);
}
};
the same for normal effect
I have a TextView which contains a processed text, so that it will be in lower case and doesn't have punctuations.
Now I want to remove the stop words (these stop words are in my language which I already define). After that, I want to send the result to another TextView.
This my code
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button6) {
Intent i2 = new Intent(this, PreposisiRemoval.class);
String test = ((TextView) findViewById(R.id.textView7)).getText()
.toString();
String[] preposisi = { "akibat", "atas", "bagai", "bagi", "berkat",
"dalam", "dari", "demi", "dengan", "di", "hingga",
"karena", "ke", "kecuali", "lewat", "oleh", "pada",
"sampai", "sejak", "seperti", "tanpa", "tentang", "untuk" };
StringBuilder result = new StringBuilder();
Scanner fip1 = new Scanner(test);
while (fip1.hasNext()) {
int flag = 1;
String s1 = fip1.next();
for (int i = 0; i < preposisi.length; i++) {
if (s1.equals(preposisi[i])) {
flag = 0;
}
if (flag != 0) {
System.out.println(s1);
result.append(s1);
}
i2.putExtra("result2", result.toString());
startActivity(i2);
}
}
}
}
After I pressed button6, I did not get any results.
Where is the part of my coding that is wrong?
This code is in another Activity which will receive the processed text.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preposisi_removal);
Intent intent = getIntent();
String result = intent.getStringExtra("result2");
TextView tv = (TextView) findViewById(R.id.textView8);
tv.setMovementMethod(new ScrollingMovementMethod());
tv.setText(result);
tv.setTextSize(12);
}
To prepare the text for result2 you can try the following-
String STOP_WORD = "."; // define your stop word here.
String result2= result.replace(STOP_WORD ,"");
Then pass the text and set it on your second TextView.