I was checking out a few online tutorials for getting input from a user using a button such as [here][1], however it is not what I was after and wanted to know if any of you have come across a similar problem.
I want to get the user to get prompted to enter an integer input ONLY when the button is clicked and I dont want the TextField etc to show on the screen until the user has clicked the button. The user input has to be saved in the int bias.
Any help would be appreciated.
Whatever is the textField that you are talking about, you can set input type like:
textFieldName.setRawInputType(Configuration.KEYBOARD_12KEY);
You can directly set it in the XML like:
android:inputType="number"
Also, even when you create the TextField, you can set the visibility to Invisible using :
textFieldName.setVisibility(View.INVISIBLE);
Then when user clicks the button you can set it to Visible using:
textFieldName.setVisibility(View.VISIBLE);
You can change the visibility on Button click as you have mentioned in the question.
You can add this textfield in the layout and set its visibility "gone"
boolean isClicked = false;
String userInput = null;
Button grayScaleFilterButton = (Button) findViewById(R.id.filter1_button);
grayScaleFilterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isClicked){
isClicked = false;
//Got the input and hide the textfield.
userInput = textField.getText().toString();
textField.setVisibility(View.GONE);
}else{
//make the textfield visible and user can enter the input.
isClicked = true;
textField.setInputType(InputType.TYPE_CLASS_NUMBER);
textField.setVisibility(View.VISIBLE);
//do something
}
}
});
Try the following code. The comments will guide you through it:
grayScaleFilterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show PopupWindow
showPopup();
// Everything after this will be handled in `doneInput(String)` method
}
});
Declare the PopupWindow as a global variable:
// Right before onCreate(Bundle)
PopupWindow popupWindow;
Create a method showPopup() in your activity:
public void showPopup() {
// Container layout to hold other components
LinearLayout llContainer = new LinearLayout(this);
// Set its orientation to vertical to stack item
llContainer.setOrientation(LinearLayout.VERTICAL);
// Container layout to hold EditText and Button
LinearLayout llContainerInline = new LinearLayout(this);
// Set its orientation to horizontal to place components next to each other
llContainerInline.setOrientation(LinearLayout.HORIZONTAL);
// EditText to get input
final EditText etInput = new EditText(this);
// TextView to show an error message when the user does not provide input
final TextView tvError = new TextView(this);
// For when the user is done
Button bDone = new Button(this);
// If tvError is showing, make it disappear
etInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tvError.setVisibility(View.GONE);
}
});
// This is what will show in etInput when the Popup is first created
etInput.setHint("Please provide a number");
// Input type allowed: Numbers
etInput.setRawInputType(Configuration.KEYBOARD_12KEY);
// Center text inside EditText
etInput.setGravity(Gravity.CENTER);
// tvError should be invisible at first
tvError.setVisibility(View.GONE);
bDone.setText("Done");
bDone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// If user didn't input anything, show tvError
if (etInput.getText().toString().equals("")) {
tvError.setText("Please enter a valid value");
tvError.setVisibility(View.VISIBLE);
etInput.setText("");
// else, call method `doneInput()` which we will define later
} else {
doneInput(etInput.getText().toString());
popupWindow.dismiss();
}
}
});
// Define LayoutParams for tvError
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.topMargin = 20;
// Define LayoutParams for InlineContainer
LinearLayout.LayoutParams layoutParamsForInlineContainer = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParamsForInlineContainer.topMargin = 30;
// Define LayoutParams for EditText
LinearLayout.LayoutParams layoutParamsForInlineET = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
// Set ET's weight to 1 // Take as much space horizontally as possible
layoutParamsForInlineET.weight = 1;
// Define LayoutParams for Button
LinearLayout.LayoutParams layoutParamsForInlineButton = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
// Set Button's weight to 0
layoutParamsForInlineButton.weight = 0;
// Add etInput to inline container
llContainerInline.addView(etInput, layoutParamsForInlineET);
// Add button with layoutParams // Order is important
llContainerInline.addView(bDone, layoutParamsForInlineButton);
// Add tvError with layoutParams
llContainer.addView(tvError, layoutParams);
// Finally add the inline container to llContainer
llContainer.addView(llContainerInline, layoutParamsForInlineContainer);
// Set gravity
llContainer.setGravity(Gravity.CENTER);
// Set any color to Container's background
llContainer.setBackgroundColor(0x95000000);
// Create PopupWindow
popupWindow = new PopupWindow(llContainer,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// Should be focusable
popupWindow.setFocusable(true);
// Show the popup window
popupWindow.showAtLocation(llContainer, Gravity.CENTER, 0, 0);
}
At last, the doneInput(String) method:
public void doneInput(String input) {
int bias = Integer.parseInt(input);
// Work with it // For example, show a Toast
Toast.makeText(this, "Number input by user was: " + bias, Toast.LENGTH_LONG).show();
// Do anything else with input!
}
Note: No xml files are required for this. Copy, follow the instructions, and paste to try it out. You can show this PopupWindow anywhere on screen, in any size, and in any color.
to display on number in keyboard add this line android:inputType="number" to your EditText
<EditText android:id="#+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"
/>
if you want to display edittext into dialog then use customdialog Dialogs Example and use mDialog.show() in button click listener.
here mDialog is object of Dialog
on button click it shows an alterDialogue for user to input. once some value is inputted it shows it in the corresponding textview. Here is the whole code:
package com.example.testandroidapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView input1;
String value = "";
int bias;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button grayScaleFilterButton = (Button) findViewById(R.id.button1);
input1 = (TextView) findViewById(R.id.textView1);
grayScaleFilterButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(v
.getContext());
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(MainActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
value = input.getText().toString();
// Convert the inputted string into Integer
bias = Integer.parseInt(value);
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
input1.setText(value);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
XML code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="5dp"
android:orientation="vertical" >
<EditText
android:id="#+id/edtInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:visibility="gone" />
<Button
android:id="#+id/btnInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="Input"/>
</LinearLayout>
</LinearLayout>
Activity code
public class MyInputActivity extends Activity implements OnClickListener {
private EditText edtInput;
private Button btnInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my);
edtInput = (EditText) findViewById(R.id.edtInput);
btnInput = (Button) findViewById(R.id.btnInput);
btnInput.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
if(edtInput.getVisibility() == View.VISIBLE){
edtInput.setVisibility(View.GONE);
// write your more code here on gone
}else{
edtInput.setVisibility(View.VISIBLE);
// write your more code here on visible
}
}
}
you can set input type number by this line in xml: using this code user can click 0,1,..9 digits only from sofrtware keyboard:
android:digits="1234567890" or android:inputType="number"
Related
I'm developing an Android app on my free time to learn about Android development. I'm trying to make a Grade/GPA Calculator App. I currently have a button called "+ New Semester" whose purpose is to open a popup where the user inputs the semester name. This can be seen in the following two images:
User clicks on "+ New Semester" and the popup appears prompting the user to add the name of that semester.
Now, what I want to do is that when the user clicks on the "Done" button a new button with the text that the user typed in into the text box is created below the "+ New Semester" button, but I can't figure out how to do it. I would appreciate any help.
This is the code I currently have:
package com.example.gradecalculator;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private ImageButton newSemesterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = new Dialog(this);
}
// When user clicks on "+ New Semester" button open a popup where the user is prompted to
// type in the Semester Name and when "Done" is clicked the new semester appears in the view
public void newSemesterPopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_semester_popup);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Open Main Activity
public void openMainActivity() {
Intent main = new Intent(this, MainActivity.class);
startActivity(main);
}
}
You can achieve that by first getting the reference to the layout where you want to add your button. Lets say, the name of the layout where your button should be has the name btn_layout,
Bind the layout. (i.e. LinearLayout layout = findViewById (R.id.btn_layout); )
When the DONE button is clicked, create your new button and add it to the layout. For example:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setText("Your text from edittext");
layout.addView(btn, params);
Even better if you can declare the Button and Layout as fields
You have to get the reference from your buttons parent layout. then create a button and add it to the view. Something like this:
public void newSemesterPopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_semester_popup);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMainActivity();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myParentLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
params = (LinearLayout.LayoutParams) new
LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
yourEditText = d.findViewById(R.id.YourEditText);
myNewButton = new Button(this);
String buttonText = yourEditText.text.toString();
myNewButton.setText(buttonText);
myParentLayout.addView(myNewButton, params);
d.dismiss();
}
});
d.show();
}
Just make that new button on main screen and set visibility to false = newButton.setVisibility(false);
and if you press button done on popup just set visibility to true hope that will help, not sure if that's what you mean
I have no clue what I am doing wrong but when I print the text from the edit text (using getText().toString()), in the logcat it is always an empty string. I am wondering if it has to do with that it is being done inside the onClickfunction for the continue button. I'm putting the whole onCreate function because the code inside the onClick function seems to match exactly what countless tutorials have shown.
#Override
protected void onCreate(Bundle savedInstanceState)
{
Button add_test = new Button(this);
Button delete_test = new Button(this);
Button[] barray = new Button[100];
int trans_grey = Color.parseColor("#40000000");
final String[] test_types = new String[] {"Choose...","Terms", "Multiple choice", "Custom"};
final ArrayAdapter<String> type_adapter = new ArrayAdapter<String>(this,R.layout.spinner_item,test_types);
// Preliminary operations and display opening layouts
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout scroll_layout = (LinearLayout)findViewById(R.id.scroll_layout);
LayoutParams scroll_params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
// Add the add a dynamic button
for (int index = 0; index <= 4; index++)
{
barray[index] = new Button(this);
barray[index].setBackgroundColor(trans_grey);
barray[index].setText("Array buttons");
barray[index].setTextColor(Color.parseColor("#CCffffff"));
scroll_layout.addView(barray[index], scroll_params);
}
add_test.setTextColor(Color.parseColor("#CCffffff"));
add_test.setBackgroundColor(trans_grey);
add_test.setText("Add a Test");
scroll_layout.addView(add_test, scroll_params);
add_test.setOnClickListener(new View.OnClickListener()
{#Override
public void onClick(View v)
{
AlertDialog.Builder add_test_builder = new AlertDialog.Builder(TestActivity.this);
final View add_test_view = getLayoutInflater().inflate(R.layout.add_test_menu, null);
Spinner type_spinner = (Spinner) add_test_view.findViewById(R.id.type);
add_test_builder.setView(add_test_view);
final Button continue_button = (Button) add_test_view.findViewById(R.id.continue_button);
AlertDialog dialog = add_test_builder.create();
dialog.show();
dialog.getWindow().setLayout(950,900);
type_spinner.setAdapter(type_adapter);
continue_button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
View add_test_view = getLayoutInflater().
inflate(R.layout.add_test_menu, null);
// The view of the test attribute dialog
EditText test_title = (EditText) add_test_view.
findViewById(R.id.testTitle);
// Test title widget to hold title of test
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title);
}
});
return;
}
});
// Add the delete a test button
delete_test.setTextColor(Color.parseColor("#CCffffff"));
delete_test.setBackgroundColor(trans_grey);
delete_test.setText("Delete a Test");
scroll_layout.addView(delete_test, scroll_params);
return;
}
}
Layout:
<EditText
android:id="#+id/testTitle"
android:maxLines="1"
android:lines="1"
android:inputType="textAutoCorrect"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#00000000"
android:hint="Test Title"/>
Don't inflate the view yiu are assigning to dialog multiple times as you are creating multiple instances of it you are writing to one view but trying to fetch the data from another....Try doing it like this...
AlertDialog.Builder add_test_builder = new AlertDialog.Builder(TestActivity.this);
final View add_test_view = getLayoutInflater().inflate(R.layout.add_test_menu, null);
final EditText test_title = (EditText) add_test_view. findViewById(R.id.testTitle);
continue_button.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title); } });
I think you should define EditText before and outside of your onlick method. Or get string after your onlick method.
IMO you may call editText string outside of Click method like above
final EditText test_title;
continue_button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
View add_test_view = getLayoutInflater().
inflate(R.layout.add_test_menu, null);
// The view of the test attribute dialog
EditText test_title = (EditText) add_test_view.
findViewById(R.id.testTitle);
// Test title widget to hold title of test
}
});
String user_title = test_title.getText().toString();
Log.i(TAG, "onClick: " + user_title);
I've got a button that inserts user information into a database.
On top of this, I would like it to display the users entered details below in a list,
#Override
public void onClick(View v) {
insertuser();
LinearLayout createworkout = (LinearLayout)findViewById(R.id.createworkout);
TextView x = new TextView(getApplicationContext());
x.setText(editTextExercise.toString());
createworkout.addView(x);
}
This is what I have so far. When clicking the button the information is inserted, but I can not see a visible Textview. No errors are thrown either, I don't know what I have done wrong here.
All help appreciated
Thank you
Have your LinearLayout orientation property set?
try to add:
android:orientation="vertical"
or:
android:orientation="horizontal"
Try to change it as...
#Override
public void onClick(View v) {
insertuser();
LinearLayout createworkout = (LinearLayout)findViewById(R.id.createworkout);
TextView x = new TextView(YourActivity.this);
x.setText(editTextExercise.toString());
LayoutParams lp = new LayoutParams ( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
createworkout.addView(x,lp);
}
I have two EditText fields i.e name and marks and one Add button.
I have to display EditText values each and every time whenever Add button is clicked.
However,I am only able to display only one single value on listview.
When i clicked again on Add button,its previous value get erased and newer value gets displayed in listview.
I wanna populate whole list in listview.
public class MainActivity extends Activity {
EditText name1;
EditText marks1;
private ListView lv;
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
TextView markshee = (TextView)findViewById(R.id.textView3);
markshee.setText("");
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try{
name1 = (EditText)findViewById(R.id.editText1);
String name = name1.getText().toString();
marks1 = (EditText)findViewById(R.id.editText2);
String marks = marks1.getText().toString();
if(name.equals("") || marks.equals("")){
String str="Don't Leave any field blank !";
Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
TextView marksheet = (TextView)findViewById(R.id.textView3);
marksheet.setText("Marks Sheet");
marksheet.setTextColor(Color.BLUE);
TextView nam = (TextView)findViewById(R.id.textView4);
nam.setText("Name");
nam.setTextColor(Color.RED);
TextView mar = (TextView)findViewById(R.id.textView5);
mar.setText("Marks");
mar.setTextColor(Color.RED);
name1.setText("");
marks1.setText("");
lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(true);
ArrayList<String> data = new ArrayList<String>();
data.add(" "+name+" "+marks);
aa =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, data);
lv.setAdapter(aa);
}
}catch(Exception ex)
{
System.out.println(ex.getStackTrace());
}
}
});
}
#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_main, menu);
return true;
}
}
Try this:
you declare ArrayList is public otherwise it will create each and every time clicking and sotre last items only
public class MainActivity extends Activity {
EditText name1;
EditText marks1;
private ListView lv;
ArrayAdapter<String> aa;
ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
TextView markshee = (TextView)findViewById(R.id.textView3);
markshee.setText("");
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try{
name1 = (EditText)findViewById(R.id.editText1);
String name = name1.getText().toString();
marks1 = (EditText)findViewById(R.id.editText2);
String marks = marks1.getText().toString();
if(name.equals("") || marks.equals("")){
String str="Don't Leave any field blank !";
Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
TextView marksheet = (TextView)findViewById(R.id.textView3);
marksheet.setText("Marks Sheet");
marksheet.setTextColor(Color.BLUE);
TextView nam = (TextView)findViewById(R.id.textView4);
nam.setText("Name");
nam.setTextColor(Color.RED);
TextView mar = (TextView)findViewById(R.id.textView5);
mar.setText("Marks");
mar.setTextColor(Color.RED);
name1.setText("");
marks1.setText("");
lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(true);
data.add(" "+name+" "+marks);
aa =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, data);
lv.setAdapter(aa);
}
}catch(Exception ex)
{
System.out.println(ex.getStackTrace());
}
}
});
}
Instead of creating and initializing your data inside onClick, try initializing it in the onCreate method and inside onClick just add the new entry to it:
ArrayList<String> data = new ArrayList<String>();
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
.....
.....
.....
data.add(" "+name+" "+marks);
....
}
}
With your existing code, when your onClick method is called, you are creating a new list data every time and adding just a single entry to it, hence it displays only a single value.
UPDATE:
Lets see an example :
Lets say have a class from which I need to get incremental value on calling a method getIncrementValue that should return current value +1 every time I call it.
This is the code for it:
public class MyClass{
public int getIncrementValue(){
int a = 0;
a = a+1;
return a;
}
}
Now if I call this method like:
MyClass m = new MyClass();
System.out.println(m.getIncrementValue()); //prints 1
System.out.println(m.getIncrementValue()); //prints 1 should print 2 right
System.out.println(m.getIncrementValue()); //prints 1 should print 3 right
You see this, every time it prints only one value instead of incremented value.
This is beacuse every time I call getIncrementValue(), I am declaring and initializing a new variable a = 0 and incrementing it and returning it, hence every time it increments it to 1 and return 1 (instead of 2 and three and so on)
For this I need to change slighlty my class, declare variable a outside that method make it a class variable (in your case declare ArrayList<String> data = new ArrayList<String>(); just after the line ArrayAdapter<String> aa;)
public class MyClass{
int a = 0;
public int getIncrementValue(){
a = a+1;
return a;
}
}
Now if I call this method like:
MyClass m = new MyClass();
System.out.println(m.getIncrementValue()); //prints 1
System.out.println(m.getIncrementValue()); //prints 2 should print 2 right
System.out.println(m.getIncrementValue()); //prints 3 should print 3 right
Now you can uderstand why that happens with your code.
So try tweaking your code a little bit and it will be fine.
according to your question i have done something for you.. i have created two Edit text as name and marks and created two lists name as list and list2...and one add button... for run this code your min sdk version should be 11.. otherwise it will not work....when you enter value on edit text box and click on add button these value will be show on two different list and never erased the previous value..... follow my code...
MainActivity.java
package com.example.textview;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
EditText Name, Marks;
Button Add;
ListView lv, lv2;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayList<String> list2 = new ArrayList<String>();
ArrayAdapter<String> adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name=(EditText)findViewById(R.id.name);
Marks=(EditText)findViewById(R.id.marks);
Add=(Button)findViewById(R.id.add);
lv=(ListView)findViewById(R.id.list);
lv2=(ListView)findViewById(R.id.list2);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, list2);
lv2.setAdapter(adapter2);
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String name = Name.getText().toString();
String marks = Marks.getText().toString();
if(name.length() > 0 && marks.length() > 0)
{
list.add(name);
adapter.notifyDataSetChanged();
list2.add(marks);
adapter2.notifyDataSetChanged();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.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: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=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/textView2" >
</ListView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/list"
android:layout_marginTop="36dp"
android:text="Enter name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/list"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="15dp"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_marginLeft="28dp"
android:layout_toRightOf="#+id/textView1"
android:text="Enter marks"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#+id/list2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textView2" >
</ListView>
<EditText
android:id="#+id/marks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/name"
android:layout_alignLeft="#+id/textView2"
android:layout_alignRight="#+id/textView2"
android:ems="10" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:layout_marginTop="33dp"
android:layout_toRightOf="#+id/name"
android:text="ADD" />
</RelativeLayout>
and your min sdk version should be 11
So when I try and run my code in the emulator, the app background pops up then closes giving me the dialog, "Unfortunately, Callisto has stopped working"
I have no idea what is wrong other than it gives me a null pointer exception (line 49) but there is nothing at line 49
XML
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/callisto_heading" />
<Button
android:id="#+id/bClasses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Classes"
android:layout_gravity="center"
android:onClick=""
/>
<Button
android:id="#+id/bSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:layout_gravity="center"
android:onClick=""
/>
</LinearLayout>
Java
package android.callisto.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class CallistoActivity extends Activity {
/** Called when the activity is first created. */
Button settings_button;
Button classes_button;
Button home_button;
CheckBox notif_cb;
CheckBox math_cb;
CheckBox science_cb;
CheckBox ss_cb;
CheckBox english_cb;
CheckBox language_cb;
boolean notif,math,science,english,ss,language;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//settings layout
notif_cb = (CheckBox) findViewById(R.id.cbNotif);
math_cb = (CheckBox) findViewById(R.id.cbMath);
science_cb = (CheckBox) findViewById(R.id.cbScience);
ss_cb = (CheckBox) findViewById(R.id.cbSS);
english_cb = (CheckBox) findViewById(R.id.cbEnglish);
language_cb = (CheckBox) findViewById(R.id.cbLang);
home_button = (Button) findViewById(R.id.bHome);
notif = true;
math = true;
science = true;
english = true;
ss = true;
language = true;
home_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.main);
}
});
//notifications
//main layout
settings_button = (Button) findViewById(R.id.bSettings);
classes_button = (Button) findViewById(R.id.bClasses);
settings_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.settings);
}
});
}
}
FYI the app was loading last night.. Thanks for any help and please remember I am new to Android programming. Thank you.
the problem is here
home_button = (Button) findViewById(R.id.bHome);
in layout file there is no bHome
The problem probabaly is, that you are using the setContentView() for displaying different screens. You should not use this method for changing screens,you should use a different activitys for this.
Usually, you only set the contentView ONCE in the oncreate, per activity.
Your R.layout.main layout probabaly does not contain the 'home' button, but the r.layout.settings layout does.
First you are loading the main layout at this line: setContentView(R.layout.main); But since this layout file does NOT contain the home button, findViewById(R.id.bHome); will return null. After that, calling a method on this returned value, home_button.setOnClickListener(); in your case, will cause a NullPointerException.
What you should do is the following:
Create an activity for your main layout:
public class CallistoMainActivity extends Activity {
/** Called when the activity is first created. */
Button settings_button;
Button classes_button;
Button home_button;
CheckBox notif_cb;
CheckBox math_cb;
CheckBox science_cb;
CheckBox ss_cb;
CheckBox english_cb;
CheckBox language_cb;
boolean notif,math,science,english,ss,language;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//main layout
settings_button = (Button) findViewById(R.id.bSettings);
classes_button = (Button) findViewById(R.id.bClasses);
settings_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),
CallistoSettingsActivity.class));
}
});
}
And an activity for your Settings layout:
public class CallistoSettingsActivity extends Activity {
Button home_button;
CheckBox notif_cb;
CheckBox math_cb;
CheckBox science_cb;
CheckBox ss_cb;
CheckBox english_cb;
CheckBox language_cb;
boolean notif,math,science,english,ss,language;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
//settings layout
notif_cb = (CheckBox) findViewById(R.id.cbNotif);
math_cb = (CheckBox) findViewById(R.id.cbMath);
science_cb = (CheckBox) findViewById(R.id.cbScience);
ss_cb = (CheckBox) findViewById(R.id.cbSS);
english_cb = (CheckBox) findViewById(R.id.cbEnglish);
language_cb = (CheckBox) findViewById(R.id.cbLang);
home_button = (Button) findViewById(R.id.bHome);
notif = true;
math = true;
science = true;
english = true;
ss = true;
language = true;
home_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
//You could either use finish() to finish the current activity, and return to the previous CallistoMainActivity on the stack.
//Or you could simply start the main activity again by using the startActivity() method you see in the onclicklistener on the settings button.
}
});
}
What happens now, is when you click the settings button in the main activity, the settings activity will be shown. When you click the home button in the settings activity, the settings activity will be finished, and the user will be returned to the previous activity on the stack; which is the main activity.
Also do not forget to define the settingsactivity in your AndroidManifest.xml
EDIT: Another thing you should note, that if there is an error 'at line x' but there is nothing at line x in your code, then the code running on your Android device, is not the same as the code you are looking at in your editor. So that might be the reason it was running last night, but not anymore.