0

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??

neeta
  • 43
  • 12
  • Did you check what the index are you getting while selecting from spinner? does it match with your json array index? – Piyush Feb 16 '17 at 05:57
  • i am trying to do this way also but i am confused how to do that to get correct data at that position – neeta Feb 16 '17 at 06:01
  • One solution is you can prepare list of string from your json array with standard as value, and later on in spinner you can get index of selected standard by using list.indexOf(selected standard), and by using tha index you can get json object from your json array – Piyush Feb 16 '17 at 06:04
  • its not working ..do you have any sample code that will help me to solve this problem – neeta Feb 16 '17 at 06:45
  • share what have you done? – Piyush Feb 16 '17 at 06:55

2 Answers2

1

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");
Piyush
  • 2,589
  • 6
  • 38
  • 77
  • You can try this @niya – Piyush Feb 23 '17 at 09:47
  • app is crashed after i tried the same as you said. what shoul i do now?? i really dont understand.. i have to take standard from json its my task only – neeta Feb 23 '17 at 10:17
  • FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.chronos.standardspinner/com.chronos.standardspinner.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0... showing this – neeta Feb 23 '17 at 10:26
  • It seems like standard array size is zero. You can update what have you done in your answer post. So i can check. – Piyush Feb 23 '17 at 10:29
  • i have posted above please hava a look @Piyush – neeta Feb 23 '17 at 10:40
  • yes it is not working properly.. wrong information gets displayed and not displaying all students information when select the standard @Piyush – neeta Feb 23 '17 at 11:32
  • Share your complete project if you are allowed – Piyush Feb 23 '17 at 11:45
  • @niya see i have attached image of my debug – Piyush Feb 23 '17 at 11:49
  • it is displaying all stdents info ... ok i am sharing you but how? @Piyush – neeta Feb 23 '17 at 11:51
  • You can upload your project in drive and share link here – Piyush Feb 23 '17 at 11:52
  • here is the link ( https://drive.google.com/open?id=0BzHt_CGpglL5QTdMT1RoQUFkajQ ) please kindly look ata this code @Piyush – neeta Feb 23 '17 at 12:01
  • I didn't understand where to put these lines of code ( Bundle b = getIntent().getBundleExtra("bundle"); ArrayList studentVOList = (ArrayList) b.getSerializable("list"); ) now i understood where i doing mistake, but after adding this code i didnt get information, second activity is blank. @ Piyush – neeta Feb 24 '17 at 05:58
  • ..i am posting my stidentInfo activity code below part by partTextView textViewName = (TextView)findViewById(R.id.textName); TextView textViewSurname = (TextView)findViewById(R.id.textSurname); TextView textViewAge = (TextView)findViewById(R.id.textAge); TextView textViewDiv = (TextView)findViewById(R.id.textDiv); Bundle b = getIntent().getBundleExtra("bundle"); ArrayList studentVOList = (ArrayList) b.getSerializable("list"); Intent intent = getIntent(); – neeta Feb 24 '17 at 07:14
  • String value = intent.getStringExtra("name"); String value1 = intent.getStringExtra("surname"); String value2 = intent.getStringExtra("age"); String value3 = intent.getStringExtra("div"); textViewName.setText(value); textViewSurname.setText(value1); textViewAge.setText(value2); textViewDiv.setText(value3); plaese kindly have a look at it. i checked your answer but still its is not working @Piyush – neeta Feb 24 '17 at 07:16
  • You should use listview to display all students data by using studentVOList @niya – Piyush Feb 24 '17 at 09:34
  • if i want to display all students information on the same activity where my spinner is present rather than dispalying on other activity, what i have to do?? @Piyush – neeta Feb 24 '17 at 09:49
  • You need to use ListView or RecyclerView by using studentVOList @niya – Piyush Feb 24 '17 at 10:24
  • i have used listview but i really dont have any idea whats happning...please check my output i have posted @piyush – neeta Feb 24 '17 at 10:34
  • You should use custom array adapter: http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter @niya – Piyush Feb 24 '17 at 10:42
  • will please help me at this position m not able to get what is happening at this situation @Piyush please have a look at this code – neeta Feb 27 '17 at 07:09
0

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);
Muhib Pirani
  • 765
  • 1
  • 6
  • 15
  • am not getting your point . will you please explain it again with some example. if its possible – neeta Feb 16 '17 at 07:19
  • see, when you select '8' from your spinner, the position of 8 is '1' in spinner items. And now when you get jsonArray.optJSONobject(1) you will get "name" "ccc" and "standard" "7" which you are passing in intent. – Muhib Pirani Feb 16 '17 at 07:21
  • yes and it should change according to my spinner selection value – neeta Feb 16 '17 at 07:24
  • i wrote this line of code but i am not getting where i go wrong ( String n = spinner.getItemAtPosition(i).toString(); – neeta Feb 16 '17 at 07:26
  • you will have to create list of students of particular standard, which is selected from spinner. so when item is selected, check from jsonArray if the standard matches with seleceted item, and add it in a list as you can have multiple students for single standard – Muhib Pirani Feb 16 '17 at 07:33
  • for (int j=0;j – Muhib Pirani Feb 16 '17 at 07:34
  • and if you want all data for single student to be binded , try creating pojo class here is example http://stackoverflow.com/questions/3527264/how-to-create-a-pojo – Muhib Pirani Feb 16 '17 at 07:38