I am coding for the first time in Android and I was developing a Login page. There is no error while running the app but the app gives me "Incorrect User details" message even if I am entering correct details. After debugging the code, I figured out that the error is while executing this line.
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
I set up different breakpoints and figured out that as soon as this line executes, I get the error message.
Here is my complete code:
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
User user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(User user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
@Override
protected User doInBackground(Void... params) {
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("username", user.username);
dataToSend.put("password", user.password);
String encodedStr = getEncodedData(dataToSend);
BufferedReader reader = null;
User returnedUser = null;
try{
//Converting the address string into URL
URL url = new URL(SERVER_ADDRESS + "FetchUserData.php");
//Opening the connection
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(encodedStr);
writer.flush();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
line = sb.toString();
Log.i("custom check","The values received are:");
Log.i("custom check",line);
JSONObject jobject = new JSONObject(line);
if(jobject.length() == 0){
returnedUser = null;
}else{
String fname = jobject.getString("FirstName");
String lname = jobject.getString("LastName");
returnedUser = new User(fname, lname, user.username, user.password);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(reader != null) {
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return returnedUser;
}
The problem is that "returnedUser" is always null even if I enter correct credentials and that is why it is showing error message.