Php 如何在android活动中读取Json响应。
当未在textedit中填写详细信息时,我从php获得json响应,响应为Php 如何在android活动中读取Json响应。,php,android,json,android-activity,android-asynctask,Php,Android,Json,Android Activity,Android Asynctask,当未在textedit中填写详细信息时,我从php获得json响应,响应为{“success”:0,“message”:“请输入有效的详细信息”。}。因此,我想阅读success和message值,并将该消息显示为Toast。我该怎么做呢 以下是异步任务: class CreateUser extends AsyncTask<String, String, String> { /** * Before starting background thread Sh
{“success”:0,“message”:“请输入有效的详细信息”。}
。因此,我想阅读success和message值,并将该消息显示为Toast
。我该怎么做呢
以下是异步任务:
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
//int success;
// try {
// Building Parameters
HashMap<String, String> Params = new HashMap<String, String>();
Params.put("username", username);
Params.put("password", password);
Params.put("email", email);
Params.put("ph", ph);
Log.d("request!", "starting");
String encodedStr = getEncodedData(Params);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(LOGIN_URL);
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString(); //Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check","The values :");
Log.i("custom_check",line);
//Object b = line;
Log.i("length", String.valueOf(line.length()));
if (line.length() == 55) {
Log.d("User Created!", line);
SharedPreferences set = getSharedPreferences (UserNum, 0);
set.edit().putString(uu,username).commit();
// Toast.makeText(Register.this, "User Registered", Toast.LENGTH_SHORT).show();
Intent i=new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
//return line.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", "failed");
// return b.getString(TAG_MESSAGE);
Toast.makeText(Register.this, "Username already in use", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Same return null, but if you want to return the read string (stored in line)
//then change the parameters of AsyncTask and return that type, by converting
//the string - to say JSON or user in your case
return null;
}
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
class CreateUser扩展异步任务{
/**
*在启动后台线程显示进度对话框之前
* */
布尔失败=假;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(Register.this);
setMessage(“正在创建用户…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…args){
//TODO自动生成的方法存根
//检查成功标签
//成功;
//试一试{
//建筑参数
HashMap Params=新的HashMap();
参数put(“用户名”,用户名);
参数put(“密码”,密码);
参数put(“电子邮件”,电子邮件);
参数put(“ph”,ph);
Log.d(“请求!”,“启动”);
字符串编码器DSTR=getEncodedData(参数);
//如果我们想从服务器读取一些数据,将使用
BufferedReader reader=null;
//连接处理
试一试{
//将地址字符串转换为URL
URL=新URL(登录\ URL);
//打开连接(未设置或使用连接超时)
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//Post方法
con.setRequestMethod(“POST”);
//启用使用POST方法输入值
//(基本上,在此之后,我们可以将dataToSend写入POST方法的主体)
con.设置输出(真);
OutputStreamWriter writer=新的OutputStreamWriter(con.getOutputStream());
//将数据写入发送到outputstreamwriter
writer.write(编码器);
//将数据发送到服务器-这足够将数据发送到服务器
//但要读取服务器的响应,您必须执行以下过程
writer.flush();
//数据读取程序-基本上逐行读取数据
StringBuilder sb=新的StringBuilder();
reader=newbufferedReader(newInputStreamReader(con.getInputStream());
弦线;
而((line=reader.readLine())!=null){//Read直到有可用的东西为止
sb.append(line+“\n”);//逐行读取和保存-不是一次全部
}
line=sb.toString();//保存以字符串形式接收的完整数据,可以采用不同的方法
//只需检查Logcat中接收到的值
Log.i(“自定义检查”,“值:”);
Log.i(“自定义检查”,第行);
//对象b=直线;
Log.i(“长度”,String.valueOf(line.length());
if(line.length()=55){
Log.d(“用户创建!”,第行);
SharedReferences集=GetSharedReferences(UserNum,0);
set.edit().putString(uu,username.commit();
//Toast.makeText(Register.this,“用户注册”,Toast.LENGTH_SHORT.show();
Intent i=新的Intent(getApplicationContext(),MainActivity.class);
星触觉(i);
完成();
//返回行.getString(标记消息);
}否则{
Log.d(“登录失败!”,“失败”);
//返回b.getString(TAG_消息);
Toast.makeText(Register.this,“用户名已在使用”,Toast.LENGTH_SHORT.show();
}
}捕获(例外e){
e、 printStackTrace();
}最后{
if(读卡器!=null){
试一试{
reader.close();//关闭
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
//相同的返回null,但如果要返回读取字符串(存储在第行中)
//然后更改AsyncTask的参数并通过转换返回该类型
//字符串-在您的示例中表示JSON或user
返回null;
}
私有字符串getEncodedData(地图数据){
StringBuilder sb=新的StringBuilder();
for(字符串键:data.keySet()){
字符串值=null;
试一试{
value=URLEncoder.encode(data.get(key),“UTF-8”);
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
如果(sb.length()>0)
某人附加(“&”);
sb.追加(键+“=”+值);
}
使某人返回字符串();
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//删除产品后关闭对话框
pDialog.disclose();
如果(文件url!=null){
Toast.makeText(Register.this,file_url,Toast.LENGTH_LONG.show();
}
}
}
这很简单,请将此代码放在=sb.toString()行下面
可能重复的
JSONObject jsonObject = new JSONObject(line);
String sucess=jsonObject.getString("success");
String message=jsonObject.getString("message");