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);
}
}
Related
I am trying to get radio button value on click of a button but it is showing red line error below this line:
I want to know why this error is showing as I am unable to understand.
radioSexButton = (RadioButton)findViewById(selectedId);
inconvertible types,cannot cast android.view.view to RadioButton
Below is my code:
XML code:
<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=".RadioButton"
android:padding="20dp">
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:checked="true" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
<Button
android:id="#+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display" />
JAVA code:
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
public class RadioButton extends AppCompatActivity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button);
radioSexGroup = findViewById(R.id.radioSex);
btnDisplay = findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = (RadioButton)findViewById(selectedId);
// find the radiobutton by returned id
Toast.makeText(getApplicationContext(),
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Someone please let me know how to resolve this issue any help would be appreciated.
THANKS
According to the exception message you're getting it appears to be an issue with casting the view returned by findViewById(int). Try the following steps below;
Rename your activity so that it's name doesn't clash with the view's type
Don't cast the return value of findViewById(int). It will automatically do that for you based on the type of your variable.
Make sure you have the correct imports.
After taking the above steps the resulting activity should be like below
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton; // this is the important part
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
// activity name changed!
public class RadioButtonActivity extends AppCompatActivity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioSexGroup = findViewById(R.id.radioSex);
btnDisplay = findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = findViewById(selectedId);
// find the radiobutton by returned id
Toast.makeText(getApplicationContext(),
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
You're encountering the issue because you're attempting to cast the return value of findViewById(int) into "RadioButton" which in your code is referring to the activity instead of android.widget.RadioButton
change your code to below code
private View radioSexButton; //make View
int radioButtonID = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = radioSexGroup.findViewById(radioButtonID);
My app doesn't response when i type
Android app project that has two (2) text fields and one (1) button. The button will
compare the input from the text fields and display a response (SAME if values are the same
and NOT THE SAME if they are not) if it is clicked. You may need to create a new activity
for this.
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button checkbtn = (Button)findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
Here is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:id="#+id/checkButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/firsttextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="" tools:targetApi="o" />
<EditText
android:id="#+id/secondtextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:importantForAutofill="no"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firsttextEditText" />
<Button
android:id="#+id/checkBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/secondtextEditText" />
</androidx.constraintlayout.widget.ConstraintLayout>
first of all, you can't compare two EditText references together to get the result of text values equality.
you can get the text wrote in the editText using getText() method
then start to compare both strings values.
also, I suggest declaring EditText out of scope setOnClickListener so that not declare new instances every time the user click button.
so your final java code can be like :
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
Button checkbtn = (Button) findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstValue = firstttextEditText.getText().toString();
String secondValue = secondtextEditText.getText().toString();
if (firstValue.equals(secondValue)) {
Intent sameTextIntent = new Intent(getApplicationContext(), SameText.class);
startActivity(sameTextIntent);
} else {
Intent notsameTextIntent = new Intent(getApplicationContext(), NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
I suggest you learn more about EditText from here
you are comparing the EditText, not the text inside the edit text. maybe change your codes to something like this.
String firstttextEditText = findViewById(R.id.firsttextEditText)).getText().toString();
String secondtextEditText = findViewById(R.id.secondtextEditText).getText().toString();
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}
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();
first activity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button bt1;
private Button bt2;
private EditText ed1;
private EditText ed2;
private TextView tv3;
static ArrayList<String> s = new ArrayList<>();
static ArrayList<Integer> i = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button)findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
bt2 = (Button)findViewById(R.id.button2);
tv3 = (TextView)findViewById(R.id.textView3);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
s.add(ed1.getText().toString());
i.add(Integer.parseInt(ed2.getText().toString()));
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(MainActivity.this, second.class);
intent.putExtra("key", s);
startActivity(intent);
}
catch(Exception e) {
tv3.setText(e.getMessage());
}
}
});
}
}
Second activity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.widget.TextView;
import java.util.ArrayList;
public class second extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tv1 = (TextView)findViewById(R.id.textView);
tv2 = (TextView)findViewById(R.id.textView2);
ArrayList<String> s = (ArrayList<String>)getIntent().getSerializableExtra("key");
for(int j=0;j<=s.size();j++) {
tv1.setText(s.get(j));
}
}
}
I don't understand the problem in this code. when I click on bt2 to pass the ArrayList from on activity to another then the app just shutdown. I am not able to understand the problem in this code.
Please help me,
I have also updated the manifest.xml for second class.
Are you sure
i.add(Integer.parseInt(ed2.getText().toString()));
in the onClick() call doesnt throw an Exception?
Use a try-catch block around your code in Listener.onClick().
Btw., you can easily use Lambda Exrpessions for ActionListeners.
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Please use following construct:-
While Sending:
intent.putStringArrayListExtra("key", s)
While Receiving:
ArrayList<String> s = getIntent().getStringArrayListExtra("key");
Replace your for loop with below, use j< s.size and not j<=s.size
for(int j=0;j<s.size();j++)
{
tv1.setText(s.get(j));
}
You can do like this :
Bundle info= new Bundle();
ArrayList<Product> mas = new ArrayList<Product>();
info.putSerializable("product", mas);
intent.putExtras(info);
And get the values with this:
ArrayList<Product> prod = getIntent().getSerializableExtra(key);
Product class like a serializable object
private class Product implements Serializable {
}
Here it is just how you can pass arraylist between activities.Hope you wil get an idea to solve your issues.
intent.putExtra("key", s);-- this is wrong, you are sending a string but not your arrayList
Try sending with-- intent.putStringArrayListExtra("key", s);
and receiving -- ArrayList<String> stringArray = getIntent().getStringArrayListExtra("key");
hope this will solve your problem...
In your second activity onCreate, add the following code:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
// Add view
// Must add check extras if null.
Bundle extras = getIntent().getExtras();
ArrayList<String> s = extras.getStringArrayListExtra("key");
// do something
}
In your first activity, send intent with:
Intent intent = new Intent(MainActivity.this, second.class);
intent.putStringArrayListExtra("key", s);
startActivity(intent);
I've tried an sample app with your code. Hope this will help you.
Kindly check my codes.
First Activity
package com.arindam.testapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class FirstActivity extends AppCompatActivity {
Button bt1;
EditText ed1;
EditText ed2;
TextView tv3;
ArrayList<String> s = new ArrayList<>();
ArrayList<String> i = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
bt1 = (Button)findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
tv3 = (TextView)findViewById(R.id.textView);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
s.add(ed1.getText().toString());
i.add(ed2.getText().toString());
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("key", s);
intent.putExtra("value", i);
startActivity(intent);
}
catch(Exception e)
{
tv3.setText(e.getMessage());
}
}
});
}
}
First Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#679667"
android:orientation="vertical"
tools:context="com.arindam.testapp.FirstActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
</LinearLayout>
Second Activity
package com.arindam.testapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
tv1 = (TextView)findViewById(R.id.textView);
tv2 = (TextView)findViewById(R.id.textView2);
ArrayList<String> s = getIntent().getStringArrayListExtra("key");
for(int j=0;j<s.size();j++)
{
tv1.setText(s.get(j));
}
ArrayList<String> i = getIntent().getStringArrayListExtra("value");
for(int k=0;k<i.size();k++)
{
tv2.setText(i.get(k));
}
}
}
Second Activity Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#229597"
android:orientation="vertical"
tools:context="com.arindam.testapp.SecondActivity">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</LinearLayout>
If you want to work with key value pairs, go for hashMap.
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
..............
}