I have array in xml and I am trying to get a particular element from array using its number from user input but my app is crashing when click on button.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String [] tabela;
TextView textView;
TextView textView2;
TextView textView3;
Button next, prev;
int index;
SharedPreferences sPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sPref = getSharedPreferences("daniel.myapplication", Context.MODE_PRIVATE);
editor = sPref.edit();
// Importing the string array from Valuses folder
tabela = getResources().getStringArray(R.array.array);
// initialization of textview
textView =(TextView)findViewById(R.id.textView);
textView2 =(TextView)findViewById(R.id.textView2);
textView3 =(TextView)findViewById(R.id.textView3);
//Initialization of buttons
next =(Button)findViewById(R.id.button);
prev =(Button)findViewById(R.id.button2);
//OnClickListener for buttons
next.setOnClickListener(this);
prev.setOnClickListener(this);
// Setting values for variable and textviews
index = sPref.getInt("key", 0);
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index+1));
textView3.setText("/"+String.valueOf(tabela.length));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPause(){
super.onPause();
editor.putInt("key",index);
editor.commit();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button2:
index++;
if (index==tabela.length){
index=0;
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index+1));
}else {
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index + 1));
}
break;
case R.id.button:
index--;
if (index ==-1){
index = tabela.length -1;
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index+1));
}else {
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index + 1));
}
break;
}
}
public void random(View view) {
Random losuj = new Random();
int i = losuj.nextInt(tabela.length);
textView.setText(tabela[i]);
textView2.setText(String.valueOf(i + 1));
}
public void press(View view) {
EditText editText = (EditText) findViewById(R.id.editText);
int b = Integer.parseInt(editText.getText().toString());
// b = (int) Array.get(tabela, b);
textView.setText(tabela[b]);
textView2.setText(String.valueOf(b + 1));
}
}
This is my XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp"
android:textSize="25sp"
android:id="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/previous"
android:id="#+id/button"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
android:id="#+id/button2"
android:layout_alignBottom="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/xx"
android:id="#+id/textView2"
android:textSize="20sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/yy"
android:id="#+id/textView3"
android:textSize="20sp"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/rand"
android:id="#+id/button3"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="random"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button4"
android:layout_below="#+id/button3"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
android:onClick="press"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignTop="#+id/button4"
android:layout_toRightOf="#+id/button4"
android:onClick="press"/>
int[] myArray = getResources().getIntArray(R.array.my_xml_int_array);
EditText editText = (EditText) findViewById(R.id.editText);
int b = Integer.valueOf(editText.getText().toString());
// Check the number is within range
if (b >= 0 && b < (myArray.length - 1)) {
textView.setText(String.valueOf(myArray[b]));
}
You should probably also make sure you set the input type for your EditText as number in your layout xml.
<EditText
android:id="#+id/editText"
...
android:inputType="number"/>
Additional:
As per my comments under your question "remove onClick from the EditText".
Your final EditText definition should look something like this:
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button4"
android:layout_toRightOf="#+id/button4"
android:inputType="number"/>
The most important thing is removing android:onClick="press" from the EditText.
When you run it, enter your number in the edit text and then press button4 (which you have labeled "New Button". The required string is then correctly shown in the TextView.
I have tested your code, copy/pasting it exactly as it is, and only changed the `EditText' as described, and created a dummy string-array in xml for testing. It works fine. If you are still having problems, provide some more description of what is happening.
In order to get an array from resource, do this somewhere within your onCreate():
ArrayList<String> yourArray;
yourArray = getResources().getStringArray(R.array.your_array_name_in_xml);
After that, you could just call yourArray.get(index) to get its content.
Given that, you could do this in order to get what you want:
int index = Integer.parseInt(yourEditText.getText().toString());
String textFromArray = yourArray.get(index);
yourTextView.setText(textFromArray);
Related
I'm building a simple app to calculate expenses and cost of living and provide smart living recommendations.
The app requests each expense as a textview, then when a button is clicked, it goes through the textviews, parses them as doubles and assigns them to a public value.
Here is my code:
package ericleeconklin.costoflivingcalculator;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
public class EnterExpenses extends ActionBarActivity {
public Double rentMortgage;
public Double utilities;
public Double insurance;
public Double phoneInternet;
public Double food;
public Double carPayment;
public Double miscellaneous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_expenses);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_enter_expenses, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void enterExpenses(View view) {
try {
TextView rentView = (TextView) findViewById(R.id.enterRent);
TextView utilitiesView = (TextView) findViewById(R.id.enterUtilities);
TextView insuranceView = (TextView) findViewById(R.id.enterInsurance);
TextView phoneView = (TextView) findViewById(R.id.enterTV);
TextView foodView = (TextView) findViewById(R.id.enterFood);
TextView carView = (TextView) findViewById(R.id.enterCarPayment);
TextView miscView = (TextView) findViewById(R.id.enterMisc);
Double[] doubleExpensesArray = new Double[]{Double.parseDouble(rentView.toString()),
Double.parseDouble(utilitiesView.toString()),
Double.parseDouble(insuranceView.toString()),
Double.parseDouble(phoneView.toString()),
Double.parseDouble(foodView.toString()),
Double.parseDouble(carView.toString()),
Double.parseDouble(miscView.toString())};
rentMortgage = doubleExpensesArray[0];
utilities = doubleExpensesArray[1];
insurance = doubleExpensesArray[2];
phoneInternet = doubleExpensesArray[3];
food = doubleExpensesArray[4];
carPayment = doubleExpensesArray[5];
miscellaneous = doubleExpensesArray[6];
Intent myIntent = new Intent(this, FinalGrade.class);
startActivity(myIntent);
} catch(NullPointerException nullPointer) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please enter valid amounts!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
And my XML:
<ScrollView
android:layout_width="fill_parent"
android:id="#+id/scrollView"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Enter Your Monthly Expenses (USD)"
android:id="#+id/textView"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:textAlignment="center"/>
<EditText android:id="#+id/enterRent"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="100dp"
android:layout_centerHorizontal="true"
android:ellipsize="end"
android:singleLine="true"
android:textColorHint="#888888"
android:hint="Enter Rent/Mortgage">
</EditText>
<EditText android:id="#+id/enterUtilities"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="160dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Utilities">
</EditText>
<EditText android:id="#+id/enterInsurance"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="220dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Insurance">
</EditText>
<EditText android:id="#+id/enterTV"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="280dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter TV/Phone/Internet">
</EditText>
<EditText android:id="#+id/enterFood"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="340dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Food">
</EditText>
<EditText android:id="#+id/enterCarPayment"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="400dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Car Payment">
</EditText>
<EditText android:id="#+id/enterMisc"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_marginTop="460dp"
android:layout_centerHorizontal="true"
android:inputType="number"
android:textColorHint="#888888"
android:hint="Enter Miscellaneous">
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grade My Cost of Living"
android:id="#+id/enterExpenses"
android:layout_marginTop="520dp"
android:layout_centerHorizontal="true"
android:onClick="enterExpenses"/>
</RelativeLayout>
</ScrollView>
First, your XML shows only 1 TextView and the rest are EditTexts, So in your activity code will need to reflect the right object type for the id's your finding on the view.
EditText rentView = (EditText) findViewById(R.id.enterRent);
EditText utilitiesView = (EditText) findViewById(R.id.enterUtilities);
EditText insuranceView = (EditText) findViewById(R.id.enterInsurance);
EditText phoneView = (EditText) findViewById(R.id.enterTV);
EditText foodView = (EditText) findViewById(R.id.enterFood);
EditText carView = (EditText) findViewById(R.id.enterCarPayment);
EditText miscView = (EditText) findViewById(R.id.enterMisc);
Second, you must use getText().toString() on the EditTexts in order to get the text value from them. See the documentation on EditText.
Double value = Double.parseDouble(carView.getText().toString());
Then if you wanting to send this your Double[] over an Intent to the Final activity, you would do it like this.
Intent intent = new Intent(EnterExpenses.this, FinalGrade.class);
Bundle bundle = new Bundle();
bundle.putDoubleArray("your_double_key", doubleExpensesArray);
intent.putExtras(bundle);
startActivity(intent);
and would receive the double in the "FinalGrade.class" like so:
Bundle bundle = this.getIntent().getExtras();
Double[] double = bundle.getDoubleArray("your_double_key");
* You could try this *
I'd also personally set up my Button click listeners in my activity code like such instead of in XML android:onClick=""/>. This might help your issue.
Button calculate = (Button) findViewById(R.id.button).
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick() {
enterExpenses();
}
});
you are wrong in these lines
double[] doubleExpensesArray = new double[]{Double.parseDouble(rentView**.getText().**toString()),
Double.parseDouble(utilitiesView.**.getText().**toString()),
Double.parseDouble(insuranceView.**.getText().**toString()),
Double.parseDouble(phoneView.**.getText().**toString()),
Double.parseDouble(foodView.**.getText().**toString()),
Double.parseDouble(carView.**.getText().**toString()),
Double.parseDouble(miscView.**.getText().**toString())};
You should first get the text of the TextView before parsing all the doubles
Double.parseDouble(utilitiesView.toString()), // that's wrong
Double.parseDouble(utilitiesView.getText().toString()), // that's right
and so on to all the TextViews.
I have an application that have a TableLayout with 60 texviews.
The user can touch them and a DialogActivity start for take the text and background color of the clicked TextView.
But the app have a bug that some times all TextView take the color of the first inputed color and inside of the code i haven't a loop that assign the color.
I think that, the problem come from to the orientation of the screen (possible?).
Because the Activity that contain TableLayout is landscape and the Dialog is portrait.
Infact when the Dialog start behind it there is the Activity that change his orientation with the Dialog and all textviews change their color.
How can i avoid this bug?
Why this happend?
Acitivity landscape:
public class ActivitySetOrario extends ActionBarActivity {
//Static perch� cosi non perdo i dati inseriti in precedenza!
static int clickedTextViewId; // Declare TextView as class level member field
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_orario);
MySQLiteHelper db = new MySQLiteHelper(this);
//Get all materie inside database
List<Materia> materia = db.getAllMaterie();
//change all TextView inputed from user
if(materia.isEmpty()){
//do nothing
}else {
for (Materia mat : materia) {
//Change all the TextView with values stored inside the database
TextView changedtextview = (TextView) findViewById(mat.getID());
changedtextview.setText(mat.getMateria());
changedtextview.setBackgroundColor(mat.getColor());
}
}
}//Fine oncreate
//Prende indietro la materia aggiunta dall'ActivityAddMateria
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1) {
if (resultCode == RESULT_OK) {
MySQLiteHelper db = new MySQLiteHelper(this);
String result = data.getStringExtra("result"); //Take the materia from Dialog
int color = data.getIntExtra("color", 1); //Take the color from Dialog
//Here i need to recognize row and column
db.addMateria(new Materia(clickedTextViewId, result, color));
TextView clickedtextView = (TextView) findViewById(clickedTextViewId); //(TextView) view;
clickedtextView.setText(result);
clickedtextView.setBackgroundColor(color);
}
if (resultCode == RESULT_CANCELED) {
//Nessuna materia inserita
}
}
}//onActivityResult
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_set_orario, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.draw_orario:
//addMateria();
MySQLiteHelper db = new MySQLiteHelper(this);
db.deleteMateria();
onStart();
return true;
case R.id.save_data_orario:
//SERIALIZZO I DATI CHE DOVRA PRENDERE ActivityOrario
backToOrario();
finish();
return true;
case R.id.exit_orario:
//Torno alla schermata orario annullo ogni modifica NON SERIALIZZO
backToOrario();
finish();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Torna alla ActivityOrario
public void backToOrario(){
Intent myIntent = new Intent(ActivitySetOrario.this, ActivityOrario.class);
startActivity(myIntent);
}
public void addMateria(View v){
//To get ID of your TextView do this
clickedTextViewId = v.getId();
//StartActivityForResult perche mi aspetto la materia inserita dall'altra activity
Intent myIntent = new Intent(ActivitySetOrario.this, ActivityAddMateria.class);
ActivitySetOrario.this.startActivityForResult(myIntent, 1);
}
}
The Dialog portrait Activity:
public class ActivityAddMateria extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_materia);
final Button exit_button = (Button) findViewById(R.id.exit_dialog_materia);
exit_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//No input
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
//Exit from Dialog
finish();
}
});
final Button accept_button = (Button) findViewById(R.id.add_materia);
accept_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Find EditText for take data
EditText nome_materia = (EditText)findViewById(R.id.nome_materia);
//Put result into variable result that is send back
String result = nome_materia.getText().toString();
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.group1);
int radioButtonID = radioGroup.getCheckedRadioButtonId();
View radioButton = radioGroup.findViewById(radioButtonID);
Drawable background = radioButton.getBackground();
if (background instanceof ColorDrawable) {
int color = ((ColorDrawable) background).getColor();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result).putExtra("color",color);
setResult(RESULT_OK,returnIntent);
}
// Exit to Dialog
finish();
}
});
}
}
The xml of the first activity:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue_orario"
android:id="#+id/table">
<TableRow
android:id="#+id/dayrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="35dp" >
<TextView
android:id="#+id/d1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Lun."
android:textColor="#color/text_orario"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/d2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Mar."
android:textColor="#color/text_orario"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/d3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Mer."
android:textColor="#color/text_orario"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/d4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gio."
android:textColor="#color/text_orario"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/d5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Ven."
android:textColor="#color/text_orario"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/d6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Sab."
android:textColor="#color/text_orario"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
<ScrollView
android:id="#+id/scrollorario"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableRow
android:id="#+id/prima_riga"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/h1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textColor="#color/text_orario"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/mat11"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:gravity="center"
android:clickable="true"
android:onClick="addMateria"
android:background="#color/grigio_chiaro"
android:text=""/>
<TextView
android:id="#+id/mat12"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="33dp"
android:gravity="center"
android:clickable="true"
android:onClick="addMateria"
android:background="#color/grigio_chiaro"
android:text="" />
<TextView
android:id="#+id/mat13"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="33dp"
android:gravity="center"
android:clickable="true"
android:onClick="addMateria"
android:background="#color/grigio_chiaro"
android:text="" />
<TextView
android:id="#+id/mat14"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="33dp"
android:gravity="center"
android:clickable="true"
android:onClick="addMateria"
android:background="#color/grigio_chiaro"
android:text="" />
<TextView
android:id="#+id/mat15"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="33dp"
android:gravity="center"
android:clickable="true"
android:onClick="addMateria"
android:background="#color/grigio_chiaro"
android:text="" />
<TextView
android:id="#+id/mat16"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginLeft="33dp"
android:gravity="center"
android:clickable="true"
android:onClick="addMateria"
android:background="#color/grigio_chiaro"
android:text="" />
</TableRow>
<!--TOO LONG THE XML I CUT IT THE OTHER ROW ARE THE SAME-->
</LinearLayout>
</ScrollView>
</TableLayout>
Some screenshoot:
You shouldn't be using the ids of the textviews in your database: they can change between different compilations of your app. Which could be the culprit. However, the only way they're all being set is in the for loop: you should verify your database is correct and verify that loop is not running every time.
I'm new to Android. I'm trying to test 2 Activities in my project where when I click on a button in my first Activity, it should take me to the second Activity. Here I have given a click event to my button but when I run the project, I'm unable to see anything, its just a blank screen. What am I missing ?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onAddCLick(View view) {
Intent TaskIntent = new Intent(this,SecondScreen.class);
startActivity(TaskIntent);
}
}
This is the second activity :-
public class SecondScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Intent task = getIntent();
}
public void cancl_btn(View view) {
Intent goBack = getIntent();
finish();
}
}
This is activity_main.xml :-
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="left"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ListView
android:layout_width="wrap_content"
android:layout_height="516dp"
android:id="#+id/theListView">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/add_task"
android:onClick="onAddCLick"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/setloc"
android:onClick="onMapbtnClck"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/settings"
android:onClick="onSetngClck"/>
</LinearLayout>
This is second_layout.xml :-
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="left">
<EditText
android:layout_width="364dp"
android:layout_height="wrap_content"
android:id="#+id/task_name_edit_txt"
android:text="Enter your Details here" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Set Location"
android:id="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Set_loc_btn"
android:onClick="set_usr_loc"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Add_task_btn"
android:onClick="add_usr_tsk_btn"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel_btn"
android:onClick="cancl_btn"/>
</LinearLayout>
</LinearLayout>
Use this code:
In first activity:
public void onAddCLick(View view) {
Intent TaskIntent = new
Intent(MainActivity.this,SecondScreen.class);
startActivity(TaskIntent);
}
In second Activity:
public void cancl_btn(View view) {
Intent goBack =new
Intent(SecondScreen.this,MainActivity.class);
startActivity(goBack);
}
by assuming that you have posted the complete XML file of the second layout,, I tried running it on my android studio and as you can see in the xml file itself you are missing lot of information in it,,,
you need to define the schema as you have done in the first xml and
the < EditText > tag cannot be outside a container, you need to place it inside the container, that is, inside any kind of layout (linear, relative etc)..
if the issue is with the xml file then modifying it as per above two points will solve your problem,, hope this helps
Am trying to use radio button group widget to select gender in my application. Now here is the thing. The user will select a gender and on clicking the button the user will be guided to the respective activity. I wrote the code . The second problem is that my program does nothing though am launching new activities in the if part. I debugged my program to see if the if condition is satisfied seems to me it does. Here is the xml and the .java file
public class Gender extends Activity{
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gender_asking);
addListenerOnButton();
}
public void addListenerOnButton() {
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.gender_button);
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//****************************
int selectedId = radioSexGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioSexButton = (RadioButton) findViewById(selectedId);
if("Iam a Guy!".equals(radioSexButton.getText()))
{
Intent male_activity = new Intent(Gender.this, Meter.class);
startActivity(male_activity);
}
if("Iam a Girl!".equals(radioSexButton.getText()))
{
Intent male_activity = new Intent(Gender.this, For_Girl.class);
startActivity(male_activity);
}
//********************************
}
});
}
}
and the associated xml is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/hyu_bg"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".KissingMeter" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="Tell Us Your Gender!"
android:textSize="30dp" />
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/gender_button"
android:layout_below="#+id/textView1"
android:layout_marginTop="30dp" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/radioFemale"
android:layout_alignLeft="#+id/radioFemale"
android:layout_marginBottom="34dp"
android:checked="true"
android:text="Iam a Guy!" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/gender_button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="44dp"
android:text="Iam a Girl!" />
</RadioGroup>
<Button
android:id="#+id/gender_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioSex"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="Lol" />
</RelativeLayout>
First of all, don't rely on the text of a View in this situation. If you decide to change it later then it will create problems. Most likely, you won't change the id of it so just use that. Change it to something like this
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
int selectedId = radioSexGroup.getCheckedRadioButtonId(); / get the id
switch (selectedId) // switch on the button selected
{
case R.id.radioMale:
Intent male_activity = new Intent(Gender.this, Meter.class);
startActivity(male_activity);
break;
case R.id.radioFemale:
Intent male_activity = new Intent(Gender.this, For_Girl.class);
startActivity(male_activity);
break;
default:
Toast.makeText(v.getContext(), "No gender selected",
Toast.LENGTH_SHORT).show();
break;
}
//********************************
}
});
In my app, the user inputs a number (in this case, the number of reactants in a chemical equation, so the number of starting materials) and as a result a number of boxes, the amount matching that of the number given by the user, are produced/spawned/created below after pressing a button.
How do I go about doing this? I thought a for-loop would come into play, so I started it off.
Here's the Java class:
public class EquationBalancer extends Activity {
final EditText reactantNumberField = (EditText) findViewById(R.id.reactantsNumber);
final int reactantNom = Integer.parseInt(reactantNumberField.getText().toString());
HorizontalScrollView reactants = (HorizontalScrollView) findViewById(R.id.reactants);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balancelayout);
Button setReactantsNo = (Button) findViewById(R.id.reactantsNumberOk);
setReactantsNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i = 1; i < reactantNom; i++) {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.balancelayout, menu);
return true;
}
}
and the XML layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/reactantsHowMany"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="#string/reactantsHowMany"
android:textSize="18dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/reactantsNumber"
android:paddingTop="5dp"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_below="#id/reactantsHowMany"
android:layout_marginLeft="60dp"
android:inputType="number"
android:hint="e.g. 4" />
<Button
android:id="#+id/reactantsNumberOk"
android:paddingTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/reactantsHowMany"
android:layout_alignParentRight="true"
android:layout_marginRight="60dp"
android:layout_alignBottom="#id/reactantsNumber"
android:text="Set" />
<HorizontalScrollView
android:id="#+id/reactants"
android:paddingTop="5dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#id/reactantsNumber" >
</HorizontalScrollView>
</RelativeLayout>
for (int i = 1; i < reactantNom; i++) {
EditText editText=new EditText(this);
editText.setText("some text if you want else remove this line");
reactants.addView(editText);
}
and if you want to get data from these edittext some where else in your code then maintain an array of edittext and save these edittext objects in that array..,.
Try this..,.