java — данные не передаются следующему действию, когда php и android используются для входа и регистрации

В моем Основная деятельность я вставляю значения в базу данных, используя вставки-DB (1) .php файл .. В файле php я создаю один vault_no используя данные, которые были отправлены через код Android, и я вставляю это в базу данных.
Здесь для цели входа я использую vault_no как username.now в моем коде я передаю все, что пользователь ввел как vault_no в login.php и он проверит, vault_no есть в php или нет. Но по моему ActivityLogin.java код должен проверить valut_no и перейти к userprofile.java страница и отображать приветственное сообщение.но это не идет к другой деятельности, это просто дает { «Ошибка»: ложь} как тост сообщение.

Может кто-нибудь, пожалуйста, сообщите мне, как достичь этого .. Спасибо заранее .. !!

MainActivity.java

package com.example.test1;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.HashMap;public class MainActivity extends Activity implements View.OnClickListener{private static final int[] SalutationCode = new int[]{0,1, 2}; // array to save Salutation code
private static final String[] Salutation = new String[]{"Salutation","Mr","Ms"}; // array to show Salutation

private static final int[] CountryCode = new int[]{0,91}; // array to save Country code
private static final String[] Country = new String[]{"Country","India"}; // array to show Country name.

private static final int[] CityCode = new int[]{0,1}; // array to save City code
private static final String[] City = new String[]{"City","Bangalore"}; // array to show City list

private static final int[] StateCode = new int[]{0,1}; // array to save State code
private static final String[] State = new String[]{"State","Karnataka"}; // array to show State list

int selectedAreaCode;
private Spinner spin;
private Spinner spin1;
private Spinner spin2;
private Spinner spin3;
private EditText editTextFname;
private EditText editTextLname;
private EditText editTextDob;
private EditText editTextMobile;
private EditText editTextPin;
private Button register;
private Button login;

private static final String REGISTER_URL = "http://oursite/insert-db(1).php";@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

spin = (Spinner)findViewById(R.id.spinner1);
spin1 = (Spinner)findViewById(R.id.spinner2);
spin2 = (Spinner)findViewById(R.id.spinner3);
spin3 = (Spinner)findViewById(R.id.spinner4);
editTextFname = (EditText) findViewById(R.id.editTextFname);
editTextLname = (EditText) findViewById(R.id.editTextLname);
editTextDob = (EditText)findViewById(R.id.editTextDob);
editTextMobile = (EditText) findViewById(R.id.editTextMobile);
editTextPin = (EditText) findViewById(R.id.editTextPin);

register = (Button) findViewById(R.id.button);

login = (Button) findViewById(R.id.button2);

register.setOnClickListener(this);

login.setOnClickListener(this);

ArrayAdapter<String> adpt_area = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Salutation);
adpt_area.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adpt_area);

ArrayAdapter<String> adpt_country = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Country);
adpt_country.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin1.setAdapter(adpt_country);

ArrayAdapter<String> adpt_city = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, City);
adpt_city.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin2.setAdapter(adpt_city);

ArrayAdapter<String> adpt_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, State);
adpt_state.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin3.setAdapter(adpt_state);}

@Override
public void onClick(View v) {
if(v == register){
registerUser();
}
if(v == login){
startActivity(new Intent(this,ActivityLogin.class));
}
}

private void registerUser() {

String fname = editTextFname.getText().toString();

if(TextUtils.isEmpty(fname)) {
editTextFname.setError("please enter first name");
return;
}

String lname = editTextLname.getText().toString();

if(TextUtils.isEmpty(lname)) {
editTextLname.setError("please enter last name");
return;
}

String dob = editTextDob.getText().toString();

if(TextUtils.isEmpty(dob)) {
editTextDob.setError("enter date of birth");
return;
}

String mobile = editTextMobile.getText().toString();

if(TextUtils.isEmpty(mobile)) {
editTextMobile.setError("please enter mobile no");
return;
}String pin = editTextPin.getText().toString();

if(TextUtils.isEmpty(pin)) {
editTextPin.setError("please enter pin no");
return;
}

int selectedPosition = spin.getSelectedItemPosition();
// get area code based on value selected in spinner
String salutation = String.valueOf(SalutationCode[selectedPosition]);

int selectedPosition1 = spin1.getSelectedItemPosition();
// get area code based on value selected in spinner
String country = String.valueOf(CountryCode[selectedPosition1]);

int selectedPosition2 = spin2.getSelectedItemPosition();
// get area code based on value selected in spinner
String state = String.valueOf(StateCode[selectedPosition2]);

int selectedPosition3 = spin3.getSelectedItemPosition();
// get area code based on value selected in spinner
String city = String.valueOf(CityCode[selectedPosition3]);register(salutation,fname,lname,dob,mobile,country,state,city,pin);
}

private void register(String salutation, String fname, String lname,String dob,String mobile, String country, String state, String city, String pin) {
class RegisterUser extends AsyncTask<String, Void, String>{
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
editTextFname.setText("");
editTextLname.setText("");
editTextDob.setText("");
editTextMobile.setText("");
editTextPin.setText("");
}

@Override
protected String doInBackground(String... params) {

HashMap<String, String> data = new HashMap<String,String>();
data.put("salutation",params[0]);
data.put("fname",params[1]);
data.put("lname",params[2]);
data.put("dob",params[3]);
data.put("mobile",params[4]);
data.put("country",params[5]);
data.put("state",params[6]);
data.put("city",params[7]);
data.put("pin",params[8]);String result = ruc.sendPostRequest(REGISTER_URL,data);

return  result;
}
}

RegisterUser ru = new RegisterUser();
ru.execute(salutation,fname,lname,dob,mobile,country,state,city,pin);
}
}

ActivityLogin.java

package com.example.test1;import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 java.util.HashMap;

public class ActivityLogin extends Activity implements View.OnClickListener{

public static final String VAULT_NUMBER = "VAULT_NUMBER";
private static final String LOGIN_URL = "http://oursite/login.php";

private EditText editVault;
private Button buttonLogin;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_login);

editVault = (EditText) findViewById(R.id.editTextFname);

buttonLogin = (Button) findViewById(R.id.login);
buttonLogin.setOnClickListener(this);
}private void login(){
String vault_no = editVault.getText().toString().trim();
userLogin(vault_no);
}

private void userLogin(final String vault_no){
class UserLoginClass extends AsyncTask<String,Void,String>{
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityLogin.this,"Please Wait",null,true,true);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(ActivityLogin.this,UserProfile.class);
intent.putExtra(VAULT_NUMBER,vault_no);
startActivity(intent);
}else{
Toast.makeText(ActivityLogin.this,s,Toast.LENGTH_LONG).show();
}
}

@Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("vault_no",params[0]);

RegisterUserClass ruc = new RegisterUserClass();

String result = ruc.sendPostRequest(LOGIN_URL,data);

return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(vault_no);
}

@Override
public void onClick(View v) {
if(v == buttonLogin){
login();
}
}
}

RegisterUserClass.java

package com.example.test1;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;public class RegisterUserClass {

public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {

URL url;
String response = "";
try {
url = new URL(requestURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));

writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));

response = br.readLine();
}
else {
response="Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}

return response;
}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}

return result.toString();
}
}

UserProfile.java

package com.example.test1;import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class UserProfile extends Activity {

private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);

textView = (TextView) findViewById(R.id.textViewUserName);

Intent intent = getIntent();

String vault_no = intent.getStringExtra(ActivityLogin.VAULT_NUMBER);

textView.setText("Welcome.Your Vault number is "+vault_no);
}
}

вставки-DB (1) .php

<?php
session_start();

define('HOST','mysql.hostinger.in');
define('USER','username');
define('PASS','password');
define('DB','dbname');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

$salutation = ($_POST['salutation']);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$dob = trim($_POST['dob']);
$mobile = trim($_POST['mobile']);
$country = trim($_POST['country']);
$state = trim($_POST['state']);
$city = trim($_POST['city']);
$pin = trim($_POST['pin']);
//////////////////mobile number validation/////////////

$sql = "SELECT mobile FROM person WHERE mobile = '$mobile' LIMIT 1";
$result = mysqli_query($con,$sql);
if(mysqli_fetch_array($result)){
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
}else{

/////////////////*******/////////////////////////////

$characters = '0123456789';
$uuid = '';
$random_string_length = 5;
for ($i = 0; $i < $random_string_length; $i++){
$uuid .= $characters[rand(0, strlen($characters) - 1)];
}
$fullname = $fname . " " . $lname;
$vault_no = $salutation . "" . $country . "" . $pin . "" . $uuid;
$sql = "insert into person (salutation,fname,lname,fullname,dob,mobile,country,state,city,pin,unique_id,vault_no,created_at) values ('$salutation','$fname','$lname','$fullname','$dob','$mobile','$country','$state','$city','$pin','$uuid','$vault_no',now())";
if(mysqli_query($con,$sql)){
$sql = "SELECT * FROM person WHERE mobile = '$mobile' LIMIT 1";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$response["error"] = false;
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['vault_no'] = $row['vault_no'];
echo json_encode($response);
}

}else{
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
mysqli_close($con);
?>

login.php

<?php
session_start();
define('HOST','mysql.hostinger.in');
define('USER','username');
define('PASS','password');
define('DB','dbname');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

//reciving the post parameters
$vault_no = trim($_POST['vault_no']);
$sql = "SELECT * FROM person WHERE vault_no = '$vault_no' LIMIT 1";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$response["error"] = false;
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['vault_no'] = $row['vault_no'];
echo json_encode($response);
}
?>

Может кто-нибудь, пожалуйста, посмотрите весь код и помогите мне с идеей / решением .. пожалуйста .. !!
И как только нажата кнопка «Регистрация», как получить сгенерированное vault_no вместе с полным именем из insert-db (1) .php и отобразить в другом действии в Android. Пожалуйста, помогите мне добиться этого.

0

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]