如何让我的JSON进入android listview?

时间:2013-03-22 07:59:29

标签: android json parsing listview

我是一名新程序员,我正在创建一个应用程序,可以将数据从MYSQL获取到php,然后在android上显示。我一直试图找到一个解决方案,但到目前为止我看到的教程似乎都没有为我工作,我只是设法从json获得一个对象到一个textview。但我真正需要的是将数据显示在listview上的各行上。

这是我的JSON输出,

 [{"id":"1","name":"darrel","password":"pass1234"},{"id":"2","name":"garrett","password":"important"},{"id":"3","name":"neoys","password":"yseniopass"},{"id":"4","name":"john","password":"mikel123"},{"id":"5","name":"owen","password":"mike4l"}]

和我的java代码,只有一个用户显示在textview上。

  package com.darre.jsonreader;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;

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

import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class Users extends ListActivity {


    /** Called when the activity is first created. */

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        //listView.setOnItemClickListener(new OnItemClickListener() {
        //  public void onItemClick(AdapterView<?> parent, View view,
        //          int position, long id) {
                // When clicked, show a toast with the TextView text
        //      Toast.makeText(getApplicationContext(),
            //  ((TextView) view).getText(), Toast.LENGTH_SHORT).show();


        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

        }
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://172.30.54.153/databases/");
        TextView textView = (TextView)findViewById(R.id.textView1);

        ListView listview = (ListView)findViewById(R.id.listView1);
  try {

   HttpResponse response = httpclient.execute(httppost);
   String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
   JSONArray mArray = new JSONArray(jsonResult);
   for (int i = 0; i < mArray.length(); i++) {
       JSONObject object = mArray.getJSONObject(i);




      String name = object.getString("name");
     String password = object.getString("password");
      textView.setText(name + " - " + password);

  }
   } 
  catch (JSONException e) {
   e.printStackTrace();
  } 
  catch (ClientProtocolException e) {
   e.printStackTrace();
  } 
  catch (IOException e) {
   e.printStackTrace();
  }



       }

提前致谢!!!

3 个答案:

答案 0 :(得分:0)

如果你想使用ListView ...那么你应该将JSON文件解析为某种数据结构,如List或ArrayList,并且n使用适配器填充ListView数据。

以下是ListView适配器的示例:

    private class MySecondAdapter extends ArrayAdapter<MiniTask>
{   
    private ArrayList<MiniTask> list;

    public MySecondAdapter(Context context, int textViewResourceId, ArrayList<MiniTask> miniTaskList) 
    {
        super(context, textViewResourceId, miniTaskList);
         this.list = new ArrayList<MiniTask>();
         this.list.addAll(miniTaskList);
    }

    public View getView(final int position, View convertView, ViewGroup parent)
    {
        miniTask = miniTaskList.get(position);
        ViewHolder holder = new ViewHolder();
        {
            LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflator.inflate(R.layout.check_list_item_new, null);

            holder.title = (TextView) convertView.findViewById(R.id.tvItemTitle);
            holder.commentsPicturesButton = (ImageView) convertView.findViewById(R.id.iAddCommetOrPicture);
            holder.commentsPicturesButton.setTag(position);
            holder.commentsPicturesButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) 
                {
                     Intent intent = new Intent(getApplicationContext(), PicturesAndCommentsActivity.class);
                     intent.putExtra(TasksListActivity.KEY_ID, task.getId());
                     intent.putExtra("mini_task_text", miniTask.getTitle());
                     startActivity(intent);
                }
            });
            holder.selected = (CheckBox) convertView.findViewById(R.id.cbCheckListItem);
            holder.selected.setTag(position);
            holder.selected.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v)
                {    
                    {                               
                        Log.d(TAG, "pressed the checkbox: " + v.getId() + " in position: " + position + " tag: " +v.getTag() +" and item from array: " + miniTaskList.get(position) );
                        CheckBox checkbox = (CheckBox) v;
                        miniTaskList.get(position).setSelected(checkbox.isChecked());   
                        numOfCheckedMiniTasks = 0;
                        for(int i=0;i<miniTaskList.size();i++)
                        {
                             miniTask = miniTaskList.get(i);
                             if(miniTask.isSelected())
                             {
                                numOfCheckedMiniTasks ++;
                             }
                        }
                        int percent = (int)(numOfCheckedMiniTasks * 100.0f) / miniTaskList.size();
                        Log.d(TAG, "the percentage is: " +percent);
                        tasksRepository.get(tasksRepository.indexOf(task)).setMiniTasksPercentageComplete(percent);
                    }
                }
            });
        }

        holder.title.setText(miniTask.getTitle());
        holder.selected.setChecked(miniTask.isSelected());
        return convertView;
    }
}

查看本教程以获取更多信息:

http://cyrilmottier.com/2012/02/16/listview-tips-tricks-5-enlarged-touchable-areas/

答案 1 :(得分:0)

您必须创建ListView适配器:

将其放入您的代码:

private String[] listArr;
public ArrayList<String> ary_name = new ArrayList<String>();

try {

   HttpResponse response = httpclient.execute(httppost);
   String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
   JSONArray mArray = new JSONArray(jsonResult);
   for (int i = 0; i < mArray.length(); i++) {
       JSONObject object = mArray.getJSONObject(i);




      String name = object.getString("name");
     String password = object.getString("password");
      textView.setText(name + " - " + password);

    ary_name.add(name);

  }


    listArr = new String[ary_name.size()];
    listArr = ary_name.toArray(listArr);



MyArrayAdapter adapter = new MyArrayAdapter(this, listArr);
        listView.setAdapter(adapter);



public class MyArrayAdapter extends ArrayAdapter<String> {

        Activity context;
        String[] listArr;

        private TextView btnchkout;

        // private final integer[] image;

        public MyArrayAdapter(Activity context, String[] objects) {
            super(context, R.layout.custmlayout, objects);
            // TODO Auto-generated constructor stub
            this.context = context;
            listArr = objects;

        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            // TODO Auto-generated method stub


            LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.custmlayout, null, true);

            TextView textView = (TextView) view.findViewById(R.id.txtTicketNo);
            textView.setText(listArr[position]);

            return view;
        }
    }

答案 2 :(得分:0)

您可以阅读本教程,它解释了实现它的方法,第一个是“直接”List适配器,第二个是自定义List的方法。

http://www.mkyong.com/android/android-listview-example/

此外,您不应该使用JSON数据,首先,您必须为每个Item创建一个Object,然后使用某种List(例如ArrayList)对其进行分组。