Very good to all and first of all thank you for reading this
I've been pulling my hair for a couple of days because I try to create an application in android studio, but I can not get past the attempt to create the user account, I use PHP, wamp and android studio but there's no way, this is the error that comes to me:
E/JSON Parser: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
V/params: [nombre=afafa, clave=afafa, correo=afa, pregunta=1 ¿En que ciudad nació?, respuesta=1313, informacion=1]
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
Process: com.example.bruno.thulin, PID: 27878
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:354)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.bruno.thulin.inicio.CrearCuenta$CrearNuevoUsuario.doInBackground(CrearCuenta.java:215)
at com.example.bruno.thulin.inicio.CrearCuenta$CrearNuevoUsuario.doInBackground(CrearCuenta.java:164)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
I have tried it in a thousand ways but I can not find the solution, this is my code:
the php to create user:
create_user.php
<?php
/*
*Este código creará los usuarios nuevos
*/
// Array para la respuesta del JSON
$response = array();
// comprobación de los campos requeridos
if (isset($_POST['nombre']) && isset($_POST['clave']) && isset($_POST['correo']) && isset($_POST['pregunta']) && isset($_POST['respuesta'])) {
$nombre = $_POST['nombre'];
$clave = $_POST['clave'];
$correo = $_POST['correo'];
$pregunta = $_POST['pregunta'];
$respuesta = $_POST['respuesta'];
$informacion = $_POST['informacion'];
// se incluye la clase de db connect
include('db_connect.php');
// Conectando con la bd
$db = new DB_CONNECT();
// mysql insertando nueva fila
$link = mysqli_connect("localhost","thulin","","thulin");
$result = mysqli_query($link,'INSERT INTO usuario (nombre, clave, correo, pregunta, respuesta, informacion) VALUES ($nombre, $clave, $correo, $pregunta, $respuesta, $informacion)');
// Comprobación de si la fila se ha insertado o no
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Cuenta creada con exito.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Ha ocurrido un error.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Falta algún campo";
// echoing JSON response
echo json_encode($response);
}
?>
And this is the class in Android Studio that calls the php and should create the account:
Create Account.java
package com.example.bruno.thulin.inicio;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.bruno.thulin.R;
import com.example.bruno.thulin.json.JSONparser;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class CrearCuenta extends AppCompatActivity {
private EditText etNombre, etPassword, etCorreo, etRespuesta;
private Button btnCrearCuenta;
private CheckBox informacion;
private boolean pregunta;
private ProgressDialog pDialog;
private JSONparser jsonParser = new JSONparser();
private static String url_crear_usuario;
private static final String TAG_SUCCESS = "success";
private String nombre;
private String password;
private String correo;
private String eleccion;
private String respuesta;
private String infostring;
private int info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crear_cuenta);
final Spinner dropdown = findViewById(R.id.spinnercreacioncuenta);
etNombre = findViewById(R.id.etnombrecreacioncuenta);
etPassword = findViewById(R.id.etpasswordcreacioncuenta);
etCorreo = findViewById(R.id.etcorreocreacioncuenta);
etRespuesta = findViewById(R.id.etrespuestacreacioncuenta);
btnCrearCuenta = findViewById(R.id.btncrearcuenta);
informacion = findViewById(R.id.checkinfocreacioncuenta);
url_crear_usuario = "http://192.168.8.100/thulin/crear_usuario.php";
final Typeface type = Typeface.createFromAsset(getAssets(), "fonts/doriel.otf");
final String[] items = new String[]{"1.- ¿En que ciudad nació?", "2.- ¿Cual es el nombre de su primer amor?", "3.- ¿Como se llama su pareja actual?", "4.- ¿De que raza es su perro?", "5.- ¿Como se llama su perro?", "6.- ¿Como se llamaba su primer instituto?", "7.- ¿Como se llama su madre?", "8.- ¿Como se llama su padre?"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_spinner_style, items) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
((TextView) v).setTextSize(16);
((TextView) v).setTypeface(type);
Log.v("estoy aqui", items.toString());
return v;
}
public View getDropDownView(int position, View convertView,ViewGroup parent) {
View v = super.getDropDownView(position, convertView,parent);
((TextView) v).setGravity(Gravity.CENTER);
((TextView) v).setTypeface(type);
return v;
}
};
dropdown.setAdapter(adapter);
etNombre.setTypeface(type);
etPassword.setTypeface(type);
etCorreo.setTypeface(type);
etRespuesta.setTypeface(type);
btnCrearCuenta.setTypeface(type);
informacion.setTypeface(type);
btnCrearCuenta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ( etNombre.getText().toString().equals("") || etPassword.getText().toString().equals("") || etCorreo.getText().toString().equals("") || etRespuesta.toString().equals("")) {
if (etNombre.getText().toString().equals("")) {
Toast ToastVacio = Toast.makeText(getApplicationContext(), "No has puesto el nombre", Toast.LENGTH_LONG);
ToastVacio.show();
}
else if (etPassword.getText().toString().equals("")) {
Toast ToastVacio = Toast.makeText(getApplicationContext(), "No has puesto la contraseña", Toast.LENGTH_LONG);
ToastVacio.show();
}
else if (etCorreo.getText().toString().equals("")) {
Toast ToastVacio = Toast.makeText(getApplicationContext(), "No has puesto el correo", Toast.LENGTH_LONG);
ToastVacio.show();
}
else if (etRespuesta.getText().toString().equals("")) {
Toast ToastVacio = Toast.makeText(getApplicationContext(), "No has puesto una respuesta", Toast.LENGTH_LONG);
ToastVacio.show();
}
}
else {
nombre = etNombre.getText().toString();
password = etPassword.getText().toString();
correo = etCorreo.getText().toString();
eleccion = dropdown.getSelectedItem().toString();
respuesta = etRespuesta.getText().toString();
if (informacion.isChecked()) {
info = 1;
}
else {
info = 0;
}
new CrearNuevoUsuario().execute();
}
}
});
}
@SuppressLint("StaticFieldLeak")
class CrearNuevoUsuario extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CrearCuenta.this);
pDialog.setMessage("Creando Usuario");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
// Building Parameters
infostring = Integer.toString(info);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair ("nombre", nombre));
params.add(new BasicNameValuePair("clave", password));
params.add(new BasicNameValuePair("correo", correo));
params.add(new BasicNameValuePair("pregunta", eleccion));
params.add(new BasicNameValuePair("respuesta", respuesta));
params.add(new BasicNameValuePair("informacion", infostring));
Log.v("nombre", nombre);
Log.v("clave", password);
Log.v("correo", correo);
Log.v("eleccion", eleccion);
Log.v("respuesta", respuesta);
Log.v("informacion", infostring);
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_crear_usuario,
"POST", params);
Log.v("params", params.toString());
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), InicioPersonaje.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Greetings to all, and I hope you can help me, I am very well android studio and I am a programmer, but I do not have much idea of servers and php and I am starting in that field.
Thanks in advance.
JSONparser.java class:
package com.example.bruno.thulin.json;
import android.util.Log;
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.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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 == "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 == "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;
}
}