I have an activity, called AddItem, which contains a couple fields that the user fills out and I am now trying to pass them to another activity. I was able to get the first two fields by doing this:
String messageText = ((EditText) findViewById(R.id.inputName)).getText().toString();
String discriptionText = ((EditText) findViewById(R.id.description)).getText().toString();
The above code worked fun, but then I tried to get another value which I then cast to a double like so:
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
It's kind of long and complicated but I'm basically doing the same thing with the exception of parsing the String and converting it to a double value. I determined that this is the problem code because when I comment it out the rest of the app runs fine.
Here is my Activity:
public class AddItem extends AppCompatActivity {
EditText inputedTask, inputedDescription, inputedLatitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
inputedTask = (EditText) findViewById(R.id.inputName);
inputedDescription = (EditText) findViewById(R.id.description);
inputedLatitude = (EditText) findViewById(R.id.Latitude);
}
public void onSaveItemButton(View view) {
String messageText = ((EditText) findViewById(R.id.inputName)).getText().toString();
String discriptionText = ((EditText) findViewById(R.id.description)).getText().toString();
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
if (messageText.equals(""));
else {
Intent intent = new Intent();
intent.putExtra(Intent_Constant.INTENT_MESSAGE_FIELD, messageText);
setResult(Intent_Constant.INTENT_RESULT_CODE, intent);
finish();
}
}
}
You need to make a public method for the onClick, from the documentation:
Within the Activity that hosts this layout, the following method
handles the click event:
/** Called when the user touches the button */
public void sendMessage(View view) {
// Do something in response to button click
}
The method you declare in the android:onClick attribute must have a
signature exactly as shown above. Specifically, the method must:
Be public
Return void
Define a View as its only parameter (this will
be the View that was clicked)
So you need to change the method to public:
public void onSaveItemButton(View view) {
...
}
UPDATE:
As the error log says:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at cs4720.cs.virginia.edu.duysalahandroidminiproject02.AddItem.onSaveItemButton(AddItem.java:33)
You need to catch for empty string in the following code:
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
so, check it first:
String val = ((EditText) findViewById(R.id.Latitude)).getText().toString();
if(!val.equals("") {
double Latitude = Double.parseDouble(val);
}
You are calling onSaveItemButton method from a view that is not initialized. You must initialize btnChangeDate in the onCreate from the activity.
Check this answer
Related
Hello I want to have an Add function that allows me to input items to my GridView
For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView. I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.
My problem: I want to have an Add button that takes me to another XML-Layout/class and IDEALLY it input a single item and so when the user goes back to MainActivity the GridView would be updated along with the previous information that I currently hard-coded atm. This previous sentence doesn't work currently
Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters
//constructor - it takes the context and the list of words
WordAdapter(Context context, ArrayList<WordFolder> word){
super(context, 0, word);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
}
//Getting the current word
WordFolder currentWord = getItem(position);
//making the 2 text view to match our word_folder.xml
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(currentWord.getTitle());
TextView desc = (TextView) listItemView.findViewById(R.id.desc);
desc.setText(currentWord.getTitleDesc());
return listItemView;
}
}
Here is my NewFolder code. Which sets contentview to a different XML. it's pretty empty since I'm lost on what to do
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
//goes back to the MainActivity
Intent intent = new Intent(NewFolder.this, MainActivity.class);
startActivity(intent);
}
});
}
In my WordFolder class I made some TextView variables and save the strings to my ArrayList<> object but so far it's been useless since it doesn't interact with the previous ArrayList<> in ActivityMain which makes sense because its an entirely new object. I thought about making the ArrayList a global variable which atm it doesn't make sense to me and I'm currently lost.
Sample code would be appreciative but looking for a sense of direction on what to do next. I can provide other code if necessary. Thank you
To pass data between Activities to need to do a few things:
First, when the user presses your "Add" button, you want to start the second activity in a way that allows it to return a result. this means, that instead of using startActivity you need to use startActivityForResult.
This method takes an intent and an int.
Use the same intent you used in startActivity.
The int should be a code that helps you identify where a result came from, when a result comes. For this, define some constant in your ActivityMain class:
private static final int ADD_RESULT_CODE = 123;
Now, your button's click listener should looks something like this:
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this, NewFolder.class);
startActivityForResult(intent, ADD_RESULT_CODE);
}
});
Now for returning the result.
First, you shouldn't go back to your main activity by starting another intent.
Instead, you should use finish() (which is a method defined in AppCompatActivity, you can use to finish your activity), this will return the user to the last place he was before this activity - ActivityMain.
And to return some data, too, you can use this code:
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
where title and desc are the variables you want to pass.
in your case it should look something like this:
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
//goes back to the MainActivity
finish();
}
});
}
You should probably also take care of the case where the user changed his mind and wants to cancel adding an item. in this case you should:
setResult(Activity.RESULT_CANCELLED);
finish();
In your ActivityMain you will have the result code, and if its Activity.RESULT_OK you'll know you should add a new item, but if its Activity.RESULT_CANCELLED you'll know that the user changed their mind
Now all that's left is receiving the data in ActivityMain, and doing whatever you want to do with it (like adding it to the grid view).
To do this you need to override a method called onActivityResult inside ActivityMain:
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check the result code to know where the result came from
//and check that the result code is OK
if(resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE )
{
String title = data.getStringExtra("title");
String desc = data.getStringExtra("desc");
//... now, do whatever you want with these variables in ActivityMain.
}
}
I am trying to convert a value that has been passed through from another fragment. The convert method is inside an onClickListener which when clicked will make the conversion of the value passed through the fragment.
The values are currently being placed into TextViews on my second fragment. However when I try to make an if statement it won't enter the loop
Text Name is what my textView has been set to.
The code is here
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textName.equals("Miles") && textName2.equals("Kilometers")) {
String str1 = editText1.getText().toString();
double unittoConvert = Double.parseDouble(str1);
double convertedUnit = unittoConvert * 1.6;
String result = Double.toString(convertedUnit);
textName3.setText(result);
}
}
});
This is the code for the methods that are setting the unit selected in scroller and passing it through to the text view which is then displaying the selected unit. When i try to extract these values it wont work
PageViewModel.getName().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName.setText(s);
}
});
PageViewModel2.getName2().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName2.setText(s);
}
});
Use getText to extract text from TextView and then compare
textName.getText().equals("Miles") && textName2.getText().equals("Kilometers")
I'm writing a calculator on Android Studio, in Java, and the app crashes if the user call the result with a dot "." alone or let the EditText field in blank.
I'm looking for a solution for not allowing these two conditions happening, together or individualy, in each of the three fields.
I've already tried TextWatcher and if/else but without success.
The .xml file where the editText field are designed is already set for decimalNumber.
I've already tried this:
if(myfieldhere.getText().toString().equals(".")){myfieldhere.setText("0");}
For each "valor line" and else for the "finalresult" line if everything is fine. Both inside the setOnClickListener block. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.peso_layout);
result = findViewById(R.id.layresult);
conc = findViewById(R.id.layconc);
dose = findViewById(R.id.laydose);
peso = findViewById(R.id.laypeso);
calc = findViewById(R.id.laycalcpeso);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
});
}
The ideal output should be the app not crashing if these two conditions happen and sending an error message to the user that input is invalid.
What i'm receiving is the app crashing.
Thank you very much. I'm very beginner in Java and I'm few days struggling with this.
Dear Friend, Your directly trying to convert string input into float and then after your check value but do your code like Below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText edt1,edt2;
TextView txtans;
Button btnsum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt1=findViewById(R.id.edt1);
edt2=findViewById(R.id.edt2);
txtans=findViewById(R.id.txtans);
btnsum=findViewById(R.id.btnsum);
btnsum.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.btnsum){
float n1,n2;
String value1=edt1.getText().toString();
String value2=edt2.getText().toString();
if(value1.equals("") || value1.equals(".")){
n1=0;
}else {
n1= Float.parseFloat(value1);
}
if(value2.equals("")|| value2.equals(".")){
n2=0;
}else{
n2= Float.parseFloat(value2);
}
float ans=n1+n2;
txtans.setText(ans+"");
}
}
}
See In above code, First get value from edittext and then check wheather it contain null or "." inside it. if it contains then store 0.0 value in some variable. then after make sum and display in textbox.
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String myvalor = myfieldhere.getText().toString();
if(myvalor.equals(".") || myvalor.isEmpty())
{
// toast error : incorrect value
return;
}
try
{
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
catch(Exception exp){// toast with exp.toString() as message}
}
});
use TextUtils for check empty String its better
if(TextUtils.isEmpty(peso.getText().toString())||
TextUtils.isEmpty(conc.getText().toString())||
TextUtils.isEmpty(dose.getText().toString())){
return;
}
I just started reading Head First Android Development and I'm little confused about the code in chapter 3.
The first activity CreateMessageActivity is sending an intent to the second activity ReceiveMessageActivity, so far so good.
public class CreateMessageActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_message);
}
// Call this when the button is clicked
public void onSendMessage(View view)
{
EditText messageView = (EditText)findViewById(R.id.message);
String messageText = messageView.getText().toString();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, messageText);
String chooserTitle = getString(R.string.chooser);
Intent chosenIntent = Intent.createChooser(intent, chooserTitle);
startActivity(chosenIntent);
}
}
The second activity ReceiveMessageActivity gets the intent from the first activity CreateMessageActivity.
public class ReceiveMessageActivity extends Activity
{
public static final String EXTRA_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_message);
Intent intent = getIntent();
String messageText = intent.getStringExtra(EXTRA_MESSAGE);
TextView messageView = (TextView)findViewById(R.id.message);
messageView.setText(messageText);
}
}
I can't understand the constant EXTRA_MESSAGE. If I change "message" to something like "asdfwerf324wd23" the code will still compile and run without problems. Even if I remove the constant EXTRA_MESSAGE and give intent.getStringExtra a random "name", the app will work fine. What's the purpose of this constant?
I have to mention that I'm somewhat new to Android/Java programming and I'm trying to understand the connections between the classes.
The constant defines the key to look for in the bundle.
Bundles are basically (at the core) maps containing a key with an associated value. If a key doesn't exist, null is returned. Meaning if nothing is passed with a given value of the key, the method get[type]Extra returns null.
You can set null as the text to a TextView without it throwing any exceptions. In the TextView code, the String is set to "" if it's null. So essentially:
String messageText = intent.getStringExtra(EXTRA_MESSAGE);//this ends up being null
TextView messageView = (TextView)findViewById(R.id.message);
messageView.setText(messageText);//and this sets the text to ""
The reason it works no matter which key you pick is because it returns null. If you don't send anything with that key though, it'll never have an actual value when you retrieve it, and the TextView will be empty
So I managed to take 4 different activities involving 4 variables and wrote them in this kind of format:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step1);
Button c = (Button) this.findViewById(R.id.continue1);
final EditText input = (EditText) findViewById(R.id.enterscore);
input.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String score1 = input.getText().toString();
Double.parseDouble(score1);
{ Intent myintent = (new Intent(step1.this,step2.class));
myintent.putExtra("SCORE1",score1);
startActivity(myintent);
}
On my final activity the one that's suppose to display the solution I have coded the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
}
public void solutionf(View v) {
Bundle extras = getIntent().getExtras();
if(extras!=null){
double score1 = extras.getDouble("SCORE1");
double score2 = extras.getDouble("SCOREF");
double l2 = extras.getDouble("L2");
double l3= extras.getDouble("L3");
double solution= (((score2-score1)/l2)*l3);
String resultString = "Result:" +solution;
TextView resultText= (TextView) findViewById(R.id.solution);
resultText.setText(resultstring);
}
}
}
Why won't the final solution display? I've checked over to make sure everything matches up in terms of the doubles that are set in the activities. Could it be I didn't properly bring the variables over from the previous activities through error on my code?
Any help to getting the solution to show would be appreciated!
Unless a part of your code is missing, solution() is never called.
Add a call to this function in onCreate of your second activity, it should help.