neeta
neeta

Reputation: 43

displaying corresponding json data in textview after selecting item in spinner

my spinner contains the unique standard value from json(like: my spinner contains only 7,8,6 (which i want,)instead of displaying all standard repitative data), if spinner item is selected, then it fetches the corresponding all information about that students who studying in that selectd standard. here is my code,

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

ArrayList<String> AllStandards = new ArrayList<>();
ArrayAdapter<String> adapter;
JSONArray jsonArray;
Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final List<String> items = getCountries("data.json");

    spinner = (Spinner) findViewById(R.id.spinnerStandard);
    adapter = new ArrayAdapter<String>(this, R.layout.second_layout, R.id.txtStandard, items);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            try {
                Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
                intent.putExtra("name", jsonArray.optJSONObject(i).getString("name"));
                intent.putExtra("surname", jsonArray.optJSONObject(i).getString("surname"));
                intent.putExtra("age", jsonArray.optJSONObject(i).getString("age"));
                intent.putExtra("div", jsonArray.optJSONObject(i).getString("div"));

                startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
    spinner.setAdapter(adapter);

}//onCreate Method

private List<String> getCountries(String fileName) {
    jsonArray = null;


    //ArrayList<String> cList = new ArrayList<String>();
    try {
        InputStream is = getResources().getAssets().open(fileName);
        int size = is.available();
        byte[] data = new byte[size];
        is.read(data);
        is.close();
        String json = new String(data, "UTF-8");

        AllStandards.clear();
        try {
            jsonArray = new JSONArray(json);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String stand = jsonObject.getString("standard");
                if (!AllStandards.contains(stand)) {
                    AllStandards.add(stand);
                }
            }
        }
        catch (JSONException je) {
            je.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }catch (IOException e) {
        e.printStackTrace();
    }
    return AllStandards;
}
}

here is json data,

[
{
"name":"aaa",
"surname":"bbb",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"ccc",
"surname":"ddd",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"eee",
"surname":"fff",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"ggg",
"surname":"hhh",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"sss",
"surname":"ddd",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"www",
"surname":"ggg",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"ggg",
"surname":"ccc",
"age":"18",
"div":"B",
"standard":"6"
}

but the problem is that when i am selecting standard 7 from my spinner it displaying only one student information. however i want all students information who all are studying in 7 standard. this should be happen for all choiecs in spinner (like i mean if i select standard 8 then it should display all students info who all are studying in 8 standard, same goes for standard 6)

for exapmle if i select standard 7 from spinner, it should display all information of student aaa, student ccc, student ggg, student www as they all are studying in standard 7.

i tried googling to find out the solution on this question but i didn't found any answers suitable to my question. i have checked stackoverflow's two posts but they dont have answers yet.

what is the correct way to do this??

Upvotes: 0

Views: 1084

Answers (2)

Piyush
Piyush

Reputation: 2609

So you want to get all students details from selected standards. Here is the code that will solve your problem.

Create value boject class with getter's and setter's

public class StudentVO implements Serializable{

    private String name;
    private String surname;
    private String age;
    private String div;
    private String standard;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getDiv() {
        return div;
    }

    public void setDiv(String div) {
        this.div = div;
    }

    public String getStandard() {
        return standard;
    }

    public void setStandard(String standard) {
        this.standard = standard;
    }
}

Now in your main class where you are selecting standard from spinner replace your code with:

//Add this
public class MainActivity extends AppCompatActivity {

ArrayList<String> AllStandards = new ArrayList<>();
private ArrayList<StudentVO> studentVOList = new ArrayList<>();
ArrayAdapter<String> adapter;
JSONArray jsonArray;
Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final List<String> items = getCountries("data.json");

    spinner = (Spinner) findViewById(R.id.spinnerStandard);
    adapter = new ArrayAdapter<String>(this, R.layout.second_layout, R.id.txtStandard, items);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            try {

                String standard = AllStandards.get(i);

                if (studentVOList.size() > 0)
                    studentVOList.clear();
                for (int j = 0; j < jsonArray.length(); j++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(j);
                    String stand = jsonObject.getString("standard");
                    if (stand.equalsIgnoreCase(standard)) {
                        StudentVO studentVO = new StudentVO();
                        studentVO.setAge(jsonObject.getString("age"));
                        studentVO.setName(jsonObject.getString("name"));
                        studentVO.setDiv(jsonObject.getString("div"));
                        studentVO.setStandard(stand);
                        studentVOList.add(studentVO);
                    }
                }

                Log.d("TAG", "List With All Students in selected standard: "+studentVOList.size());

                Intent intent = new Intent(getApplicationContext(), StudentsInfo.class);
                Bundle b = new Bundle();
                b.putSerializable("list",studentVOList);

                intent.putExtra("bundle",b);

                startActivity(intent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
    spinner.setAdapter(adapter);

}//onCreate Method

private List<String> getCountries(String fileName) {
    jsonArray = null;


    //ArrayList<String> cList = new ArrayList<String>();
    try {
        InputStream is = getResources().getAssets().open(fileName);
        int size = is.available();
        byte[] data = new byte[size];
        is.read(data);
        is.close();
        String json = new String(data, "UTF-8");

        AllStandards.clear();
        try {
            jsonArray = new JSONArray(json);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String stand = jsonObject.getString("standard");
                if (!AllStandards.contains(stand)) {
                    AllStandards.add(stand);
                }
            }
        }
        catch (JSONException je) {
            je.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }catch (IOException e) {
        e.printStackTrace();
    }
    return AllStandards;
}
}

After this you can get this list in StudentsInfo class like:

Bundle b = getIntent().getBundleExtra("bundle");
ArrayList<StudentVO> studentVOList = (ArrayList<StudentVO>) b.getSerializable("list");

Log.d("TAG", "List Size; "+studentVOList.size());

And you don't need to get list of standards from json array. You can prepare static list of students with standards 1,2,3.... so on and pass it to your array adapter.

See my debug result: enter image description here

I just check your code Remove

intent.putExtra("name", jsonArray.optJSONObject(i).getString("name"));
                    intent.putExtra("surname", jsonArray.optJSONObject(i).getString("surname"));
                    intent.putExtra("age", jsonArray.optJSONObject(i).getString("age"));
                    intent.putExtra("div", jsonArray.optJSONObject(i).getString("div"));

code from your MainActivity and in onCreate() method of StudentInfo activity class You can get list of students like:

Bundle b = getIntent().getBundleExtra("bundle");
    ArrayList<StudentVO> studentVOList = (ArrayList<StudentVO>) b.getSerializable("list");

Upvotes: 1

Muhib Pirani
Muhib Pirani

Reputation: 775

its because in your spinner itemSelected listener you are getting jsonArray.optJSONObject(i) here i is position of spinner item and not the standard. You will have get the value of this standard like this from spinner

spinner.getItemAtPosition(i);

and match it with the standard of all elements in JSONArray and add it in a list. then pass this list in your intent.

intent.putStringArrayListExtra("test", (ArrayList<String>) test);

Upvotes: 0

Related Questions