For some reason my username and password variables are red. When I define them as strings I get errors which say that they cannot be cast from edit text....Is there any way to actually fix this? It's irritating because I'm working from a tutorial verbatim and they appear to not have these issues. I have already tried doing various things such as turning password and username to Strings. It's just not working properly.
Here is what I've tried so far. I just want this simply login/signup code to work. (Code Updated)
package myapplication.example.com.cis490_project;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class loginactivity extends AppCompatActivity {
Button loginButton;
Button signUpButton;
EditText usernameField;
EditText passwordField;
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginactivity);
loginButton = (Button) findViewById(R.id.btlogin);
signUpButton = (Button) findViewById(R.id.btsignup);
usernameField = (EditText) findViewById(R.id.tusername);
passwordField = (EditText) findViewById(R.id.tpassword);
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
Parse.initialize(this, "SECRET_KEY", "SECRET_KEY");
ParseObject testObject = new ParseObject("Testing");
testObject.put("foo", "badr");
testObject.saveInBackground();
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
username = usernameField.getText().toString();
password = passwordField.getText().toString();
ParseUser.logInInBackground(username, password, new LogInCallback() {
public void done(ParseUser user, com.parse.ParseException e) {
if (user != null) {
//start next activity
//start sinch service
} else {
Toast.makeText(getApplicationContext(),
"There was an error logging in.",
Toast.LENGTH_LONG).show();
}
}
});
}
});
signUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
username = usernameField.getText().toString();
password = passwordField.getText().toString();
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password);
user.signUpInBackground(new SignUpCallback() {
public void done(com.parse.ParseException e) {
if (e == null) {
//start next activity
//start sinch service
} else {
Toast.makeText(getApplicationContext(),
"There was an error signing up."
, Toast.LENGTH_LONG).show();
}
}
});
}
});
}
#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_loginactivity, 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);
}
}
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="myapplication.example.com.cis490_project.loginactivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/btlogin"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Password"
android:id="#+id/tpassword"
android:layout_above="#+id/btlogin"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Username"
android:id="#+id/tName"
android:layout_above="#+id/tpassword"
android:layout_alignLeft="#+id/tpassword"
android:layout_alignStart="#+id/tusername"
android:layout_marginBottom="40dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/iprofile"
android:src="#drawable/com_facebook_profile_picture_blank_square"
android:layout_above="#+id/tName"
android:layout_alignRight="#+id/btlogin"
android:layout_alignEnd="#+id/btlogin"
android:layout_marginBottom="56dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Signup"
android:id="#+id/btsignup"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Define all your widgets after setContentView inside onCreate. And define username and password as String variables. Because You did not define username and password anywhere in your code.
public class loginactivity extends AppCompatActivity {
Button loginButton;
Button signUpButton;
EditText usernameField;
EditText passwordField;
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginactivity);
loginButton = (Button) findViewById(R.id.btlogin);
signUpButton = (Button) findViewById(R.id.btsignup);
usernameField = (EditText) findViewById(R.id.tusername);
passwordField = (EditText) findViewById(R.id.tpassword);
//rest of your code
..............
}
Related
I am trying to grab male female text from this radio button, but it give me a null pointer exception, and I am just stuck at every point of trying to fix that whether storing the text as another variable entirely or whatever. This is using firebase as it's backend, so maybe this is just a new quirk in irebase not to allow this.
package io.github.anoobishnoob.barker;
import android.content.Intent;
import android.nfc.Tag;
import android.renderscript.Sampler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Logger;
public class RegistrationActivity extends AppCompatActivity {
//TODO: fix nullpointer eexception on line 64-67
private Button mRegister;
private EditText mEmail, mPassword, mName;
private RadioGroup mRadioGroup;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mRegister = (Button) findViewById(R.id.register);
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mName = (EditText) findViewById(R.id.name);
mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
Log.d("test debug mRadioGroup", mRadioGroup.toString());
mRegister.setOnClickListener(new View.OnClickListener() {
int selectId = mRadioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = (RadioButton) findViewById(selectId);
//String radioButtonValue = String.valueOf(radioButton.getText());
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
final String name = mName.getText().toString();
Log.d("test debug", mRadioGroup.toString());
//Log.d("test debug", radioButton.toString());
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(RegistrationActivity.this, "sign up error", Toast.LENGTH_SHORT);
}
else{
String userId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserDb = FirebaseDatabase
.getInstance()
.getReference()
.child("Users")
.child(radioButton.toString()).child(userId).child("name");
currentUserDb.setValue(name);
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="io.github.anoobishnoob.barker.RegistrationActivity"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="name"
android:id="#+id/name"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radioGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>
</RadioGroup>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"
android:id="#+id/email"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="password"
android:id="#+id/password"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="register"
android:id="#+id/register"/>
</LinearLayout>
Firstly give id to both RadioButton.
And after that, you can use it like below
int rid = mRadioGroup.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(rid);
String radioText = rb.getText().toString();
Instead of radioButton.toString() use radioButton.getText().toString();
How to I hide the next button and will only show when the user choose a radio group button
I have this 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">
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/assembly"
android:checked="false"
/>
<RadioButton
android:id="#+id/csharp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/java"
android:checked="false" />
<Button
android:id="#+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NEXT"
android:onClick="OnClick"
/>
</RadioGroup>
</LinearLayout>
and this class code
package com.example.quiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
/**
* Created by leste on 3/5/2016.
*/
public class CS_Category extends Activity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_category);
addListenerOnButton();
}
public void addListenerOnButton() {
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = (RadioButton) findViewById(selectedId);
if (radioSexButton.getId() == R.id.assembly) {
Intent i = new Intent(CS_Category.this, CS_Assembly.class);
startActivity(i);
} else {
if (radioSexButton.getId() == R.id.csharp) {
Intent i = new Intent(CS_Category.this, CS_Csharp.class);
startActivity(i);
} else {
if (radioSexButton.getId() == R.id.java) {
Intent i = new Intent(CS_Category.this, CS_Java.class);
startActivity(i);
}
}
Toast.makeText(CS_Category.this,
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
What should I do to hide the next button and show only if there is a selected radio button
In your button xml you should use:
android:visibility="gone"
In java you should use:
btnDisplay.setVisibility(View.VISIBLE);
First of all I would take the button out of the radio group and just have it be below it. Then in my java code I would have this function:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.assembly:
if (checked)
make_button_visible();
break;
case R.id.csharp:
if (checked)
make_button_visible();
break;
}
}
Make sure that each radio button has onClick="onRadioButtonClicked" set.
Then have a function called make_button_visible() that has these lines:
Button mButton=(Button)findViewById(R.id.btnDisplay);
mButton.setVisibility(View.VISIBLE);//This will make it visible
add below code in your onCreate method
addListenerOnButton();
btnDisplay.setVisibility(View.INVISIBLE);
radioSexGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if (btnDisplay.getVisibility() == View.INVISIBLE)
btnDisplay.setVisibility(View.VISIBLE);
}
});
I'm learning to use the external class. This project is just an example. I have a class that extends Activity and in this class I want to access my Login button. And the Login Button will run the external class that implements OnClickListener in OnClickListenerLogin().
In OnClickListenerLogin I want to get EditText value in Login.xml. But whenever I call it, the value returns "".
What's missing from my code and what is the right code for my OnClickListenerLogin so I can get the EditText value in Login.xml?
Login.xml
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
tools:context="com.example.phonekiosk.LoginActivity" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<!-- Login Form -->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip">
<!-- Email Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Username"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="20dip"
android:singleLine="true"
android:id="#+id/txtUsername"/>
<!-- Password Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Password"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:singleLine="true"
android:password="true"
android:id="#+id/txtPassword"/>
<!-- Login Button -->
<Button
android:id="#+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Login" />
</LinearLayout>
<!-- Login Form Ends -->
</RelativeLayout>
</ScrollView>
PhoneKiosk.java
package com.example.phonekiosk;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListenerLogin());
}
}
OnClickListenerLogin.java
package com.example.phonekiosk;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.EditText;
import android.widget.Toast;
public class OnClickListenerLogin implements OnClickListener {
#Override
public void onClick(View view) {
final Context context = view.getContext();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View formLogin = inflater.inflate(R.layout.login, null);
final EditText txtUsername = (EditText) formLogin.findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText) formLogin.findViewById(R.id.txtPassword);
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}
You are not using the same view as that created by LoginActivity.
Your code that inflates the view in onClick need to be removed.
You can pass the reference to EditText of user name & password to your OnClickListenerLogin by implementing a constructor for it.
public class OnClickListenerLogin implements OnClickListener {
private EditText txtUsername;
private EditText txtPassword;
public OnClickListenerLogin (EditText userEditText, EditText passwordEditText) {
this.txtUsername = userEditText;
this.txtPassword = passwordEditText;
}
#Override
public void onClick(View view) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}
In the login activity, you can do following
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(
new OnClickListenerLogin(
(EditText) findViewById(R.id.txtUsername),
(EditText) findViewById(R.id.txtPassword));
}
Disclaimer: I have entered the code directly here, not checked for compilation issue due to typo. I hope you get the essence of the solution
no need of external class here
you can simply set onClickListener to your login button and perfrom your action in onClick method.
public class LoginActivity extends Activity {
Button btnLogin;
EditText txtUsername,txtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
txtUsername = (EditText) findViewById(R.id.txtUsername);
txtPassword = (EditText) findViewById(R.id.txtPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
// your action here
}
});
}
}
One solution would be to simple make the onClickListener a inner class of your Login Class
public class LoginActivity extends Activity {
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
............
}
//inner class
class OnClickListenerLogin implements OnClickListener {
.........
}
}//Login class ends
Inner classes exist primarily to solve these kind of problems , try reading about them .
this is very simple so you should proceed like below for getting the value from edittext.
public class LoginActivity extends Activity implements OnClickListener{
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUsername = (EditText) formLogin.findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText) formLogin.findViewById(R.id.txtPassword)
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListenerLogin());
}
public click(View view)
{
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}
No matter how much I edit or change to my Java code for this assignment, it refused to properly update the value of the integer variable I've set for the result. Can someone show me what on earth I'm missing here? Below is my code:
package com.example.minicalc;
import com.example.minicalc.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class MainActivity extends Activity implements OnEditorActionListener {
private static final String TAG = "MiniCalc";
private SharedPreferences savedValues;
private EditText editText1;
private EditText editText2;
private Button button1;
private Spinner spinner1;
private TextView answerLbl;
private int ivalue1 = 0;
private int ivalue2 = 0;
private int ianswer;
private int spinChoice;
//private String[] spinner_strings = {"+", "-", "×", "÷"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate event started");
setContentView(R.layout.activity_main);
spinner1 = (Spinner) findViewById(R.id.spinner1);
button1 = (Button) findViewById(R.id.button1);
answerLbl = (TextView) findViewById(R.id.answerTxt);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
editText1.setOnEditorActionListener(this);
editText2.setOnEditorActionListener(this);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
spinChoice = spinner1.getSelectedItemPosition();
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.d(TAG, "onClick event started");
ianswer = 0;
if (spinChoice == 0) {
ianswer = ivalue1 + ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 1) {
ianswer = ivalue1 - ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 2) {
ianswer = ivalue1 * ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
} else if (spinChoice == 3) {
ianswer = ivalue1 / ivalue2;
Log.d(TAG, "ianswer VALUE IS: " + Integer.valueOf(ianswer).toString());
}
answerLbl.setText(Integer.toString(ianswer));
//answerLbl.setText(""+ianswer);
Log.d(TAG, "answerLbl TEXT IS: " + answerLbl.getText());
}
});
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.d(TAG, "onEditorAction event started");
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
ivalue1 = Integer.parseInt(editText1.getText().toString());
ivalue2 = Integer.parseInt(editText2.getText().toString());
}
return false;
}
#Override
public void onPause() {
Log.d(TAG, "onPause event started");
Editor editor = savedValues.edit();
editor.putString("value1", editText1.getText().toString());
editor.putString("value2", editText2.getText().toString());
editor.commit();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume event started");
editText1.setText(savedValues.getString("value1", ""));
editText2.setText(savedValues.getString("value2", ""));
}
}
Here is my layout XML, activity_main.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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="com.example.minicalc.MainActivity" >
<TextView
android:id="#+id/valLbl1"
android:labelFor="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="40dp"
android:text="#string/valueLbl1" />
<TextView
android:id="#+id/valLbl2"
android:labelFor="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl1"
android:layout_below="#+id/editText1"
android:layout_marginTop="24dp"
android:text="#string/valueLbl2" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl1"
android:layout_below="#+id/valLbl1"
android:layout_marginTop="20dp"
android:ems="5"
android:inputType="number">
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/valLbl2"
android:layout_below="#+id/valLbl2"
android:layout_marginTop="16dp"
android:ems="5"
android:inputType="number" />
<TextView
android:id="#+id/answerTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/answerLblTxt"
android:layout_centerHorizontal="true"
android:ems="7"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/submit" />
<TextView
android:id="#+id/answerLblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/editText2"
android:layout_below="#+id/button1"
android:layout_marginTop="16dp"
android:text="#string/answerLbl" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/valLbl2"
android:layout_marginStart="28dp"
android:layout_toEndOf="#+id/editText2"
android:entries="#array/spinner_strings" />
</RelativeLayout>
Now, the app runs fine, the LogCat messages show up fine...except when I put them in the onClickListener. So yes, I've sorta identified WHERE the problem is, I just don't know WHAT the problem is. I'd show a screen shot of the error, but this is my first time posting. In any case, the phone I'm running the app on is a Samsung Galaxy Note 3, running Android 4.4.4. Can anyone help me?
Your spinners getSelectedItemPoisition() method is only called once in your onCreate() method and it is not called every time you click on the button, resulting in the value never being updated.
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
spinChoice = spinner1.getSelectedItemPosition();
...
}
This line of code needs to be added in the onClick() method causing the new value to be read on button click.
I'm having some issues with my school project. I can't get the text from the textbox. I searched for a solution but nothing found.. I'll be grateful if somebody help me :)
So here is my Java code:
package com.src.vicnote;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;
public class NewNoteActivity extends ActionBarActivity {
Button saveButton;
EditText textData;
Context context;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
//text = "this is sparta!";
Log.d("ADebugTag", "string: \"" + text + "\" end of note text");
new SaveClass(text/*, context.getApplicationContext()*/);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_note, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new_note,
container, false);
return rootView;
}
}
}
And my XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.src.vicnote.NewNoteActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonSave"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Save" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
Also I want to ask you what will happen if the text is cyrillic? Will be there any problem?
Try initializing textData outside of your OnClickListener:
textData = (EditText) findViewById(R.id.editText);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() { //...
I was also stuck at finding method to get text from edittext. I got resolved this issue by doing the below,
String selQuantity = (((TextView)findViewById(R.id.etxtQuantity)).getText()).toString();
Try this. It works.