来自JSON的信息不会显示在我的ListView中,以及传递给OnItemClickListener的内容

时间:2016-02-22 08:59:56

标签: android json android-asynctask onitemclicklistener

我对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;
    }

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

Empty list

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

Random numbers

正如你所看到的,我是新手,我不能在这里看到我的问题。所有的帮助表示赞赏。

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

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();
    }