1

我在 android 中使用异步任务从在线数据库中获取 json,以检查用户密码和用户名是否正确。

每次我在手机上测试时,“状态”的 json 字符串始终为“否”,即使我输入了正确的信息,也永远不会“是”。

但是当我在浏览器中使用我在手机中输入的相同信息对其进行测试时,我得到了正确的 json 结果。它总是返回“不”

异步任务:

public class ReadLogInJSON extends AsyncTask
<String, Void, String> {

    Context c;

    public ReadLogInJSON(Context context)
    {
         c = context;
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPostExecute(String result){

        //decode json here
        try{                
            JSONObject json = new JSONObject(result);

            String status = json.getString("status");
            Log.d("BeforeIf", status);
            if(status.equals("no")){
                //toast logIN failed
                Log.d("logIN-no", status);
                String message = "Log In Failed";
                Toast.makeText(c,  message, Toast.LENGTH_SHORT).show();
            }
            else{
                //get userName
                Log.d("logIN-yes", "correct");
                //get user ID

                //set preferences

                //launch normal activity
            }
        }
        catch(Exception e){
        }

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }        
        return stringBuilder.toString();
    }

}
4

1 回答 1

2

是否有缓存是异步任务?

不,AsyncTask不会缓存其结果。您可以通过查看此处的源代码自己了解这一点。

于 2013-06-22T03:23:32.160 回答