如何设置从php脚本接收标签的String变量?

时间:2013-12-13 07:54:14

标签: php android json

这是我的doInBackground

protected Integer doInBackground(String... args) {
  try {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", Username));
    params.add(new BasicNameValuePair("password", Password));

    Log.d("request!", "starting");
    JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);

    Log.d("Login attempt", json.toString());                
        success = json.getInt(TAG_SUCCESS);
    res = json.getString(TAG_MESSAGE);
    loginposition = json.getJSONArray(TAG_POSTS);

    for (int i = 0; i < loginposition.length(); i++) {
      JSONObject c = loginposition.getJSONObject(i);
      Position = c.getString(TAG_POSITION);
    }
  } catch (JSONException e) {
    Log.e(TAG, "JSON error", e);
    success = Integer.valueOf(0);
  }
  return success;
}

我将Position变量声明为String Position,我不知道为什么我的android json说我的成功不是1或null ..甚至我的标签帖子。

这是我的logcat

12-13 15:52:09.830: D/request!(27146): starting
12-13 15:52:13.139: D/Login attempt(27146): {"posts":["user"],"message":"Login Successful!","success":1}
12-13 15:52:13.149: E/(27146): JSON error
12-13 15:52:13.149: E/(27146): org.json.JSONException: Value user at 0 of type java.lang.String cannot be converted to JSONObject
12-13 15:52:13.149: E/(27146):  at org.json.JSON.typeMismatch(JSON.java:96)
12-13 15:52:13.149: E/(27146):  at org.json.JSONArray.getJSONObject(JSONArray.java:484)
12-13 15:52:13.149: E/(27146):  at com.pmss.Login$AttemptLogin.doInBackground(Login.java:157)
12-13 15:52:13.149: E/(27146):  at com.pmss.Login$AttemptLogin.doInBackground(Login.java:1)
12-13 15:52:13.149: E/(27146):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-13 15:52:13.149: E/(27146):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-13 15:52:13.149: E/(27146):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-13 15:52:13.149: E/(27146):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-13 15:52:13.149: E/(27146):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-13 15:52:13.149: E/(27146):  at java.lang.Thread.run(Thread.java:1019)
12-13 15:52:13.149: D/Login Failure!(27146): res: Login Successful!

2 个答案:

答案 0 :(得分:0)

您在String[]中收到posts,并且您正试图将其投放到JSONObject,这会让您例外。

尝试替换

JSONObject c = loginposition.getJSONObject(i);

String jsonText = loginposition.getString(i);

答案 1 :(得分:0)

如果

  

“loginposition是JSONArray类型是和Position是一个字符串变量,负责保存字符串,如用户和员工从我的数据库”

你有这个json:

{"posts":["user"],"message":"Login Successful!","success":1}

你可以这样做:

//loop through all the entries in loginposition and extract strings for each index
for (int i = 0; i < loginposition.length(); i++) {
  position = loginposition.getJSONObject(i);
}

如果您的json包含多个用户,例如[“user”,“staff”],这个循环将遍历所有这些循环,所以你需要相应地处理它。

注意:请记住,按照Java惯例,您应该使用带小写首字母的变量名称(所以'position'不是'Position')。