null return Intent on android programming - java

I write a simple program in android studio and create an object from Intent.
but i don't know why it return null ??
in the MainActivity.java I send userName and password to ProfileActivity.java.but Log.i shows null!
but Token is not null
com.example.sayres.myapplication2.ProfileActivity: onCreate User Name:
null Password: null Token: 22546874569
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String INTENT_USER_NAME_KYE = "user_name_key";
public static final String INTENT_USER_PASSWORD_KYE = "password_key";
protected final String TAG = "====>";
private EditText editTextUserName, editTextPassword;
private Button buttonLogin, buttonExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLogin:
getUserInfo();
break;
case R.id.btnExit:
finish();
break;
}
}
private void initView() {
editTextUserName = (EditText) findViewById(R.id.editUserName);
editTextPassword = (EditText) findViewById(R.id.editPassword);
buttonExit = (Button) findViewById(R.id.btnExit);
buttonLogin = (Button) findViewById(R.id.btnLogin);
buttonLogin.setOnClickListener(this);
buttonExit.setOnClickListener(this);
}
private void getUserInfo() {
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
editTextUserName.setText("");
editTextPassword.setText("");
String msg = "";
if (userName.isEmpty() || password.isEmpty()) {
msg = "Insert UserName And Password !!!";
} else {
msg = "Welcome " + userName;
// TODO: 1/7/2017 go to ProfileActivity !!!
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra("INTENT_USER_NAME_KYE", userName);
intent.putExtra("INTENT_USER_PASSWORD_KYE", password);
Bundle bundle = new Bundle();
bundle.putString("user_token", "22546874569");
intent.putExtras(bundle);
startActivity(intent);
finish();
}
Log.i(TAG, "UserName= " + userName + "\t" + "Password= " + password);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
}
ProfileActivity.java:
public class ProfileActivity extends AppCompatActivity {
private static final String TAG = ProfileActivity.class.getName();
private TextView textViewUserName, textViewPassword, textViewAge, textViewSex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// initviews();
Intent intent = getIntent();
String userName = intent.getStringExtra(MainActivity.INTENT_USER_NAME_KYE);
String password = intent.getStringExtra(MainActivity.INTENT_USER_PASSWORD_KYE);
// System.out.println("User Name iS:"+userName);
Bundle extras = intent.getExtras();
String user_token = extras.getString("user_token");
Log.i(TAG, "onCreate " + "User Name: " + userName + " Password: " + password + " Token: " + user_token);
}

intent.putExtra("INTENT_USER_NAME_KYE", userName);
intent.putExtra("INTENT_USER_PASSWORD_KYE", password);
You're using a literal "INTENT_USER_NAME_KYE" as the intent key, not the value of the INTENT_USER_NAME_KYE field you're using for reading the extras:
String userName = intent.getStringExtra(MainActivity.INTENT_USER_NAME_KYE);
String password = intent.getStringExtra(MainActivity.INTENT_USER_PASSWORD_KYE);
Remove the ".

Bundle bundle = new Bundle();
bundle.putString("user_token", "22546874569");
intent.putExtras(bundle);
above code removing intent values(extra values) which you set in intent so you should always choose either intent or bundle to pass your data to another activity.
try with below code it should work
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra("INTENT_USER_NAME_KYE", userName);
intent.putExtra("INTENT_USER_PASSWORD_KYE", password);
intent.putExtra("user_token", "22546874569");
startActivity(intent);

Related

How to Get String Value to Another Class in Andriod?

I have created a signup form linked with Firebase. Onclick Signup button generated an unique id which I have later stored in
String str = userid;
But now I want to pass this String str value back into my main activity so that I can get that unique id and can later on use in my other code.
I have tried many methods like bundle and passing string through intent but I'm getting nothing. Please help me resolving this issue.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignIn = (Button) findViewById(R.id.sign_in_button);
btnSignUp = (Button) findViewById(R.id.sign_up_button);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputNumber = (EditText) findViewById(R.id.number);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnResetPassword = (Button) findViewById(R.id.btn_reset_password);
btnResetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignupActivity.this, ResetPasswordActivity.class));
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("users");
final String userid = reference.push().getKey();
final String name = inputName.getText().toString().trim();
final String email = inputEmail.getText().toString().trim();
final String Number = inputNumber.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
Toast.makeText(getApplicationContext(), "Enter your name!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(Number)) {
Toast.makeText(getApplicationContext(), "Enter mobile number!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
final UserHelperClass helperClass = new UserHelperClass(name, email,Number,password,userid);
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
String str = userid;
reference.child(userid).setValue(helperClass);
startActivity(new Intent(SignupActivity.this, Home.class));
finish();
}
}
});
}
});
}
You can use SharedPreferences API to save this string to an XML file in the second activity and read it from the same XML file in the MainActivity.
To save the string:
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", 0);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString("key", userid);
editor.apply();
To retrieve the string:
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", 0);
String userid = sharePreferences.getString("key", "NOT FOUND");
You can read more about SharedPreferences here
You can start your second activity saying startActivityForResult
(See here), this way you can pass strings, numbers... back to the MainActivity from where you started your second activity once your second activity finishes.
Like
First Activity:
Intent i = new Intent(getApplicationContext(), yourSecondActivity.class);
i.putExtra("name", "value");
startActivityForResult(i, requestCode);
Second activiy:
Intent output = new Intent();
output.putExtra("name", "value");
setResult(RESULT_OK, output);
finish();
To recieve output in first Activity
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
String value = data.getStringExtra("name");

How to get data from text view in first activity and post it from another activity?

I want the data of textview in the second activity to pass in the third but i dont want to display it in the third activity. I want to directly send the data from the second activity to Pass in my sql db after clicking the button in the final activity. Is is achievable?
This is my first activity.
public class MainActivity extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN ="http://192.168.1.83/Attendance/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading= findViewById(R.id.loading);
email = findViewById(R.id.editTextUserEmail);
password = findViewById(R.id.editTextPassword);
btn_login = findViewById(R.id.buttonRegister);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPassword.isEmpty()) {
Login(mEmail, mPassword);
}else{
email.setError("Please Enter Email");
password.setError("Please Enter Password");
}
}
});
}
private void Login(final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("JSON", jsonObject.toString());
String success = jsonObject.getString("success");
JSONArray jsonArray =
jsonObject.getJSONArray("login");
if (success.equals("1"))
{
for (int i = 0; i<jsonArray.length(); i++){
JSONObject object =
jsonArray.getJSONObject(i);
String name =
object.getString("name").trim();
String email =
object.getString("email").trim();
// Toast.makeText(MainActivity.this,
"Success Login \nYour name: "+name+"\nYour Email: "+email,
// Toast.LENGTH_LONG).show();
Intent intent = new
Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("name",name);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Error"
+e.toString(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error"
+error.toString(),
Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
This is my second activity
public class HomeActivity extends AppCompatActivity {
private TextView name,email;
private TextView welcome;
private Button Send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
Send = findViewById(R.id.btn_send);
welcome = findViewById(R.id.welcome);
final Intent intent = getIntent();
String extraName = intent.getStringExtra("name");
String extraEmail = intent.getStringExtra("email");
name.setText(extraName);
email.setText(extraEmail);
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(HomeActivity.this,StatusActivity.class);
intent1.putExtra("wel", welcome.getText().toString());
intent1.putExtra("name1", name.getText().toString());
intent1.putExtra("email1", email.getText().toString());
startActivity(intent1);
}
});
}
And this is my final activity but Here i dont want to show the text view i just want to post it from here.
public class StatusActivity extends AppCompatActivity {
private TextView welcome, name, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
welcome = findViewById(R.id.abcd);
name = findViewById(R.id.name1);
email = findViewById(R.id.email1);
final Intent intent = getIntent();
String extraName1 = intent.getStringExtra("name1");
String extraEmail1 = intent.getStringExtra("email1");
String extraWelcome = intent.getStringExtra("wel");
name.setText(extraName1);
email.setText(extraEmail1);
welcome.setText(extraWelcome);
}
Your question is pretty clear until you put MySql to the topic. Why you want to pass the data from one activity to another through the database. Why involve database operations which take time and resources.
You may pass data from one activity to another through Intents (primitive values, Strings and Parcelables)!
All you have to do is:
Get the data (int your case from TextView).
Create the Intent to navigate to the next Activity.
Put the data to the Intent.
Start the Activity.
Retrieve the data from the Intent.
For example if will navigate to the next Activity via button click then in that button's onClick():
// 1.
String data = myTextView.getText();
// 2.
Intent intent = new Intent(yourContext,YourNextActivity.class);
// 3.
intent.putStringExtra("MY DATA KEY",data);
// 4.
yourContext.startActivity(intent);
// 5. Now in YourNextActivity's onCreate();
String retrievedData = YourNextActivity.this.getIntent().getStringExtra("MY DATA KEY");
// Done!

java.lang.ClassCastException: Activity cannot be cast to MainActivity

I am trying to do a login session using Volley, PHP, MySQL but my login layout won't load. I do not know what is happening and in my logcat it says " java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.merylle.themoneyger/com.example.merylle.themoneyger.activity.LoginActivity}: java.lang.ClassCastException: com.example.merylle.themoneyger.activity.LoginActivity cannot be cast to com.example.merylle.themoneyger.activity.MainActivity"
which is cause by "Caused by: java.lang.ClassCastException: com.example.merylle.themoneyger.activity.LoginActivity cannot be cast to com.example.merylle.themoneyger.activity.MainActivity"
Can someone help me identify my error? Here's my code
SessionManager.java
public class SessionManager {
SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Context context;
int PRIVATE_MODE=0;
private static final String PREF_NAME = "MONEYGER";
private static final String LOGIN = "IS_LOGIN";
public static final String FIRSTNAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String USERID = "USERID";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void createSession(String firstname, String email) {
editor.putBoolean(LOGIN, true);
editor.putString(FIRSTNAME, firstname);
editor.putString(EMAIL, email);
/*editor.putString(USERID, userid);*/
editor.apply();
}
public boolean isLoggin(){
return sharedPreferences.getBoolean(LOGIN, false);
}
public void checkLogin() {
if (!this.isLoggin()) {
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity)context).finish();
}
}
public HashMap<String, String> getUserDetail() {
HashMap<String, String> user = new HashMap<>();
user.put(FIRSTNAME, sharedPreferences.getString(FIRSTNAME, null));
user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
/*user.put(USERID, sharedPreferences.getString(USERID, null));*/
return user;
}
public void logout() {
editor.clear();
editor.commit();
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity)context).finish();
}
}
LoginActivity.java
public class LoginActivity extends Activity {
TextView title;
Typeface marcellus;
private EditText emailuser, passworduser;
TextView forgot;
private Button login, register;
private ProgressBar progressBar;
private static String HttpURL = "http://10.0.2.2:63343/TheMoneyger/api/user-login.php?";
SessionManager sessionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sessionManager = new SessionManager(this);
sessionManager.checkLogin();
title = (TextView) findViewById(R.id.txtTitle);
marcellus = Typeface.createFromAsset(getAssets(), "marcellus.ttf");
title.setTypeface(marcellus);
emailuser = (EditText) findViewById(R.id.txtEmail);
passworduser = (EditText) findViewById(R.id.txtPassword);
login = (Button) findViewById(R.id.btnLogin);
forgot = (TextView) findViewById(R.id.txtForgotPW);
register = (Button) findViewById(R.id.btnRegister);
progressBar = (ProgressBar)findViewById(R.id.progressBar3);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mEmail = emailuser.getText().toString().trim();
String mPass = passworduser.getText().toString().trim();
if(!mEmail.isEmpty() || !mPass.isEmpty()) {
Login(mEmail, mPass);
}
else {
emailuser.setError("Please insert email");
passworduser.setError("Please insert password");
}
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registration = new Intent(LoginActivity.this, RegistrationActivity.class);
startActivity(registration);
}
});
forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forgot = new Intent(LoginActivity.this, ForgotPassword.class);
startActivity(forgot);
}
});
}
private void Login(final String emailuser, final String passworduser) {
progressBar.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String firstname = object.getString("firstname").trim();
String email = object.getString("email").trim();
String id = object.getString("userid").trim();
sessionManager.createSession(firstname, email);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("firstname", firstname);
intent.putExtra("email", email);
startActivity(intent);
finish();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Something went wrong.. " + e.toString(), Toast.LENGTH_SHORT).show();
login.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Something went wrong.. " + error.toString(), Toast.LENGTH_SHORT).show();
login.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", emailuser);
params.put("password", passworduser);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Home2.java
public class Home2 extends Fragment {
private TextView profileName, profileEmail;
CardView cv1, cv2, cv3, cv4, cv5, cv6;
SessionManager sessionManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
sessionManager = new SessionManager(getActivity().getApplicationContext());
sessionManager.checkLogin();
cv1 = (CardView)view.findViewById(R.id.cv1); //settings
cv2 = (CardView)view.findViewById(R.id.cv2); //profile
cv3 = (CardView)view.findViewById(R.id.cv3); //expenses summary
cv4 = (CardView)view.findViewById(R.id.cv4); //budget summary
cv5 = (CardView)view.findViewById(R.id.cv5); //report
cv6 = (CardView)view.findViewById(R.id.cv6); //logout
profileName = (TextView)view.findViewById(R.id.txtProfileName); //display profilename
profileEmail = (TextView)view.findViewById(R.id.txtProfileEmail); //display profileemail
HashMap<String, String> user = sessionManager.getUserDetail();
String mName = user.get(sessionManager.FIRSTNAME);
String mEmail = user.get(sessionManager.EMAIL);
profileName.setText(mName);
profileEmail.setText(mEmail);
return view;
}
}
user-login.php
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'];
$password = $_POST['password'];
require_once 'config.php';
$sql = "SELECT * FROM users WHERE email='$username'";
$response = mysqli_query($db, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1 ) {
$row = mysqli_fetch_assoc($response);
if ( password_verify($password, $row['password']) ) {
$index['firstname'] = $row['firstname'];
$index['email'] = $row['email'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($db);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($db);
}
}
}
?>
You have initialized sessionManager with LoginActivity's context:
sessionManager = new SessionManager(this);
and then inside SessionManager class you use this:
((MainActivity)context).finish();
which throws the error.
You can't cast LoginActivity's context to MainActivity.
Change to this:
((LoginActivity)context).finish();
After all it is LoginActivity you want to finish isn't it?

Android Studio, My Activities are going to the wrong activity

so I am a fresh face to android development, and I encountered a problem which I have been going loops for.
I have three activities here, they are for registration, I don't want to implement scrollview because it isn't that good looking so I made it to three form activities,
The first activity gathers all info from the XML's and passes the values as via intent to the second activity,
then the second activity gathers all info from it's own XML, and then passes it together with the Extra of the first activity to the third activity, and the third activity together with the first and seconds Extras PLUS it's own values from it's own XML's, finally, saves the values to firebase.
Yes the values get's saved, but my problem is the third activity doesn't go to the Welcome class which is supposedly written on its intent. I tried rebuilding and cleaning but it did not work. I couldn't find the bug to my work, can anyone help me out? any help is appreciated. Thanks
Here are my three java classes, and I will also put in the welcome class incase you might want to ask for it:
Profile.java
public class Profile extends Activity {
//DECLARE FIELDS
EditText name,username, phone, age, birth;
Button saveBtn;
//FIREBASE REF
DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//FIREBASE DATABASE REF
userRef = FirebaseDatabase.getInstance().getReference("Users");
//ASSIGN ID's
saveBtn = (Button) findViewById(R.id.profileBtn);
name = (EditText) findViewById(R.id.profileName);
username = (EditText) findViewById(R.id.profileUsername);
age = (EditText) findViewById(R.id.profileAge);
phone = (EditText) findViewById(R.id.profilePhone);
birth = (EditText) findViewById(R.id.profileBirth);
// SAVE BUTTON LOGIC
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addUser();
}
});
}
private void addUser(){
String userNameString = name.getText().toString();
String userPhoneString = phone.getText().toString();
String userAgeString = age.getText().toString();
String userBirthString = birth.getText().toString();
String userUserNameString = username.getText().toString();
//GET USER KEY FROM INTENT
String userKey = getIntent().getStringExtra("USER_KEY");
String userEmail = getIntent().getStringExtra("USER_EMAIL");
String userPass = getIntent().getStringExtra("USER_PASS");
String userID = getIntent().getStringExtra("USER_ID");
if (!TextUtils.isEmpty(userNameString) && !TextUtils.isEmpty(userPhoneString) && !TextUtils.isEmpty(userAgeString) && !TextUtils.isEmpty(userBirthString) && !TextUtils.isEmpty(userUserNameString)) {
Toast.makeText(Profile.this, "Next!", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Profile.this, Profile2.class);
myIntent.putExtra("USER_KEY", userKey);
myIntent.putExtra("USER_NAME", userNameString);
myIntent.putExtra("USER_PHONE", userPhoneString);
myIntent.putExtra("USER_AGE", userAgeString);
myIntent.putExtra("USER_BIRTH", userBirthString);
myIntent.putExtra("USER_USERNAME", userUserNameString);
myIntent.putExtra("USER_EMAIL", userEmail);
myIntent.putExtra("USER_PASS", userPass);
myIntent.putExtra("USER_ID", userID);
startActivity(myIntent);
} else {
Toast.makeText(Profile.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile.this, Profile.class));
}
}
}
Profile2.java
public class Profile2 extends Activity {
//DECLARE FIELDS
EditText Address, FSN, bType, Height, Weight;
Button saveBtn;
//FIREBASE REF
DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
//FIREBASE DATABASE REF
userRef = FirebaseDatabase.getInstance().getReference("Users");
//ASSIGN ID's
saveBtn = (Button) findViewById(R.id.profileBtn);
Address = (EditText) findViewById(R.id.Address);
FSN = (EditText) findViewById(R.id.FSN);
bType = (EditText) findViewById(R.id.bType);
Height = (EditText) findViewById(R.id.Height);
Weight = (EditText) findViewById(R.id.Weight);
//MOVE TO LOGIN
// SAVE BUTTON LOGIC
saveBtn.setOnClickListener(new View.OnClickListener() {
// #RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View view) {
addUser();
}
});
}
private void addUser(){
String AddressString = Address.getText().toString();
String FSNString = FSN.getText().toString();
String WeightString = Weight.getText().toString();
String bTypeString = bType.getText().toString();
String HeightString = Height.getText().toString();
//GET USER KEY FROM INTENT
String userKey = getIntent().getStringExtra("USER_KEY");
String userNameString = getIntent().getStringExtra("USER_NAME");
String userPhoneString = getIntent().getStringExtra("USER_PHONE");
String userAgeString = getIntent().getStringExtra("USER_AGE");
String userBirthString = getIntent().getStringExtra("USER_BIRTH");
String userUserNameString = getIntent().getStringExtra("USER_USERNAME");
String userPass = getIntent().getStringExtra("USER_PASS");
String userID = getIntent().getStringExtra("USER_ID");
String userEmail = getIntent().getStringExtra("USER_EMAIL");
if (!TextUtils.isEmpty(AddressString) && !TextUtils.isEmpty(FSNString) && !TextUtils.isEmpty(WeightString) && !TextUtils.isEmpty(bTypeString) && !TextUtils.isEmpty(HeightString)) {
Toast.makeText(Profile2.this, "Go mamshie!", Toast.LENGTH_LONG).show();
Intent myIntent2 = new Intent(Profile2.this, Profile3.class);
myIntent2.putExtra("USER_KEY", userKey);
myIntent2.putExtra("USER_NAME", userNameString);
myIntent2.putExtra("USER_PHONE", userPhoneString);
myIntent2.putExtra("USER_AGE", userAgeString);
myIntent2.putExtra("USER_BIRTH", userBirthString);
myIntent2.putExtra("USER_USERNAME", userUserNameString);
myIntent2.putExtra("USER_ADDRESS", AddressString);
myIntent2.putExtra("USER_FSN", FSNString);
myIntent2.putExtra("USER_BTYPE", bTypeString);
myIntent2.putExtra("USER_HEIGHT", HeightString);
myIntent2.putExtra("USER_WEIGHT", WeightString);
myIntent2.putExtra("USER_PASS", userPass);
myIntent2.putExtra("USER_ID", userID);
myIntent2.putExtra("USER_EMAIL", userEmail);
startActivity(myIntent2);
} else {
Toast.makeText(Profile2.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile2.this, Profile2.class));
}
}
}
Profile3.java
public class Profile3 extends Activity {
//DECLARE FIELDS
EditText NPP, PCS, MC, SB, PPH;
Button saveBtn;
//FIREBASE REF
DatabaseReference mDataRef, userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile3);
//FIREBASE DATABASE REF
userRef = FirebaseDatabase.getInstance().getReference("Users");
//ASSIGN ID's
saveBtn = (Button) findViewById(R.id.profileBtn);
NPP = (EditText) findViewById(R.id.previous);
PCS = (EditText) findViewById(R.id.previouscs);
MC = (EditText) findViewById(R.id.miscar);
SB = (EditText) findViewById(R.id.stillbirth);
PPH = (EditText) findViewById(R.id.post);
//MOVE TO LOGIN
// SAVE BUTTON LOGIC
saveBtn.setOnClickListener(new View.OnClickListener() {
// #RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View view) {
addUser();
}
});
}
private void addUser(){
String NoPrevPregnancies = NPP.getText().toString();
String PreviousCS = PCS.getText().toString();
String Miscarriages = MC.getText().toString();
String Stillbirth = SB.getText().toString();
String PostPartumHem = PPH.getText().toString();
//GET USER KEY FROM INTENT
String userKey = getIntent().getStringExtra("USER_KEY");
String userEmail = getIntent().getStringExtra("USER_EMAIL");
String userPass = getIntent().getStringExtra("USER_PASSWORD");
String userID = getIntent().getStringExtra("USER_ID");
String userNameString = getIntent().getStringExtra("USER_NAME");
String userPhoneString = getIntent().getStringExtra("USER_PHONE");
String userAgeString = getIntent().getStringExtra("USER_AGE");
String userBirthString = getIntent().getStringExtra("USER_BIRTH");
String userUserNameString = getIntent().getStringExtra("USER_USERNAME");
String AddressString = getIntent().getStringExtra("USER_ADDRESS");
String FSNString = getIntent().getStringExtra("USER_FSN");
String bTypeString = getIntent().getStringExtra("USER_BTYPE");
String HeightString = getIntent().getStringExtra("USER_HEIGHT");
String WeightString = getIntent().getStringExtra("USER_WEIGHT");
mDataRef = userRef.child(userNameString);
if (!TextUtils.isEmpty(PreviousCS) && !TextUtils.isEmpty(NoPrevPregnancies) && !TextUtils.isEmpty(PostPartumHem) && !TextUtils.isEmpty(Miscarriages) && !TextUtils.isEmpty(Stillbirth)) {
User3 user = new User3(PreviousCS, NoPrevPregnancies, PostPartumHem, Miscarriages, Stillbirth);
userRef.child(userNameString).setValue(user);
mDataRef.child("USER_KEY").setValue(userKey);
mDataRef.child("USER_PASS").setValue(userPass);//
mDataRef.child("USER_ID").setValue(userID);//
mDataRef.child("USER_NAME").setValue(userNameString);//
mDataRef.child("USER_PHONE").setValue(userPhoneString);
mDataRef.child("USER_AGE").setValue(userAgeString);
mDataRef.child("USER_BIRTH").setValue(userBirthString);
mDataRef.child("USER_USERNAME").setValue(userUserNameString);//
mDataRef.child("USER_ADDRESS").setValue(AddressString);
mDataRef.child("USER_FSN").setValue(FSNString);
mDataRef.child("USER_BTYPE").setValue(bTypeString);
mDataRef.child("USER_HEIGHT").setValue(HeightString);
mDataRef.child("USER_WEIGHT").setValue(WeightString);
mDataRef.child("USER_EMAIL").setValue(userEmail);//
Toast.makeText(Profile3.this, "User Details Completed and Saved!", Toast.LENGTH_LONG).show();
Intent myIntent1 = new Intent(Profile3.this, Welcome.class);
myIntent1.putExtra("USER_KEY", userKey);
myIntent1.putExtra("USER_EMAIL", userEmail);
myIntent1.putExtra("USER_PHONE", userPhoneString);
myIntent1.putExtra("USER_BIRTH", userBirthString);
myIntent1.putExtra("USER_USERNAME", userUserNameString);
myIntent1.putExtra("USER_NAME", userNameString);
myIntent1.putExtra("USER_AGE", userAgeString);
myIntent1.putExtra("USER_ID", userID);
startActivity(myIntent1);
} else {
Toast.makeText(Profile3.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile3.this, Profile3.class));
}
}
}
My welcome activity which gets some data and shows it
public class Welcome extends AppCompatActivity {
private static final String TAG = "ViewDatabase";
//ADD FIREBASE STUFF
//DECLARE FIELDS
Button outBtn;
TextView welcome;
private DatabaseReference myRef, mDataRef, userRef;
private FirebaseDatabase mFirebaseDatabase;
private String userIDPassed;
private String userID;
private String userKey;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private ListView mListView;
//FIREBASE AUTH FIELDS
private FirebaseAuth nAuth;
private FirebaseAuth.AuthStateListener nAuthlistener;
//GET USER KEY FROM INTENT
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
//DRAWER LAYOUT
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
//ASSIGN IDS
outBtn = (Button) findViewById(R.id.logoutBtn);
welcome = (TextView) findViewById(R.id.WelcomeName);
mListView = (ListView) findViewById(R.id.listview);
//ASSIGN INSTANCE
myRef = FirebaseDatabase.getInstance().getReference().child("Users");
nAuth = FirebaseAuth.getInstance();
userRef = FirebaseDatabase.getInstance().getReference("Users");
FirebaseUser User = nAuth.getCurrentUser();
userID = User.getUid();
//navigation Drawer
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
#Override public boolean onNavigationItemSelected(MenuItem menuItem)
{ switch (menuItem.getItemId())
{
case(R.id.nav_account): Intent accountActivity = new Intent(getApplicationContext(), Welcome.class);
startActivity(accountActivity);
break;
case(R.id.nav_exercises): Intent accountActivity1 = new Intent(getApplicationContext(), Video.class);
startActivity(accountActivity1);
break;
case(R.id.nav_tips): Intent accountActivity2 = new Intent(getApplicationContext(), Image.class);
startActivity(accountActivity2);
break;
case(R.id.nav_scheduler): Intent accountActivity3 = new Intent(getApplicationContext(), CalendarActivity.class);
startActivity(accountActivity3);
break;
case(R.id.nav_logout): Intent accountActivity4 = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(accountActivity4);
finish();
break;
case(R.id.nav_settings): Intent accountActivity5 = new Intent(getApplicationContext(), Profile.class);
startActivity(accountActivity5);
break;
case(R.id.nav_info): Intent accountActivity6 = new Intent(getApplicationContext(), Info.class);
startActivity(accountActivity6);
break;
}
return true;
} });
//Navigation Drawer
nAuthlistener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser User = firebaseAuth.getCurrentUser();
if (User != null){
Log.d(TAG, "onAuthStateChanged:signed_in:" + User.getUid());
Toast.makeText(Welcome.this, "Successfully signed in with: " + User.getEmail(), Toast.LENGTH_LONG).show();
}else{
Log.d(TAG, "onAuthStateChanged:signed_out" + userID);
Toast.makeText(Welcome.this, "Successfully signed out.", Toast.LENGTH_LONG).show();
}
}
};
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot){
showData(dataSnapshot);
}
#Override
public void onCancelled (DatabaseError databaseError){
}
});
outBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nAuth.signOut();
finish();
startActivity(new Intent(Welcome.this, MainActivity.class));
}
});
}
private void showData(DataSnapshot dataSnapshot) {
//GET USER KEY FROM INTENT
String userKey = getIntent().getStringExtra("USER_KEY");
String userEmail = getIntent().getStringExtra("USER_EMAIL");
String userPhone = getIntent().getStringExtra("USER_PHONE");
String userBirth = getIntent().getStringExtra("USER_BIRTH");
String userUserName = getIntent().getStringExtra("USER_USERNAME");
String userName = getIntent().getStringExtra("USER_NAME");
String userAge = getIntent().getStringExtra("USER_AGE");
String userID = getIntent().getStringExtra("USER_ID");
mDataRef = userRef.child(userName);
if (!TextUtils.isEmpty(userKey) && !TextUtils.isEmpty(userEmail) && !TextUtils.isEmpty(userID) && !TextUtils.isEmpty(userBirth) && !TextUtils.isEmpty(userUserName)) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
Log.d(TAG, "showData: snapshot: " + ds);
Log.d(TAG, "showData: snapshot: " + ds.child("Users"));
//display all info taken
Log.d(TAG, "showData: USER_NAME: " + userName);
Log.d(TAG, "showData: USER_AGE: " + userAge);
Log.d(TAG, "showData: USER_BIRTH: " + userBirth);
Log.d(TAG, "showData: USER_PHONE: " + userPhone);
Log.d(TAG, "showData: USER_USERNAME: " + userUserName);
ArrayList<String> array = new ArrayList<>();
array.add(userName);
array.add(userAge);
array.add(userBirth);
array.add(userPhone);
array.add(userUserName);
ArrayAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
} else {
}
}
#Override
protected void onStart() {
super.onStart();
nAuth.addAuthStateListener(nAuthlistener);
}
#Override
protected void onStop() {
super.onStop();
nAuth.removeAuthStateListener(nAuthlistener);
}
//FOR NAVIGATION DRAWER
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
//Navigation Drawer End
}
What did I do wrong? Thinking of it as flowing water, I think the values flowed well until the last activity?
in your profile1, change the intent to profiles, profile2 eg
Toast.makeText(Profile.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile.this, Profile2.class));
and do same for profile 2 and profile 3.
Try debugging by removing your else statements and maybe add them all to the last activity

I/O Error On Post Request Spring Boot Rest Service In Android

I'm doing a Small android Application. In that I'm storing The user entered Information to my local data base With Http Rest Call.
There is nothing problem with the service It is working fine I tested In Browser and postman I'm able to Perform CRUD Operations through Postman Client.
But When I try to POST OR GET From Android It is Throwing Error Like I/O error On Post method Connection Refused.
I don't Know the Reason for this.
Below Is My Code in Android.
This code is for GET Request.
public class Result extends AppCompatActivity {
String ID;
Login login=new Login();
final String url = "http://192.168.1.189:9001/login";
// List login = new ArrayList<>();
Button logout;
TextView nameTv, ageTv, emailTv, usernameTv;
String NAME, AGE, EMAIL, USERNAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Intent intent=getIntent();
// ID=intent.getStringExtra("ID");
// new HttpGetTask().execute();
logout = (Button) findViewById(R.id.buttonLogout);
nameTv = (TextView) findViewById(R.id.nameTextView);
ageTv = (TextView) findViewById(R.id.ageTextView);
emailTv = (TextView) findViewById(R.id.emailTextView);
usernameTv = (TextView) findViewById(R.id.UsernameTextView);
nameTv.setText(NAME);
ageTv.setText(AGE);
emailTv.setText(EMAIL);
usernameTv.setText(USERNAME);
new HttpRequestTask().execute();
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent logoutintent = new Intent(Result.this, MainActivity.class);
startActivity(logoutintent);
}
});
}
private class HttpRequestTask extends AsyncTask<Void, Void, Login> {
#Override
protected Login doInBackground(Void... params) {
try {
// final String url = "http://192.168.1.213:9001/consumer/local/64";
RestTemplate restTemplate = new RestTemplate();
Login lg = restTemplate.getForObject(url, Login.class);
// NAME=lg.getName().toString();
Log.d("", "doInBackground:++++++++++++++++++++++ "+NAME);
return lg;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
This Below Code is for POST Request.
public class Register extends AppCompatActivity {
Button buttonRegister;
public String ID;
TextView editId,editName,editAge,editEmail,editUsername,editPassword;
private String Name,Age,Email,Username,Password;
Login login=new Login();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editId=(TextView)findViewById(R.id.editId);
editName=(TextView)findViewById(R.id.editName);
editAge=(TextView)findViewById(R.id.editAge);
editEmail=(TextView)findViewById(R.id.editEmail);
editUsername=(TextView)findViewById(R.id.editUsername);
editPassword=(TextView)findViewById(R.id.editPassword);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Register.this, "Registration Successful", Toast.LENGTH_SHORT).show();
Name = editName.getText().toString();
Age = editAge.getText().toString();
Email = editEmail.getText().toString();
Username = editUsername.getText().toString();
Password = editPassword.getText().toString();
Log.d("???????????", "onClick:------------> " + Name);
Log.d("???????????", "onClick:------------> " + ID);
Log.d("???????????", "onClick:------------> " + Age);
Log.d("???????????", "onClick:------------> " + Email);
Log.d("???????????", "onClick:------------> " + Username);
Log.d("???????????", "onClick:------------> " + Password);
new HttpPostTask().execute();
Intent regintent = new Intent(Register.this, Result.class);
//regintent.putExtra("ID",1);
startActivity(regintent);
/*Intent regintent = new Intent(Register.this, Result.class);
startActivity(regintent);*/
}
});
}
public class HttpPostTask extends AsyncTask<Void,Void,Login>{
#Override
protected Login doInBackground(Void... params) {
final String url = "http://192.168.1.189:9001/login";
RestTemplate restTemplate = new RestTemplate();
Login login = new Login();
login.setName(Name);
login.setAge(Age);
login.setEMail(Email);
login.setUserName(Username);
login.getId();
login.setPassword(Password);
Log.d("???????????", "onClick:!!!!!!!!!!!!!!> " + Name);
login = restTemplate.postForObject(url, login, Login.class);
ID=login.getId();
Log.d("???????????", "onClick:!!!!!!!!!!!!!!> " + login.getId());
return login;
}
#Override
protected void onPostExecute(Login login){
super.onPostExecute(login);
}
}
}
I have been searching for this problem since last two days.
Any help appreciated Thanks In advance...........
Restarting my System Solve My Problem

Categories