I tried all i can find in previous similar posts but it didnt help. I get the error: "I/System.out: Error: org.json.JSONException: Value br of type java.lang.String cannot be converted to JSONObject"
Java Code:
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import
com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
private static final String KEY_STATUS = "status";
private static final String KEY_MESSAGE = "message";
private static final String KEY_FULL_NAME = "full_name";
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_EMPTY = "";
private EditText etUsername;
private EditText etPassword;
private EditText etConfirmPassword;
private EditText etFullName;
private String username;
private String password;
private String confirmPassword;
private String fullName;
private ProgressDialog pDialog;
private String register_url = "http://10.0.2.2/user102/register.php";
private SessionHandler session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionHandler(getApplicationContext());
setContentView(R.layout.activity_register);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
etConfirmPassword = findViewById(R.id.etConfirmPassword);
etFullName = findViewById(R.id.etFullName);
Button login = findViewById(R.id.btnRegisterLogin);
Button register = findViewById(R.id.btnRegister);
//Launch Login screen when Login Button is clicked
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(RegisterActivity.this, Login.class);
startActivity(i);
finish();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Retrieve the data entered in the edit texts
username = etUsername.getText().toString().toLowerCase().trim();
password = etPassword.getText().toString().trim();
confirmPassword = etConfirmPassword.getText().toString().trim();
fullName = etFullName.getText().toString().trim();
if (validateInputs()) {
registerUser();
}
}
});
}
/**
* Display Progress bar while registering
*/
private void displayLoader() {
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Signing Up.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Launch Dashboard Activity on Successful Sign Up
*/
private void loadDashboard() {
Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
startActivity(i);
finish();
}
private void registerUser() {
displayLoader();
JSONObject request = new JSONObject();
try {
//Populate the request parameters
request.put(KEY_USERNAME, username);
request.put(KEY_PASSWORD, password);
request.put(KEY_FULL_NAME, fullName);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("JSON= "+ request.toString());
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, register_url, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
//Check if user got registered successfully
if (response.getInt(KEY_STATUS) == 0) {
//Set the user session
session.loginUser(username,fullName);
loadDashboard();
}else if(response.getInt(KEY_STATUS) == 1){
//Display error message if username is already existsing
etUsername.setError("Username already taken!");
etUsername.requestFocus();
}else{
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
System.out.println("Error: "+error.getMessage());
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
/**
* Validates inputs and shows error if any
* #return
*/
private boolean validateInputs() {
if (KEY_EMPTY.equals(fullName)) {
etFullName.setError("Full Name cannot be empty");
etFullName.requestFocus();
return false;
}
if (KEY_EMPTY.equals(username)) {
etUsername.setError("Username cannot be empty");
etUsername.requestFocus();
return false;
}
if (KEY_EMPTY.equals(password)) {
etPassword.setError("Password cannot be empty");
etPassword.requestFocus();
return false;
}
if (KEY_EMPTY.equals(confirmPassword)) {
etConfirmPassword.setError("Confirm Password cannot be empty");
etConfirmPassword.requestFocus();
return false;
}
if (!password.equals(confirmPassword)) {
etConfirmPassword.setError("Password and Confirm Password does not match");
etConfirmPassword.requestFocus();
return false;
}
return true;
}
Php Code:
<?php
$response = array();
include 'db/db_connect.php';
include 'db/functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
//convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) &&
isset($input['password']) &&
isset($input['full_name'])){
$username = $input['username'];
$password = $input['password'];
$fullName = $input['full_name'];
//Check if user already exist
if(!userExists($username)){
//Get a unique Salt
$salt = getSalt();
//Generate a unique password Hash
$passwordHash = password_hash(concatPasswordWithSalt($password,$salt),PASSWORD_DEFAULT);
//Query to register new user
$insertQuery = "INSERT INTO user_data(username, full_name, password_hash, salt) VALUES (?,?,?,?)";
if($stmt = $con->prepare($insertQuery)){
$stmt->bind_param("ssss",$username,$fullName,$passwordHash,$salt);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "User created";
$stmt->close();
}
}
else{
$response["status"] = 1;
$response["message"] = "User exists";
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing
mandatory parameters";
}
echo json_encode($response);
?>
Does the register_url string cannot be converted? I am very new to this. Thank you
Try like this
try{
JSONArray parametersForPhp = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(key,value);
jsonObject.put(key,value);
parametersForPhp.put(jsonObject);
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpurl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG,response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch(Exception e){
e.printStackTrace();
}
Related
so I'm new to android apps developement and currently trying to make an app which lets the user login with their info from the database.
I have followed tutorials from youtube and currently am stuck with this problem: Value Connected of type java.lang.String cannot be converted to JSONObject
Login.php
<?php if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
require_once 'connect.php';
$sql = "SELECT * FROM users_table WHERE email='$email' ";
$response = mysqli_query($conn, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1 ) {
$row = mysqli_fetch_assoc($response);
if ( password_verify($password, $row['password']) ) {
$index['name'] = $row['name'];
$index['email'] = $row['email'];
$index['id'] = $row['id'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}?>
Login class
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Login extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN = "https://interntest1.000webhostapp.com/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loading = findViewById(R.id.loading);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_login = findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPass = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPass.isEmpty()) {
Login(mEmail, mPass);
} else {
email.setError("Please insert email");
password.setError("Please insert 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);
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();
String id = object.getString("id").trim();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +error.toString(), Toast.LENGTH_SHORT).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);
}
}
Currently I am working on developing an app through Android Studio and working on coding the login and registration capabilities. We send newly registered users' info to a MySQL database externally (i.e. not locally) through PHP, and also want to log registered users into the app. At the moment, the Android app is not sending the PHP file the information the user types into the text boxes. I put a tracer into the PHP file and it shows that the values are coming up null.
Here is my MainActivity.java:
package android.capstone.registerlogin;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import static android.capstone.registerlogin.R.id.etCreateAccEmail;
import static android.capstone.registerlogin.R.id.etCreateAccPassword;
import static android.capstone.registerlogin.R.id.etCreateAccUsername;
public class MainActivity extends Activity {
private EditText etUserName, etPassWord, etEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
etPassWord = (EditText) findViewById(etCreateAccPassword);
etUserName = (EditText) findViewById(etCreateAccUsername);
etEmail = (EditText) findViewById(etCreateAccEmail);
final TextView createAcc = (TextView) findViewById(R.id.tvCreateAcc);
createAcc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* creating this intent shows where you're starting and
where you want to go, we want to get the to the create account page
called RegisterUser.java
first line creates the intent
*/
Intent createIntent = new Intent(MainActivity.this, CreateAccount.class);
//second line makes the intent actually happen .startActivity
MainActivity.this.startActivity(createIntent);
}
});
}
public void signup(View v) {
String UserName = etUserName.getText().toString();
String PassWord = etPassWord.getText().toString();
String Email = etEmail.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(UserName, PassWord, Email);
}
}
Here is my SignupActivity.java:
package android.capstone.registerlogin;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String userName = arg0[0];
String passWord = arg0[1];
String eMail = arg0[2];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&email=" + URLEncoder.encode(eMail, "UTF-8");
link = "http://cgi.soic.indiana.edu/~gabschle/signup.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successful.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted. Signup failed." + jsonStr, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Here is my CreateAccount.java:
package android.capstone.registerlogin;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.capstone.registerlogin.R.id.etCreateAccEmail;
import static android.capstone.registerlogin.R.id.etCreateAccPassword;
import static android.capstone.registerlogin.R.id.etCreateAccUsername;
public class CreateAccount extends Activity {
private EditText etUserName, etPassWord, etEmail;
private Button mButton;
//private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
etPassWord = (EditText) findViewById(etCreateAccPassword);
etUserName = (EditText) findViewById(etCreateAccUsername);
etEmail = (EditText) findViewById(etCreateAccEmail);
final String UserName = etUserName.getText().toString();
final String PassWord = etPassWord.getText().toString();
final String Email = etEmail.getText().toString();
mButton = (Button) findViewById(R.id.bCreateAccSignUp);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(CreateAccount.this).execute(UserName, PassWord, Email);
}
});
}
public void signup(View v) {
String UserName = etUserName.getText().toString();
String PassWord = etPassWord.getText().toString();
String Email = etEmail.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(UserName, PassWord, Email);
}
}
Here is my PHP file:
<?php
$con=mysqli_connect("db.soic.indiana.edu","caps16_team19","capstoneteam19","caps16_team19");
if (mysqli_connect_errno($con))
{
echo '{"query_result":"ERROR"}';
}
$userName = $_GET['username'];
$passWord = $_GET['password'];
$tDate = $_GET['date'];
$tDate = date('Y-m-d');
$eMail =$_GET['email'];
if($eMail == null) {
echo '{"query_result":"FAILURE"}';
} else {
$result = mysqli_query($con,"INSERT INTO account (username, password, activated, email) VALUES ('$userName', '$passWord', '$tDate','$eMail')");
if($result == true) {
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
}
}
mysqli_close($con);
?>
Let me know if you need additional files!
Thanks for your help!
you're getting the values from the text fields before they'are assigned (during onCreate).
Change to this:
mButton = (Button) findViewById(R.id.bCreateAccSignUp);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String UserName = etUserName.getText().toString();
String PassWord = etPassWord.getText().toString();
String Email = etEmail.getText().toString();
//Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(CreateAccount.this).execute(UserName, PassWord, Email);
}
});
ps.: that context inside SignupActivity is a memory leak.
So first of all, im new to this kind of stuff. I got an app with registration activity. Everything works fine except messages after successful/unsuccessful try. Android studio gives me
JSONException: Value of type java.lang.String cannot be converted to JSONObject
and I have completely no idea how to fix that. Anyone here that could help at least a bit? Thanks!
package info.logirej.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import info.logirej.R;
import info.logirej.app.AppConfig;
import info.logirej.app.AppController;
import info.logirej.helper.SQLiteHandler;
import info.logirej.helper.SessionManager;
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputImie;
private EditText inputNazwisko;
private EditText inputEmail;
private EditText inputPassword;
private EditText inputPin;
private EditText inputTelefon;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputImie = (EditText) findViewById(R.id.imie);
inputNazwisko = (EditText) findViewById(R.id.nazwisko);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
inputPin = (EditText) findViewById(R.id.pin);
inputTelefon = (EditText) findViewById(R.id.telefon);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String imie = inputImie.getText().toString().trim();
String nazwisko = inputNazwisko.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
String pin = inputPin.getText().toString().trim();
String telefon = inputTelefon.getText().toString().trim();
if (!imie.isEmpty() && !nazwisko.isEmpty() && !email.isEmpty() && !password.isEmpty() && !pin.isEmpty() && !telefon.isEmpty()) {
registerUser(imie, nazwisko, email, password, pin, telefon);
} else {
Toast.makeText(getApplicationContext(),
"Prosze wprowadzić dane!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String imie, final String nazwisko, final String email, final String pin, final String telefon,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Tworzę konto");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Stan rejestracji: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String imie = user.getString("imie");
String nazwisko = user.getString("nazwisko");
String email = user.getString("email");
String pin = user.getString("pin");
String telefon = user.getString("telefon");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(imie, nazwisko, email, pin, telefon, uid, created_at);
Toast.makeText(getApplicationContext(), "Konto zostało utworzone! Zapraszamy do logowania!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Błąd rejestracji: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("imie", imie);
params.put("nazwisko", nazwisko);
params.put("email", email);
params.put("password", password);
params.put("pin", pin);
params.put("telefon", telefon);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Your problem in the following line:
JSONObject jObj = new JSONObject(response);
Obviously, your response is invalid JSON, since I can not see how it is built, can't tell you much more.
Try to validate your JSON response here
http://jsonlint.com/#
I'm very new to android. I tried to create login app with PHP and Mysql. I referred to a source where he used a library called GenAsync.jar to avoid many coding "he said". However, i followed every bit of his instruction but unfortunately I cant login. What is the problem? Could it be because am running it on mobile device and not emulator as he demonstrated? I also use an online server but his demo used a localhost. Pls help me out? Many Thanks in advance.
package issa.example.com.mysqldatabase;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.asynctask.AsyncResponse;
import com.kosalgeek.asynctask.PostResponseAsyncTask;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements AsyncResponse{
EditText etUsername, etPassword;
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword = (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("btnLogin", "Login");
postData.put("mobile", "android");
postData.put("user_name", etUsername.getText().toString());
postData.put("pass_word", etPassword.getText().toString() );
PostResponseAsyncTask loginTask =
new PostResponseAsyncTask(MainActivity.this, postData);
loginTask.execute("http://mchucha.com/android/logini.php");
}
});
}
#Override
public void processFinish(String output) {
if(output.equals("success")){
Intent intent = new Intent(MainActivity.this, Activity2.class);
Toast.makeText(this, "Login Successfully",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
}
PHP script text
<?php
$servername = "localhost";
$username = "mchuchac_user";
$password = "123";
$dname = "mchuchac_db";
$conn = mysqli_connect($servername, $username, $password, $dname);
if (!$conn){
die ("connection failed: " .mysqli_connect_error());
}
else {
echo " connection success";
}
?>
<?PHP
include_once("connection.php");
if( isset($_POST['user_name']) && isset($_POST['pass_word']) ) {
$username = $_POST['user_name'];
$password = $_POST['pass_word'];
$query = "SELECT username, password FROM tbl_client ".
" WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
if($result->num_rows > 0){
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo " Login success";
} else{
echo "Login Failed <br/>";
}
}
?>
although your question not so clear (what have you done for that fail and have the username and password value passed to php/web service) I want to try help you by do some steps to get your fail/error.
first, make sure the connection of DB is well.
$conn = mysqli_connect($servername, $username, $password, $dname);
if (!$conn){
die ("connection failed: " .mysqli_connect_error());
}
else {
echo " connection success";
}
Check the username and password value have it passed in webservice, by echoing $username and $password.
If until 2nd step run well, please to debug the query by doing like this:
$query = "SELECT username, password FROM tbl_client ".
" WHERE username = '$username' AND password = '$password'";
Run that query in mysql application (phpmyadmin for example).
Thats my explanation, hopefully it will help you.
Try my webservices of Login which i have given
Login.php
<?php
include_once('connect.php');
error_reporting( error_reporting() & ~E_NOTICE );
$r_emailid = $_GET["r_emailid"];
$r_password = $_GET["r_password"];
$sql = "select * from admin_registration
where r_emailid = '$r_emailid' and r_password = '$r_password'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
if(empty($output))
{
$response['success'] =false;
$response['message']="Invalid Login";
print(json_encode($response));
}
else
{
$response['Data']=$output;
$response['success']=true;
$response['message']="Login Successfully";
print(json_encode($response));
}
?>
connect.php
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "adurec";
$con = #mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,
$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
?>
this response you can check
Like this you will get the output that makes sure your php side is correct you have to do on your android side
**Login.java**
public class Login extends Activity implements OnClickListener {
String regId = "";
public static final String REG_ID = "regId";
public static final String EMAIL_ID = "eMailId";
EditText et_username, et_password;
public Button bt_login;
public static String Username, Password, Name;
// Connection detector
ConnectionDetector cd;
private ProgressDialog pDialog;
String URL, URLmessage;
Animation shake;
private boolean validEmail(String email) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
return pattern.matcher(email).matches();
}
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.login_details);
cd = new ConnectionDetector(getApplicationContext());
addintialvalues();
et_username.setText(SettingsFragment.getDefaults("Username", getApplicationContext()));
}
private void addintialvalues() {
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
bt_login = (Button) findViewById(R.id.bt_login);
shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
bt_login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_login:
if (cd.isWifiAvailable() || cd.isNetworkAvailable()) {
// Get username, password from EditText
Username = et_username.getText().toString();
Password = et_password.getText().toString();
if ((!validEmail(Username))) {
et_username.startAnimation(shake);
et_username.setError("Please enter valid email");
} else if (Password.length() <= 0) {
et_password.startAnimation(shake);
et_password.setError("Password Should not be Empty");
} else if (Password.length() != 4) {
et_password.startAnimation(shake);
et_password.setError("Enter 4 Digit");
} else {
try {
URL = "http://localhost/mis/login.php?"
+ "r_emailid="
+ Username
+ "&r_password="
+ Password;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
new LoginTask().execute();
}
} else {
Toast.makeText(getApplicationContext(), "Please Check Internet.....", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
/**
* Async task class to get json by making HTTP call
*/
public class LoginTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please Wait.....");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// JSONArray data = null;
String jsonstr = jParser.makeServiceCall(URL, JSONParser.POST);
Log.d("Json url view string", jsonstr);
if (jsonstr != null) {
try {
JSONObject jobj = new JSONObject(jsonstr);
URLmessage = jobj.getString("message").toString();
JSONArray jarray = jobj.getJSONArray("Data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobjj = jarray.getJSONObject(i);
Name = jobjj.getString("r_name");
Username = jobjj.getString("r_emailid");
Password = jobjj.getString("r_password");
}
} catch (JSONException e1) {
e1.printStackTrace();
}
} else {
Log.e("Login Screen", "Couldn't get any data from the url");
}
return null;
}
#SuppressLint("ShowToast")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
if (URLmessage.matches("Invalid Login")) {
Toast.makeText(getApplicationContext(), "Invalid Login.....",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Login Successful...",
Toast.LENGTH_SHORT).show();
Password = et_password.getText().toString();
Username = et_username.getText().toString();
Intent k = new Intent(getBaseContext().getApplicationContext(),
MainActivity.class);
startActivity(k);
}
}
}
JSONParser.java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class JSONParser {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public JSONParser() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
**Webservices of Login**
<?php
include_once('connect.php');
$R_emailid = $_GET["R_emailid"];
$R_password = $_GET["R_password"];
$sql="select * from registration
where R_emailid='$R_emailid' and R_password='$R_password'";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$output[] = $obj;
}
if(empty($output))
{
$response['success']=false;
$response['message']="user does not Exist";
print(json_encode($response));
}
else
{
$response['Data']=$output;
$response['success']=true;
$response['message']="login successfulll";
print(json_encode($response));
}
?>
The complete demo on how to login with json with use of webservices
Refer it and if any query do ask me
Kindly abort please if you find it useful
Thank you
My application cannot read data from a server, but I can't find the error in my code or its error log. In fact, after checking my API, the link works fine. INTERNET and WRITE_EXTERNAL_STORAGE permission are already set in the manifest.
My code:
package com.berthojoris.bacaberita;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.berthojoris.bacaberita.adapter.BeritaAdapter;
import com.berthojoris.bacaberita.bean.BeritaBean;
import com.berthojoris.bacaberita.lib.Constants;
import com.berthojoris.bacaberita.lib.ImageLoader;
import com.berthojoris.bacaberita.lib.JSONParser;
import com.berthojoris.bacaberita.lib.Utils;
import com.berthojoris.bacaberita.sqlite.UtilBerita;
public class Berita extends ListActivity {
ProgressDialog dialog;
private static String urlBerita = "http://newapi.bacaberita.com/berita";
public ImageLoader imageLoader;
private JSONParser jParser;
Toast msg;
TextView notfound;
JSONArray contacts = null;
ArrayList<BeritaBean> AmbilDataBean = new ArrayList<BeritaBean>();
BeritaAdapter adapter;
UtilBerita UtilBerita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
UtilBerita = new UtilBerita(this);
imageLoader = new ImageLoader(this.getApplicationContext());
notfound = (TextView) findViewById(R.id.notfound);
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
AmbilDataBean = new ArrayList<BeritaBean>();
adapter = new BeritaAdapter(this, AmbilDataBean);
setListAdapter(adapter);
Utils.setPolicyThread();
// Creating JSON Parser Instance
jParser = new JSONParser();
Log.e("Berita Activity", "TOTAL SIZE DATABASE : "
+ UtilBerita.ReadBerita().size());
if (UtilBerita.ReadBerita().size() < 1) {
Log.e("Berita Activity", "DATABASE KOSONG. JALANKAN ASYNC");
new async().execute();
} else {
AmbilDataBean = UtilBerita.ReadBerita();
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity", "DATABASE DIAMBIL");
}
setTimerRefresh();
}// Tutup onCreate
private class async extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
AmbilDataBean = new ArrayList<BeritaBean>();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String jsonContent = jParser.getJSONDataFromUrl(urlBerita);
Log.e("Berita Activity", "PROSES BACKGROUND DIJALANKAN");
return jsonContent;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.length() > 0) {
dialog.dismiss();
// parsing disini
JSONObject json = null;
try {
json = new JSONObject(result);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(Constants.TAG_ITEM);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(Constants.TAG_MenuID);
String judul = c.getString(Constants.TAG_Title);
//String img = c.getString(Constants.TAG_Link);
String desk = c.getString(Constants.TAG_Post);
String date = c.getString(Constants.TAG_Created);
BeritaBean mb = new BeritaBean();
mb.setID(id);
mb.setTitle(judul);
//mb.setLink("http://" + img);
mb.setPost(desk);
mb.setCreated(date);
AmbilDataBean.add(mb);
}
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity",
"PROSES SELESAI. DATA AKAN DITAMPILKAN");
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
}
});
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
} // Tutup if (result.length() > 0)
else {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Data Not Found. Please try again...",
Toast.LENGTH_SHORT).show();
}
if (AmbilDataBean.size() < 1) {
notfound.setVisibility(View.VISIBLE);
getListView().setVisibility(View.GONE);
} else {
for (BeritaBean bean : AmbilDataBean) {
if (UtilBerita.getDetailWhereID(bean.getID()).getID() == null) {
Log.e("Berita Activity",
"Insert database : " + bean.getID());
UtilBerita.CreateData(bean);
} else {
Log.e("Berita Activity",
"Update database : " + bean.getID());
UtilBerita.UpdateBerita(bean);
}
}
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
} // Tutup onPostExecute
} // Tutup private class async extends AsyncTask
// =========================================================================================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).setNegativeButton(R.string.no, null).show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
// =========================================================================================================================
// Declare the timer
Timer timer = null;
final Handler handler = new Handler();
public void setTimerRefresh() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Log.e("Main Activity", "RUNNING TASK...");
new async().execute();
}
});
}
}, 1000 * 60 * 1, 1000 * 25);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer = null;
}
if (UtilBerita != null)
UtilBerita.Close();
}
}
== UPDATE ==
My Constants class :
package com.berthojoris.bacaberita.lib;
public class Constants {
public static final String TAG_ITEM = "items";
public static final String TAG_MenuID = "Menu_ID";
public static final String TAG_IsDisplay = "IsDisplay";
public static final String TAG_CategoryName = "CategoryName";
public static final String TAG_CategoryID = "Category_ID";
public static final String TAG_ContentID = "Content_ID";
public static final String TAG_Title = "Title";
public static final String TAG_Post = "Post";
public static final String TAG_Link = "Link";
public static final String TAG_Meta = "Meta";
public static final String TAG_CreatedBy = "CreatedBy";
public static final String TAG_Created = "Created";
public static final String TAG_StartDisplay = "StartDisplay";
public static final String TAG_Counter = "counter";
}
You have to retrieve jsonArray from the jsonObject items. But in your code you have not used items anywhere. Try this way:
String jsonStr = new ConnectionService().connectionGet("http://newapi.bacaberita.com/berita","");
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println("..........JSON OBJECT.............");
System.out.println(jsonObject); // full json Object
JSONArray jsonArray = jsonObject.getJSONArray("items");
System.out.println("..........JSON ARRAY PARSING.............");
for(int i=0;i<jsonArray.length();i++)
{
String menu_id = jsonArray.getJSONObject(i).getString("Menu_ID");
String is_display = jsonArray.getJSONObject(i).getString("IsDisplay");
System.out.println("MENU_ID: "+menu_id);
System.out.println("IsDisplay: "+is_display);
}
The methods used in above example are as follows:
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}