【问题标题】:Json Parsing using Async Task and BaseAdapter使用 Async Task 和 BaseAdapter 解析 Json
【发布时间】:2013-03-22 05:23:40
【问题描述】:

我正在访问http://graph.facebook.com/xyz 并在ListView 中显示姓名、ID 和性别。我不知道如何调用 doInBackground 和 BaseAdapter 的结果。

public class FbMainActivity extends Activity {
Button b;
ListView lv;
DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
ArrayList<FBAccount> al;
MyAdapter adapter;
TextView tv1, tv2, tv3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fb_main);
    b = (Button) findViewById(R.id.bFAce);
    tv1 = (TextView) findViewById(R.id.textView1);
    tv2 = (TextView) findViewById(R.id.textView2);
    tv3 = (TextView) findViewById(R.id.textView3);

    lv = (ListView) findViewById(R.id.list);
    al = new ArrayList<FBAccount>();
    adapter = new MyAdapter();
    lv.setAdapter(adapter);

    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MyOperation operation = new MyOperation();
            operation.execute();
        }
    });
}

private class MyOperation extends AsyncTask<String, Void, String> {
    ProgressDialog dialog = new ProgressDialog(FbMainActivity.this);

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog.setMessage("Loading....");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        client = new DefaultHttpClient();
        get = new HttpGet("http://graph.facebook.com/somename");
        try {
            response = client.execute(get);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        entity = response.getEntity();
        InputStream is = null;
        try {
            is = entity.getContent();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = null;
        do {
            try {
                line = reader.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            buffer.append(line);
        } while (line != null);
        String str = buffer.toString();
        FBAccount account;
        JSONObject object;
        try {
            object = new JSONObject(str);
            String id = object.getString("id");
            String name = object.getString("name");
            String gender = object.getString("gender");

            account = new FBAccount();
            account.setId(id);
            account.setName(name);
            account.setGender(gender);

            al.add(account);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        adapter.notifyDataSetChanged();
        return str;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        dialog.dismiss();


    }
}

private class MyAdapter extends BaseAdapter {

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return al.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return al.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(
                R.layout.cust_layout, null);

        String id = al.get(position).getId();
        String name = al.get(position).getName();
        String gender = al.get(position).getGender();
        tv1.setText(id);
        tv2.setText(name);
        tv3.setText(gender);
        return layout;
    }

}

}

【问题讨论】:

    标签: android json android-asynctask baseadapter android-adapter


    【解决方案1】:

    你需要在getView()方法中初始化textviews...

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
        View rowView = inflater.inflate(R.layout.row_student_sms, parent, false);
        YourModelClass model = al.get(position);
    
        final TextView tv1 = (TextView) rowView.findViewById(R.id.textView1);
        tv1.setText(model.getId());
    
        TextView tv2 = (TextView) rowView.findViewById(R.id.textView2);
        tv2.setText(model.getName());
    
        TextView tv3 = (TextView) rowView.findViewById(R.id.textView3);
        tv2.setText(model.getGender());
    
        return rowView;
     }
    

    【讨论】:

    • 谢谢:) 但是为什么它不能在下面的代码上工作LinearLayout layout = (LinearLayout) getLayoutInflater().inflate( R.layout.cust_layout, null); tv1 = (TextView) findViewById(R.id.textView1); tv2 = (TextView) findViewById(R.id.textView2); tv3 = (TextView) findViewById(R.id.textView3);
    • 因为 getView() 方法负责为适配器创建视图。所以你的布局将在 getView() 方法中初始化。
    【解决方案2】:

    从api获取数据后使用onPostExecute方法更新ListView。通过在onPostExecute 中调用adapter.notifyDataSetChanged() 而不是doInBackground 来更改您的代码:

     @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
    
           // update listView here
    
          adapter.notifyDataSetChanged();
    
          dialog.dismiss();
    
        }
    

    【讨论】:

    • lv = (ListView) findViewById(R.id.list); al = new ArrayList&lt;FBAccount&gt;(); adapter = new MyAdapter(); lv.setAdapter(adapter); adapter.notifyDataSetChanged(); 不工作....
    • @DroidLearner:只需使用 adapter.notifyDataSetChanged();在 onPostExecute 里面检查它是否工作?
    • 这里是使用adapter.notifyDataSetChanged()后的logcat(tinypic.com/r/51voqs/6);
    【解决方案3】:

    您在活动中错误地初始化了TextView。它应该在您的适配器的 getView 方法中,并且应该使用您的 LinearLayout layout 实例访问它,如下所示:

    尝试如下:

       @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
          LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       View m_view = inflater.inflate(R.layout.cust_layout, parent, false);
           tv1 = (TextView)m_view.findViewById(R.id.textView1);
           tv2 = (TextView)m_view.findViewById(R.id.textView2);
           tv3 = (TextView)m_view.findViewById(R.id.textView3);
       return m_view;
      }
    

    【讨论】:

    • NullPointerException 在这条线上 tv1.setText(id); @ρяσѕρєя K
    猜你喜欢
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 2019-10-08
    • 2018-03-08
    • 2012-03-02
    相关资源
    最近更新 更多