【问题标题】:Information from JSON does not show in my ListView, and what to pass to OnItemClickListener来自 JSON 的信息未显示在我的 ListView 中,以及传递给 OnItemClickListener 的内容
【发布时间】:2016-02-22 08:59:56
【问题描述】:

我对android很陌生,我已经在网上搜索了3天的答案,在这里和其他地方,但运气不佳。请原谅我的愚蠢问题。 好吧,我基本上想做的是一个简单的联系人列表,其中包含 3 个字段。私人姓名、姓氏和电话号码。我从 JSON 中获取信息。 这是我的 MainActivity。

public class MainActivity extends Activity implements AdapterView.OnItemClickListener {

   private static String stream = "http://cs.ash-college.ac.il/~habitbul/androidStudents.html";
    CustomListAdapter adapter=new CustomListAdapter();
    ListView list;
    TextView firstName,lastName,number;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter = new CustomListAdapter(new ArrayList<Student>(), this);
        list = (ListView) findViewById(R.id.listView);
        firstName=(TextView)findViewById(R.id.txtfirstname);
        lastName=(TextView)findViewById(R.id.txtlastname);
        number=(TextView)findViewById(R.id.txtnumber);
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
        new myAsyncTask().execute(stream);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


        Object call=list.getItemAtPosition(position);
        call.toString();
        String uri = "tel:" + call;
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse(uri));
        startActivity(intent);

    }

    public class myAsyncTask extends AsyncTask<String, Void, List<Student>> {
        private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.setMessage("Downloading contacts...");
            dialog.show();
        }

        @Override
        protected List<Student> doInBackground(String... params) {
            List<Student> result;
            result = new ArrayList<Student>();

            try {
                URL u = new URL(stream);

                HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();

                InputStream inputStream = connection.getInputStream();
                // Read the stream
                byte[] b = new byte[1024];
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                while (inputStream.read(b) != -1)
                    output.write(b);
                    String JSONResp = new String(output.toByteArray());

                JSONArray arr = new JSONArray(JSONResp);
                for (int i = 0; i < arr.length(); i++) {
                    result.add(new Student(arr.getJSONObject(i)));
                }
                return result;


            } catch (Throwable t) {
                t.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(List<Student> result) {
            super.onPostExecute(result);
            dialog.dismiss();
            adapter.setItemList(result);
            adapter.notifyDataSetChanged();


        }

        public Student convertStudent(JSONObject obj) throws JSONException {

            String firstname = obj.getString("first_name");
            String lastname = obj.getString("last_name");
            String number = obj.getString("phone_number");

            return new Student(firstname, lastname, number);
        }

    }

我的 CustomListAdapter 类:

public class CustomListAdapter extends BaseAdapter {



    private List<Student> studentList;
    private Context context;

    /*************  CustomAdapter Constructor *****************/
    public CustomListAdapter(ArrayList<Student> itemList, Context c)
    {

        this.studentList=itemList;
        this.context=c;

    }



    public CustomListAdapter() {

    }


    @Override
    public int getCount() {

        if (studentList != null)
            return studentList.size();
        return 0;
    }

    @Override
    public Student getItem(int i) {


        if (studentList != null)
            return studentList.get(i);

        return null;
    }

    @Override
    public long getItemId(int i) {


        if (studentList != null)
            return studentList.get(i).hashCode();

        return 0;
    }

    @Override
    public View getView(int i, View convertStudent, ViewGroup viewGroup) {

            View cell=convertStudent;
        if (cell == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            cell = inflater.inflate(R.layout.list_cell, null);
        }

            Student s = studentList.get(i);

        TextView firstName = (TextView) cell.findViewById(R.id.txtfirstname);
        firstName.setText(s.getFirstName());

        TextView lastName = (TextView) cell.findViewById(R.id.txtlastname);
        lastName.setText(s.getLastName());

        TextView number = (TextView) cell.findViewById(R.id.txtnumber);
        number.setText(s.getNumber());

        return cell;
    }

    public List<Student> getItemList() {


        return this.studentList;
    }



    public void setItemList(List<Student> itemList) {


        this.studentList = itemList;
    }



}

这是我的学生班:

/**Create Model to save each ListView row data.*/
public class Student {
    int id;
    String firstName;
    String lastName;
    String number;


    public Student(JSONObject object) {

        try {
            this.id=object.getInt("1");
            this.firstName = object.getString("first_name");
            this.lastName = object.getString("last_name");
            this.number=object.getString("phone_number");
        }

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

    }



    public Student(String firstname, String lastname, String number) {

        this.firstName=firstname;
        this.lastName=lastname;
        this.number=number;

    }

    public String getFirstName(){

        return firstName;

    }
    public void  setFirstName(String fn){
        this.firstName=fn;
    }
    public void  setLastName(String ln){
        this.lastName=ln;
    }
    public void setNumber(String num){
        this.number=num;
    }
    public Student getItemList( ){

        return getItemList();
    }
    public Student setItemList(Student s){
        return s;
    }
    public String getNumber() {


        return number;
    }

    public String getLastName(){

        return lastName;
    }

当我运行应用程序时,它是一个包含行的空列表,如下所示:

当我按下空列表中的行时,由于某种原因,我得到了所有随机数,如下所示:

如您所见,我是新手,在这里我看不到我的问题。感谢所有帮助。

【问题讨论】:

  • 你能从服务器获得 JSON 响应吗??
  • @madhusudhan 你是什么意思?我该如何检查?再说一次,你可能猜到了,我是新手。
  • 您以错误的方式解析您的 json 响应。如果您看到响应,则在数组的每个元素中都有一个带有键 person 的 json 对象。您需要访问它。
  • 我明白了。所以我检查了你的服务器 URL ..它给出了一些 JSON 响应。所以你需要解析它并在列表视图中显示它。我对吗?
  • 在您的 doInBackground 中打印 result.toString() 并检查您收到正确响应的结果

标签: android json android-asynctask onitemclicklistener


【解决方案1】:

将此添加到Student 类中

public void setId(int Id){
    this.id = Id;
}

然后在doInBackgrount 方法中像这样解析你的JSON

JSONArray arr = new JSONArray(JSONResp);
for (int i = 0; i < arr.length(); i++) {
    JSONObject temp = arr.getJSONObject(i); 
    JSONObject obj = temp.getJSONObject("person");
    Student student = new Student(obj);
    student.setId(temp.getInt("id"));
    result.add(student);
}

id 参数在外部对象中。为此添加一个 setter 并使用它。

更新

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Student call = (Student)adapter.getItem(position);
    String uri = null;
    if(call != null) // getItem might give you null
        uri = "tel:" + call.getNumber();
    else{
        Log.e("onItemClick", "Clicked object is null");
        return;
    }
    Intent intent = new Intent(Intent.ACTION_DIAL);
    intent.setData(Uri.parse(uri));
    startActivity(intent);
}

【讨论】:

  • 我正在返回结果,在“try”之后......并且在 catch 之后我返回 null。
  • @GrowingDev:您的 JSON 解析不正确。试试这个。
  • 哇。我现在看到名单了!但是当我按下列表中的某个人时,由于某种原因它什么也没做。
  • 是的,我忘了从我的 onItemClickListener 方法中删除注释符号!非常感谢!
  • 我做到了。顺便说一句...我有一些小问题。我需要“修剪”琴弦,但我不能。我怎样才能做到这一点?我使用 .trim() 方法。但那是我将它用作字符串的时候,现在它是“学生”。更新:它工作正常 - 忘记它。再次感谢!
【解决方案2】:
Parse it as below   

 try {
        // jsonString is a string variable that holds the JSON 
        JSONArray itemArray=new JSONArray(JSONResp);
        for (int i = 0; i < itemArray.length(); i++) {
            JSONObject c = itemArray.getJSONObject(i);

             id = c.getInt("id");
             JSONObject person = c.getJSONObject("person");
             String  first_name = c.getString("first_name");
             String  last_name = c.getString("last_name");
            String  phone_number =  c.getString("phone_number");
            new Student(first_name, last_name, phone_number);

        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

【讨论】:

    猜你喜欢
    • 2016-05-19
    • 2016-10-15
    • 2018-03-05
    • 2016-06-06
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多