0

我是安卓新手。我正在实施一个项目,我想从后端获取数据并显示在我的 android 屏幕上。

我要调用的 Json 是:-

[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds@fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin@qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]

我的 JsonParser.java 如下:-

package com.example.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;


import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONArray jarray = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONArray getJSONFromUrl(String url) {

  StringBuilder builder = new StringBuilder();
   HttpClient client = new DefaultHttpClient();
   HttpGet httpGet = new HttpGet(url);
   try {
     HttpResponse response = client.execute(httpGet);
     StatusLine statusLine = response.getStatusLine();
     int statusCode = statusLine.getStatusCode();
     if (statusCode == 200) {
       HttpEntity entity = response.getEntity();
       InputStream content = entity.getContent();
       BufferedReader reader = new BufferedReader(new InputStreamReader(content));
       String line;
       while ((line = reader.readLine()) != null) {
         builder.append(line);
       }
     } else {
       Log.e("==>", "Failed to download file");
     }
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }

// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jarray;

}
}
   /* public void writeJSON() {
          JSONObject object = new JSONObject();
          try {
            object.put("name", "");
            object.put("score", new Integer(200));
            object.put("current", new Double(152.32));
            object.put("nickname", "Programmer");
          } catch (JSONException e) {
            e.printStackTrace();
          }
          System.out.println(object);
        } 
*/

我的activity.java如下: -

package com.example.library;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;


public class SecondActivity extends Activity 
{
    private Context context;
    private static String url = "http://192.168.0.100:3000/users.json";

    private static final String TAG_ID = "id";
    private static final String TAG_FIRST_NAME = "first_name";
    private static final String TAG_MIDDLE_NAME = "middle_name";
    private static final String TAG_LAST_NAME = "last_name";

    // private static final String TAG_POINTS = "experiencePoints";

    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

    ListView lv ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new ProgressTask(SecondActivity.this).execute();
    }

    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog dialog;

    public ProgressTask(SecondActivity secondActivity) {

    Log.i("1", "Called");
    context = secondActivity;
    dialog = new ProgressDialog(context);
    }

    /** progress dialog to show user that the backup is processing. */

    /** application context. */
    private Context context;

    protected void onPreExecute() {
    this.dialog.setMessage("Progress start");
    this.dialog.show();
    }

    @Override
    protected void onPostExecute(final Boolean success) {
    if (dialog.isShowing()) {
    dialog.dismiss();
    }
    ListAdapter adapter = new SimpleAdapter(context, jsonlist,
    R.layout.list_item, new String[] { TAG_ID, TAG_FIRST_NAME,
    TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
    R.id.id, R.id.first_name, R.id.middle_name,
    R.id.last_name });

    setListAdapter(adapter);

    // selecting single ListView item
    lv = getListView();






    }

    private void setListAdapter(ListAdapter adapter) {
        // TODO Auto-generated method stub

    }

    protected Boolean doInBackground(final String... args) {

    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONArray json = jParser.getJSONFromUrl(url);

    for (int i = 0; i < json.length(); i++) {

    try {
    JSONObject c = json.getJSONObject(i);
    String id = c.getString(TAG_ID);

    String first_name = c.getString(TAG_FIRST_NAME);
    String middle_name = c.getString(TAG_MIDDLE_NAME);
    String last_name = c.getString(TAG_LAST_NAME);

    HashMap<String, String> map = new HashMap<String, String>();

    // adding each child node to HashMap key => value
    map.put(TAG_ID, id);
    map.put(TAG_FIRST_NAME, first_name);
    map.put(TAG_MIDDLE_NAME, middle_name);
    map.put(TAG_LAST_NAME, last_name);
    jsonlist.add(map);
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    return null;

    }
    }

    public ListView getListView() {
        // TODO Auto-generated method stub
        return null;
    }
}

用户屏幕 不提供/显示任何输出

我无法在模拟器上为用户显示任何内容,而我可以从服务器获取数据

实际上,在项目中,我想显示库中存在的所有用户。我正在访问 Ubuntu 上的服务器。

控制台(终端)上显示以下消息:-

Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
  User Load (0.4ms)  SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
  Admin Load (0.3ms)  SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN  Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

但是我无法在 android 屏幕/模拟器上显示数据。

请帮我解决一下这个。

4

1 回答 1

2

我错过了你的setAdapterList()方法。

您的 json 解析器有任何错误吗?你能把你的活动从SecondActivity继承吗?

//modify getListView
public ListView getListView() {
    // TODO Auto-generated method stub
    listView = (ListView)findViewById(r.your.listview);
    return listView;
}

//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
    // TODO Auto-generated method stub
    lv.setAdapter(adapter);
}
于 2013-05-06T07:59:27.497 回答