Проблемы со входом в Android: поля возвращаются пустыми

В настоящее время я создаю приложение для Android для нашей диссертации. Я почти закончил с приложением, когда у меня начались проблемы с логином. Поля принимают входные данные, когда я пытаюсь поджарить их, но отправляют мне ответ «Поля пусты», когда я отправляю данные на сервер. Я застрял, работая над этим, поэтому любая помощь будет по достоинству оценена.

Это мой класс JSONParser:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

// Making HTTP request
try {

// check for request method
if(method.equals("POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} else if (method.equals("GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;
}
}

Это мой логин asynctask:

class AttemptLogin extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

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

int success;
String emailaddress = EADD.getText().toString();
String password = PASS.getText().toString();

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mem_email", emailaddress));
params.add(new BasicNameValuePair("mem_password", password));

Log.d("request!", "starting");

JSONObject json = jsonParser.makeHttpRequest("http://builtcycles.com/built_mobile/login.php", "POST", params);

// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
try{
success = json.getInt("success");

if (success == 1) {
String memberId = json.getString("id");
String memberName = json.getString("uid");

Log.d("Login Successful!", json.toString());
pDialog.dismiss();

intent = new Intent(Login.this, MainActivity.class);

intent.putExtra("id", memberId);
intent.putExtra("uid", memberName);

startActivity(intent);
finish();

return json.getString("message");
} else {
Log.d("Login Failure!", json.getString("message"));
return json.getString("message");
}

} catch (Exception e) {
e.printStackTrace();
}

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/

@Override
protected void onPostExecute(String file_url) {

pDialog.dismiss();

if (file_url != null) {
Toast.makeText(Login.this, file_url, Toast.LENGTH_SHORT).show();
}
}
}

И это мой логин php:

<?php
$response = array();
if (!empty($_POST)) {

$email= $_POST['mem_email'];

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("SELECT * from tblmembers where mem_email='$email'");

if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$response["id"] = $row["mem_id"];
$response["uid"] = $row["mem_fname"];

if ($row["mem_active"]==1) {
if (md5($_POST['mem_password'])===$row['mem_password']) {

$response["success"] = 1;
$response["message"] = "Login successfully!";

echo json_encode($response);
} else {

$response["success"] = 0;
$response["message"] = "Invalid email or password";

echo json_encode($response);
}
} else {
$response["success"] = 3;
$response["message"] = "Check your email for verification! Thanks.";

echo json_encode($response);
}
}
} else {
// no products found
$response["success"] = 4;
$response["message"] = "No user found";

// echo no users JSON
echo json_encode($response);
}
} else {
$response["success"] = 4;
$response["message"] = "Fields are empty.";

// echo no users JSON
echo json_encode($response);
}
?>

Я изменил метод == «POST» / «GET» на method.equals («POST»). Тем не менее, я не могу отправить данные на сервер. Проблема возникает из класса jsonparser или из doinbackground () асинктической задачи?

0

Решение

Измените операторы сравнения строк в

makeHttpRequest()

от

// check for request method
if(method == "POST"){
...
} else if (method == "GET") {

в

// check for request method
if(method.equals("POST")){
...
} else if (method.equals("GET")) {
1

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

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