我正在尝试从Android活动连接到我的sqldatabase的数据进行注册页面,我收到此错误" org.json.JSONException:Value
我知道我在SO上看过所有类似的问题。我累了过去7个小时才解决这个错误。我尝试了几乎所有东西,在网上搜索了很多,但无法得到这个错误的解决方案:
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
**** **** JSONParser.java
public class JSONParser {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
StrictMode.setThreadPolicy(policy);
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
// check for request method
if(method.equals("POST")){
Log.d("my", "method equals POST is working");
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d("my", "HTTp client is working");
HttpPost httpPost = new HttpPost(url);
Log.d("my", "HTTp post is working");
httpPost.setEntity(new UrlEncodedFormEntity(params));
Log.d("my", "url encoded");
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.d("my", "HTTp response is working");
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("my", "HTTp entity is working");
is = httpEntity.getContent();
Log.d("my", "getcontent is working");
}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);
Log.d("my", "buffer reader crated");
StringBuffer sb = new StringBuffer();
Log.d("my", "string buffer object crated");
String line = null;
while ((line = reader.readLine())!= null) {
sb.append(line + "\n");
Log.d("my", "line appended");
}
is.close();
Log.d("my", "inputstram closed");
json = sb.toString();
Log.d("my", "string buffer to string conversion");
} 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;
}
}
TAP_Cliente_nuevo.java
enter code here
公共类Tap_Cliente_Nuevo扩展了活动{
JSONParser parseadorJson = new JSONParser();
Button btn;
EditText RFC;
EditText Nombre;
EditText ApellidoP;
EditText ApellidoM;
EditText Telefono;
EditText Calle;
EditText Numero;
EditText Colonia;
EditText Municipio;
EditText Estado;
EditText CP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tap__cliente__nuevo);
RFC = (EditText)findViewById(R.id.txtRFCCliente);
Nombre = (EditText)findViewById(R.id.txtNombreCliente);
ApellidoP = (EditText)findViewById(R.id.txtApellidoPCliente);
ApellidoM = (EditText)findViewById(R.id.txtApellidoMCliente);
Telefono = (EditText)findViewById(R.id.txtTelefonoCliente);
Calle = (EditText)findViewById(R.id.txtCalleCliente);
Numero = (EditText)findViewById(R.id.txtNumeroCliente);
Colonia = (EditText)findViewById(R.id.txtColoniaCliente);
Municipio = (EditText)findViewById(R.id.txtMunicipioCliente);
Estado = (EditText)findViewById(R.id.txtEstadoCliente);
CP = (EditText)findViewById(R.id.txtCPCliente);
btn = (Button)findViewById(R.id.btnRegistrarCliente);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(RFC.getText().length()==0 ||
Nombre.getText().length()==0 ||
ApellidoP.getText().length()==0 ||
ApellidoM.getText().length()==0 ||
Telefono.getText().length()==0 ||
Calle.getText().length()==0 ||
Numero.getText().length()==0 ||
Colonia.getText().length()==0 ||
Municipio.getText().length()==0 ||
Estado.getText().length()==0 ||
CP.getText().length()==0){
Toast.makeText(getApplicationContext(), "Por favor llena los campos obligatorios", Toast.LENGTH_SHORT).show();
}else{
List<NameValuePair> parametros = new ArrayList<NameValuePair>();
parametros.add(new BasicNameValuePair("inRFC", RFC.getText().toString()));
parametros.add(new BasicNameValuePair("inNombre", Nombre.getText().toString()));
parametros.add(new BasicNameValuePair("inApPat", ApellidoP.getText().toString()));
parametros.add(new BasicNameValuePair("inApMat", ApellidoM.getText().toString()));
parametros.add(new BasicNameValuePair("inTel", Telefono.getText().toString()));
parametros.add(new BasicNameValuePair("inCalle", Calle.getText().toString()));
parametros.add(new BasicNameValuePair("inNum", Numero.getText().toString()));
parametros.add(new BasicNameValuePair("inCol", Colonia.getText().toString()));
parametros.add(new BasicNameValuePair("inMuni", Municipio.getText().toString()));
parametros.add(new BasicNameValuePair("inEsta", Estado.getText().toString()));
parametros.add(new BasicNameValuePair("inCP", CP.getText().toString()));
Log.e("Registro", obtenIpServidor());
parseadorJson.makeHttpRequest("http://192.168.1.72/tractofer/alta_clientes.php", "POST", parametros);
Toast.makeText(getApplicationContext(), "Datos Insertados correctamente", Toast.LENGTH_SHORT).show();
RFC.setText("");
Nombre.setText("");
ApellidoP.setText("");
ApellidoM.setText("");
Telefono.setText("");
Calle.setText("");
Numero.setText("");
Colonia.setText("");
Municipio.setText("");
Estado.setText("");
CP.setText("");
}
}
});
}
public String obtenIpServidor()
{
String ip=null;
SharedPreferences pref = getSharedPreferences("com.example.tractopartesycamiones_preferences",MODE_PRIVATE);
Log.e("Registro", "tipo_conexion: " + pref.getString("tipo_conexion", "1"));
if (pref.getString("tipo_conexion", "1").equals( "1"))
ip="192.168.1.72";
else
ip = pref.getString("ip_servidor", "0.0.0.0");
return ip;
}
}
alta_cliente.php
<?php
//Constantes
$db_usuario = "root";
$db_pass = "";
$db_host = "localhost";
$db_schema = "tractofer";
//Conexion con la base de datos
$enlace = mysql_connect($db_host, $db_usuario, $db_pass)
or die (' No se conecto al servidor');
mysql_select_db($db_schema,$enlace)
or die('Error al seleccionar la base de datos');
$respuesta = array();
$RFC = $_POST['inRFC'];
$Nombre = $_POST['inNombre'];
$ApPat = $_POST['inApPat'];
$ApMat = $_POST['inApMat'];
$Tel = $_POST['inTel'];
$Calle = $_POST['inCalle'];
$Num = $_POST['inNum'];
$Col = $_POST['inCol'];
$Muni = $_POST['inMuni'];
$Esta = $_POST['inEsta'];
$CP = $_POST['inCP'];
$db_query =
"INSERT INTO cliente VALUES('$RFC', '$Nombre', '$ApPat', '$ApMat', '$Tel', '$Calle', '$Num', '$Col', '$Muni', '$Esta', '$CP')";
//Ejecutamos el Query
$resultado = mysql_query($db_query,$enlace)
or die('Error en el query: ' .$db_query);
if($resultado)
{
$respuesta["success"]=1;
$respuesta["message"]="Usuario agregado";
echo json_encode($respuesta);
}
else
{ echo 'Error en el json'; }
//desconexion de la base de datos
@mysql_close($enlace);
?>
答案 0 :(得分:0)
在您的PHP
文件中,您正在使用echo
语句,这些语句也会作为回复输出。所以你的json
字符串包含一个html标签和/或行,因此无法解析它。
或者在json
字符串的某个地方,它包含<br />
标记,因此无法对其进行解析。