user5533608
user5533608

Reputation:

Information from JSON does not show in my ListView, and what to pass to OnItemClickListener

I'm very new with android, and I have been searching for 3 days now for an answer online, in here and other places, but with not much luck. please forgive me for my noobish question. well, what I'm basically trying to do is a simple contact list with 3 fields in it. a private name, last name and phone number. I get the information from a JSON. This is my 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);
        }

    }

my CustomListAdapter class:

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



}

And this is my student class:

/**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;
    }

when I run the app, the is an empty list with rows in it, like so:

Empty list

and when I press on of the rows in the empty list I get all random numbers for some reason, like so:

Random numbers

as you can see, I am new to this, and I can't really see my problem here. all help is appreciated.

Upvotes: 0

Views: 74

Answers (2)

Rohit5k2
Rohit5k2

Reputation: 18112

Add this in Student class

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

Then in doInBackgrount method parse your JSON like this

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 parameter is in the outer object. Add a setter for that and use that.

Update

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

Upvotes: 1

sanky jain
sanky jain

Reputation: 873

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

Upvotes: 0

Related Questions