I'm trying to learn android development, I'm using Android Studio. I need to access an external database (to insert, get itens ... CRUD) and I've found a tutorial that tells me to use koush ion, from Android using Ion, I call a web page that is a Laravel 7 Route. When I call without parameters, it works very well and I can get in Android the returned value. But when I use "setBodyParameter", I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.gson.JsonElement com.google.gson.JsonObject.get(java.lang.String)' on a null object reference
My laravel route just calls this function:
function cadastrar(){
date_default_timezone_set('America/Sao_Paulo');
$resposta = array();
$myUser = null;
$nome = isset($_POST['nome']) ? $_POST['nome'] : 'Teste 2';
$email = isset($_POST['email']) ? $_POST['email'] : '[email protected]';
$myUser = new Usuario;
$myUser->nome = $nome;
$myUser->email = $email;
$myUser->save();
$resposta = array('id' => strval($myUser->id_usuario), 'nome' => $myUser->nome, 'email' => $myUser->email);
return json_encode($resposta);
}
My Laravel route is Route::get (but when I change it to Route::post I get an error too).
And my Android code that calls this page is:
final TextView txtErro = (TextView) findViewById(R.id.textView4);
txtErro.setText("");
final String strNome = nome.getText().toString();
final String strEmail = email.getText().toString();
String url = "**My URL to the route in laravel**";
Ion.with(MainActivity.this)
.load(url)
.setBodyParameter("nome", strNome)
.setBodyParameter("email", strEmail)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
try {
txtErro.setText(result.get("id").getAsString());
} catch (Exception erro) {
txtErro.setText(erro.toString());
}
}
});
When I comment the two lines of ".setBodyParameter", I get the returned value from laravel (if laravel route is Route::get). When I change the line of "load" to "load("POST", url)", I get an error.
I tried something related to CORS that I found here in StackOverflow and in my Laravel Kernel.php I commented the line that calls "VerifyCsrfToken", but still didn't working.
(Finally, I'm sorry if have something wrong in my english)
Did you try logging the Exception e and JsonObject result? or set logging for the request and watch it in logcat
.setLogging("MyLogs", Log.DEBUG)