1

我是一名新程序员,我正在制作一个应用程序,它可以将数据从 MYSQL 获取到 php,然后在 android 上显示。我一直在努力寻找解决方案,但到目前为止我所看到的教程似乎都不适合我,我只设法将 json 中的一个对象放入单个 textview 中。但我真正需要的是让数据显示在列表视图的各个行上。

这是我的 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();
  }



       }

提前致谢!!!

4

3 回答 3

0

如果你想使用 a ListView... 那么你应该将你JSON的文件解析成某种数据结构,比如 List 或 an 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/

于 2013-03-22T08:02:35.347 回答
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;
        }
    }
于 2013-03-22T08:06:10.613 回答
0

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

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

此外,您不应该使用 JSON 数据,首先,您必须为每个项目创建一个对象,然后将其与某种列表(例如 ArrayList)分组。

于 2013-03-22T08:11:19.647 回答