我正在尝试使用mysql数据库和php创建一个android应用程序。该代码在使用API 21的设备上运行良好,但是在使用API 19的设备上,出现此错误:
异常:java.lang.String类型的值异常无法转换为JSONObject
我看到了JSONArray的解决方案,但没有JSONObject的解决方案。
这是MainActivity.java:
public class MainActivity extends Activity {
EditText name, password;
String Name, Password;
Context ctx = this;
String NAME = null, PASSWORD = null, EMAIL = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.main_name);
password = (EditText) findViewById(R.id.main_password);
}
public void main_register(View v) {
startActivity(new Intent(this, Register.class));
}
public void main_login(View v) {
Name = name.getText().toString();
Password = password.getText().toString();
BackGround b = new BackGround();
b.execute(Name, Password);
}
class BackGround extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String name = params[0];
String password = params[1];
String data = "";
int tmp;
try {
URL url = new URL("https://something.com/login.php");
String urlParams = "name=" + name + "&password=" + password;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while ((tmp = is.read()) != -1) {
data += (char) tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
@Override
protected void onPostExecute(String s) {
String err = null;
try {
JSONObject root = new JSONObject(s);
JSONObject user_data = root.getJSONObject("user_data");
NAME = user_data.getString("name");
PASSWORD = user_data.getString("password");
EMAIL = user_data.getString("email");
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: " + e.getMessage();
}
Intent i = new Intent(ctx, Home.class);
i.putExtra("name", NAME);
i.putExtra("password", PASSWORD);
i.putExtra("email", EMAIL);
i.putExtra("err", err);
startActivity(i);
}
}
}
有什么解决办法吗?