Multiple Spinners making various JSON calls - android

The aim of the application is to have spinners left (home team) and on the right (Away team). I can successfully populate the home team spinners but when i try to populate the away team spinners i get the error:
06-25 18:02:36.052: W/System.err(17916): org.json.JSONException: Value at 0 is null.
06-25 18:02:36.057: W/System.err(17916): at org.json.JSONArray.get(JSONArray.java:259)
06-25 18:02:36.057: W/System.err(17916): at org.json.JSONArray.getJSONObject(JSONArray.java:480)
06-25 18:02:36.057: W/System.err(17916): at app.league.npd.CaptainsInfo.useaJson(CaptainsInfo.java:309)
I can see that the error is coming from the "ateam" array, but i dont know what the problem is. I am new to android programming so any help would be appreciated.
Here is the code:
public class CaptainsInfo extends Activity {
JSONArray jsonArray = null;
JSONArray str_login = null;
public String items[];
public String aitems[];
private Spinner
spinner1, spinner2, spinner3, spinner4,
spinner5, spinner6, spinner7, spinner8,
spinner9, spinner10, spinner11, spinner12,
spinner13, spinner14;
private Button btnSubmit;
public String kode;
public String Home_team;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
addListenerOnSpinner2ItemSelection();
}
public void addItemsOnSpinner(String items[]) {
spinner3 = (Spinner) findViewById(R.id.player11);
spinner5 = (Spinner) findViewById(R.id.player12);
spinner7 = (Spinner) findViewById(R.id.player21);
spinner9 = (Spinner) findViewById(R.id.player22);
spinner11 = (Spinner) findViewById(R.id.player31);
spinner13 = (Spinner) findViewById(R.id.player32);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner3.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner5.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner7.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner9.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner11.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner13.setAdapter(adapter);
}
public void addItemsOnSpinner2(String aitems[]) {
spinner4 = (Spinner) findViewById(R.id.aplayer11);
spinner6 = (Spinner) findViewById(R.id.aplayer12);
spinner8 = (Spinner) findViewById(R.id.aplayer21);
spinner10 = (Spinner) findViewById(R.id.aplayer22);
spinner12 = (Spinner) findViewById(R.id.aplayer31);
spinner14 = (Spinner) findViewById(R.id.aplayer32);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner4.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner6.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner8.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner10.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner12.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner14.setAdapter(adapter);
}
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.h_type);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
//String test1 = parent.getItemAtPosition(position).toString();
String test = (String) spinner1.getSelectedItem();
//String test2 = (String) spinner2.getSelectedItem();
items=useJson(test);
//aitems=useaJson(test2);
//addItemsOnSpinner2(aitems);
addItemsOnSpinner(items);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });}
public void addListenerOnSpinner2ItemSelection(){
spinner2 = (Spinner) findViewById(R.id.a_type);
spinner2.setOnItemSelectedListener(new CustomOnItemSelectedListener());
spinner2.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
//String test2 = parent.getItemAtPosition(position).toString();
//String test = (String) spinner1.getSelectedItem();
String test2 = (String) spinner2.getSelectedItem();
// items=useJson(test);
aitems=useaJson(test2);
addItemsOnSpinner2(aitems);
//addItemsOnSpinner(items);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.h_type);
spinner2 = (Spinner) findViewById(R.id.a_type);
spinner3 = (Spinner) findViewById(R.id.player11);
spinner4 = (Spinner) findViewById(R.id.aplayer11);
spinner5 = (Spinner) findViewById(R.id.player12);
spinner6 = (Spinner) findViewById(R.id.aplayer12);
spinner7 = (Spinner) findViewById(R.id.player21);
spinner8 = (Spinner) findViewById(R.id.aplayer21);
spinner9 = (Spinner) findViewById(R.id.player22);
spinner10 = (Spinner) findViewById(R.id.aplayer22);
spinner11 = (Spinner) findViewById(R.id.player31);
spinner12 = (Spinner) findViewById(R.id.aplayer31);
spinner13 = (Spinner) findViewById(R.id.player32);
spinner14 = (Spinner) findViewById(R.id.aplayer32);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CaptainsInfo.this,
"OnClickListener : " +
"\nSpinner 1 : " + String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : " + String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
String links_url = "http://192.168.9.59/NPD/detail-info.php?Match_id="+kode;
// Call the FunctionParser to parse the information being returned
// From the FHL databaseList<NameValuePair> params = new ArrayList<NameValuePair>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.FunctionParser(links_url);
// The array is called and the information is returned from
// the database corresponding to each string below
try {
str_login = json.getJSONArray("temp");
String jdwl = "";
TextView isi = (TextView) findViewById(R.id.fixdet);
for(int i = 0; i < str_login.length(); i++){
JSONObject ar = str_login.getJSONObject(i);
Home_team = ar.getString("Home_team");
jdwl += "" + ar.getString("Home_team")+"\n vs \n"+
"" + ar.getString("Away_team")+"\n"+
"" + ar.getString("Fixture_date")+"\n";
}
isi.setText(jdwl);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String[] useJson(String test) {
JSONParser jParser = new JSONParser();
String link_url = "http://10.2.0.0/NPD/P_name.php?"+test;
JSONObject json = jParser.FunctionParser(link_url);
try {
jsonArray = json.getJSONArray("team");
items = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
items[i]=jsonObject.getString("name");
}
return(items);}
catch (JSONException e) {
e.printStackTrace();
}
return items;
}
public String[] useaJson(String test2) {
JSONParser jjParser = new JSONParser();
String links_url = "http://10.2.0.0/NPD/P_name1.php?"+test2;
JSONObject json = jjParser.FunctionParser(links_url);
try {
jsonArray = json.getJSONArray("ateam");
aitems = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
aitems[i]=jsonObject.getString("name");
}
return(aitems);}
catch (JSONException e) {
e.printStackTrace();
}
return aitems;
}
}

According to json.org (http://www.json.org/javadoc/org/json/JSONArray.html#getJSONObject(int)):
getJSONObject throws JSONException if there is no value for the index
or if the value is not a JSONObject.
How your ateam array is being populated? Seems that you are adding null values inside it. Make sure that your ateam array is populated only with initialized JSONObject, maybe the JSONObject is null when you add it to ateam array so you must check if is null before adding it to ateam.

Related

Extract substring from a string for spinner entry

I need to extract part of the string and display it in the spinner
I need that when the spinner display data example
For array entries like the following
"Equipo-001"
"Equipo-002"
Should show only:
"001"
"002"
Here's my code
private void rellenarSpinnerConFoliosDeMaquinasDelPunto(List<String> folios) {
maquinas = dbOn.getMaquinasDePunto(idPunto);
for (int i = 0; i < maquinas.size(); i++) {
foliosDeMaquinas.add(maquinas.get(i).getcFolioMaquina());
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, folios);
adaptadorFoliosMaquina.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn_folioMaquina.setAdapter(adaptadorFoliosMaquina);
spn_folioMaquina.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
ArrayList<String> numberFolios = new ArrayList<>();
for(int j =0; j < folios.size(); j++){
numberFolios.add(folios.get(j).substring(8, 10));
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, numberFolios);
Check link for better reference on how to use substring.
You can use SPLIT function
ArrayList<String> data = new ArrayList();
foreach(String get:folios){
data.add(folios.split("-")[1]);
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
If your result will be dynamic(The string length would vary in future) the below solution may work,
private void rellenarSpinnerConFoliosDeMaquinasDelPunto(List<String> folios) {
try{
maquinas = dbOn.getMaquinasDePunto(idPunto);
for (int i = 0; i < maquinas.size(); i++) {
foliosDeMaquinas.add(maquinas.get(i).getcFolioMaquina().toString().split("-")[1]);
}
} catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, folios);
adaptadorFoliosMaquina.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn_folioMaquina.setAdapter(adaptadorFoliosMaquina);
spn_folioMaquina.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

Get details of the selected item of spinner

I have a data in JSON format which consists of city id and names. when an item is selected i want its cityid. I tried doing this. but itdoes not show correct cityid.
JSONArray gg = new JSONArray(objCity);
ArrayList<String> cityal = new ArrayList<String>();
ArrayList<String> cityalid = new ArrayList<String>();
for (int j=0; j<gg.length(); j++){
pojo = new Pojo();
JSONObject jobj = gg.getJSONObject(j);
String cityid = jobj.optString("id");
String cityName = jobj.optString("name");
cityal.add(cityName);
cityalid.add(cityid);
}
List<String> listTem = cityal;
List<String> listTemId = cityalid;
Set<String> tem = new HashSet<String>(listTem);
Set<String> temid = new HashSet<String>(listTemId);
SharedPreferences.Editor editr = getSharedPreferences("City", MODE_PRIVATE).edit();
tem.addAll(listTem);
temid.addAll(listTemId);
editr.putStringSet("cityname", tem);
editr.putStringSet("cityid", temid);
editr.commit();
and in postExecute
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("Post exec calleld", "dfds");
nDialog.dismiss();
SharedPreferences prefs = getSharedPreferences("City", MODE_PRIVATE);
Set<String> set = prefs.getStringSet("cityname", null);
Set<String> set11 = prefs.getStringSet("cityid", null);
List<String> titlesList = new ArrayList<String>(0);
titlesList.addAll(set);
List<String> descList = new ArrayList<String>(0);
descList.addAll(set11);
ssservice.clear();
for (String p : set) {
pojo = new Pojo();
pojo.setCityName(p);
al_city.add(pojo);
ssservice.add(p);
}
for (String p11 : set11) {
pojo = new Pojo();
pojo.setCityId(p11);
al_cityId.add(pojo);
ssservice11.add(p11);
}
Log.e("Cityname",""+al_city);
Log.e("City iddd", ""+al_cityId);
spinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
ssservice));
// Spinner on item click listener
spinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
ed_spinner = spinner.getSelectedItem().toString();
String idd = pojo.getCityId();
Log.e("City id from spinner",""+idd);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.textview, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setView(promptsView);
// set dialog message
alertDialogBuilder.setTitle("Select City");
// alertDialogBuilder.setIcon(R.drawable.ic_launcher);
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();
final Spinner mSpinner= (Spinner) promptsView
.findViewById(R.id.c_spinner);
//mSpinner.setAdapter(ssservice);
mSpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
ssservice));
final Button mButton = (Button) promptsView
.findViewById(R.id.c_btn);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos= mSpinner.getSelectedItemPosition();
Log.e("POS",""+pos);
pojo = new Pojo();
String cid = al_cityId.get(pos).getCityId();
Log.e("ciddddd",""+cid);
SharedPreferences.Editor editor = getSharedPreferences(
"CityIdSpinner", MODE_PRIVATE).edit();
editor.putString("id", cid);
}
});
// reference UI elements from my_dialog_layout in similar fashion
// mSpinner.setOnItemSelectedListener(new OnSpinnerItemClicked());
// show it
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
return;
}
This is my jsom
[{"city":[{"id":"3","name":"Pune"},{"id":"4","name":"Bhopal"},{"id":"5","name":"Indore"},{"id":"6","name":"Amravati"},{"id":"8","name":"Wardha"},{"id":"12","name":"Nagpur"},{"id":"16","name":"akola"}]
Please suggest me something.
Store your values in HashMap. cityname as Key and ID as value.
HashMap<String,String> spinnerValuesMap = new HashMap<String,String>();
for (int j=0; j<jsonArray.length(); j++){
JSONObject jobj = gg.getJSONObject(j);
String cityid = jobj.optString("id");
String cityName = jobj.optString("name")
spinnerValuesMap.put(cityName,cityid);
}
Access Id Like This:
String selectedItem= mySpinner.getSelectedItem().toString();
String cityId = spinnerValuesMap.get(selectedItem); // Your CIty id is here

Dynamically view and hide Spinners in an Activity

I want to generate Spinners dynamically. Maximum numbers of Spinners I want to generate is 7. But I want to generate Spinners according to the data sets I'm getting from json response.
For the moment I have below shown code, which is used to identify how many spinners to generate. According to the below code MealDealCatCode contains L1, L2. So I want to get the value as 2 and display only 2 Spinners out of 7 (Hide remaining 5 Spinners).
How is possible to achieve my task. Any help will be appreciated.
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> MainMenuDescription1 = new ArrayList<String>();
List<String> MainMenuDescription2 = new ArrayList<String>();
List<String> MainMenuDescription3 = new ArrayList<String>();
List<String> MainMenuDescription4 = new ArrayList<String>();
List<String> MainMenuDescription5 = new ArrayList<String>();
List<String> MainMenuDescription6 = new ArrayList<String>();
List<String> MainMenuDescription7 = new ArrayList<String>();
List<String> MealDealCatCode = new ArrayList<String>();
int uniqueItemIdCount = 0;
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
JSONArray subMenuArray = object
.getJSONArray("MealDealItemEntity");
for (int j = 0; j < subMenuArray.length(); ++j) {
JSONObject subMenuObject = subMenuArray.getJSONObject(j);
Log.i("MealDealCatCode ",
subMenuObject.getString("MealDealCatCode"));
MealDealCatCode.add(subMenuObject
.getString("MealDealCatCode"));
MealDealCatCode = Utils
.removeDuplicatesFromList(MealDealCatCode);
uniqueItemIdCount = MealDealCatCode.size();
if (subMenuObject.getString("MealDealCatCode").trim()
.equals("L1")) {
Log.i("MainMenuDescription",
subMenuObject.getString("MainMenuDescription"));
MainMenuDescription1.add(subMenuObject
.getString("MainMenuDescription"));
}
if (subMenuObject.getString("MealDealCatCode").trim()
.equals("L2")) {
MainMenuDescription2.add(subMenuObject
.getString("MainMenuDescription"));
}
if (subMenuObject.getString("MealDealCatCode").trim()
.equals("L3")) {
MainMenuDescription3.add(subMenuObject
.getString("MainMenuDescription"));
}
if (subMenuObject.getString("MealDealCatCode").trim()
.equals("L4")) {
MainMenuDescription4.add(subMenuObject
.getString("MainMenuDescription"));
}
if (subMenuObject.getString("MealDealCatCode").trim()
.equals("L5")) {
MainMenuDescription5.add(subMenuObject
.getString("MainMenuDescription"));
}
if (subMenuObject.getString("MealDealCatCode").trim()
.equals("L6")) {
MainMenuDescription6.add(subMenuObject
.getString("MainMenuDescription"));
}
if (subMenuObject.getString("MealDealCatCode").trim()
.equals("L7")) {
MainMenuDescription7.add(subMenuObject
.getString("MainMenuDescription"));
}
}
item1SP = (Spinner) findViewById(R.id.sp_item1);
item2SP = (Spinner) findViewById(R.id.sp_item2);
item3SP = (Spinner) findViewById(R.id.sp_item3);
item4SP = (Spinner) findViewById(R.id.sp_item4);
item5SP = (Spinner) findViewById(R.id.sp_item5);
item6SP = (Spinner) findViewById(R.id.sp_item6);
item7SP = (Spinner) findViewById(R.id.sp_item7);
item1SP.setVisibility(View.GONE);
item2SP.setVisibility(View.GONE);
item3SP.setVisibility(View.GONE);
item4SP.setVisibility(View.GONE);
item5SP.setVisibility(View.GONE);
item6SP.setVisibility(View.GONE);
item7SP.setVisibility(View.GONE);
item1SP.setOnItemSelectedListener(new MyOnItemSelectedListener());
MainMenuDescription1 = Utils
.removeDuplicatesFromList(MainMenuDescription1);
ArrayAdapter<String> dataAdapterOne = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
MainMenuDescription1);
dataAdapterOne
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
item1SP.setAdapter(dataAdapterOne);
item1SP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterOne,
R.layout.contact_spinner_row_nothing_selected, this));
item2SP.setOnItemSelectedListener(new MyOnItemSelectedListener());
MainMenuDescription2 = Utils
.removeDuplicatesFromList(MainMenuDescription2);
ArrayAdapter<String> dataAdapterTwo = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
MainMenuDescription2);
dataAdapterTwo
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
item2SP.setAdapter(dataAdapterTwo);
item2SP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterTwo,
R.layout.contact_spinner_row_nothing_selected, this));
item3SP.setOnItemSelectedListener(new MyOnItemSelectedListener());
MainMenuDescription3 = Utils
.removeDuplicatesFromList(MainMenuDescription3);
ArrayAdapter<String> dataAdapterThree = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
MainMenuDescription3);
dataAdapterThree
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
item3SP.setAdapter(dataAdapterThree);
item3SP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterThree,
R.layout.contact_spinner_row_nothing_selected, this));
item4SP.setOnItemSelectedListener(new MyOnItemSelectedListener());
MainMenuDescription4 = Utils
.removeDuplicatesFromList(MainMenuDescription4);
ArrayAdapter<String> dataAdapterFour = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
MainMenuDescription4);
dataAdapterFour
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
item4SP.setAdapter(dataAdapterFour);
item4SP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterFour,
R.layout.contact_spinner_row_nothing_selected, this));
item5SP.setOnItemSelectedListener(new MyOnItemSelectedListener());
MainMenuDescription5 = Utils
.removeDuplicatesFromList(MainMenuDescription5);
ArrayAdapter<String> dataAdapterFive = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
MainMenuDescription5);
dataAdapterFive
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
item5SP.setAdapter(dataAdapterFive);
item5SP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterFive,
R.layout.contact_spinner_row_nothing_selected, this));
item6SP.setOnItemSelectedListener(new MyOnItemSelectedListener());
MainMenuDescription6 = Utils
.removeDuplicatesFromList(MainMenuDescription6);
ArrayAdapter<String> dataAdapterSix = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
MainMenuDescription6);
dataAdapterSix
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
item6SP.setAdapter(dataAdapterSix);
item6SP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterSix,
R.layout.contact_spinner_row_nothing_selected, this));
item7SP.setOnItemSelectedListener(new MyOnItemSelectedListener());
MainMenuDescription7 = Utils
.removeDuplicatesFromList(MainMenuDescription7);
ArrayAdapter<String> dataAdapterSeven = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
MainMenuDescription7);
dataAdapterSeven
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
item7SP.setAdapter(dataAdapterSeven);
item7SP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterSeven,
R.layout.contact_spinner_row_nothing_selected, this));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I was able to achieve what I want by following answer,
for (int a = 0; a < uniqueItemIdCount; a++) {
if (uniqueItemIdCount == 1) {
item1SP.setVisibility(View.VISIBLE);
}
if (uniqueItemIdCount == 2) {
item1SP.setVisibility(View.VISIBLE);
item2SP.setVisibility(View.VISIBLE);
}
if (uniqueItemIdCount == 3) {
item1SP.setVisibility(View.VISIBLE);
item2SP.setVisibility(View.VISIBLE);
item3SP.setVisibility(View.VISIBLE);
}
if (uniqueItemIdCount == 4) {
item1SP.setVisibility(View.VISIBLE);
item2SP.setVisibility(View.VISIBLE);
item3SP.setVisibility(View.VISIBLE);
item4SP.setVisibility(View.VISIBLE);
}
if (uniqueItemIdCount == 5) {
item1SP.setVisibility(View.VISIBLE);
item2SP.setVisibility(View.VISIBLE);
item3SP.setVisibility(View.VISIBLE);
item4SP.setVisibility(View.VISIBLE);
item5SP.setVisibility(View.VISIBLE);
}
if (uniqueItemIdCount == 6) {
item1SP.setVisibility(View.VISIBLE);
item2SP.setVisibility(View.VISIBLE);
item3SP.setVisibility(View.VISIBLE);
item4SP.setVisibility(View.VISIBLE);
item5SP.setVisibility(View.VISIBLE);
item6SP.setVisibility(View.VISIBLE);
}
if (uniqueItemIdCount == 7) {
item1SP.setVisibility(View.VISIBLE);
item2SP.setVisibility(View.VISIBLE);
item3SP.setVisibility(View.VISIBLE);
item4SP.setVisibility(View.VISIBLE);
item5SP.setVisibility(View.VISIBLE);
item6SP.setVisibility(View.VISIBLE);
item7SP.setVisibility(View.VISIBLE);
}
}

Issue with android spinners - Loading distinct values in spinners

I'm using two Spinners to show the items I'm getting from the json response. I have 2 problems right now. When u check my logcat u can see there are items repeating (Right side list, u can see so many pan). I want to have 1 item only once in my Spinner. I want to use something similar to distinct we use in sql databases.
My second problem is,
Select pan in the 1 spinner then 2nd spinner should contain items related to pan. (select pan in 1st spinner and 2nd should display only Pan large, pan medium and personal pan)
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> crust = new ArrayList<String>();
List<String> description = new ArrayList<String>();
List<String> extraDescription = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
JSONArray subMenuArray = object
.getJSONArray("SubMenuEntity");
for (int j = 0; j < subMenuArray.length(); ++j) {
JSONObject subMenuObject = subMenuArray
.getJSONObject(j);
Log.i("Crust", subMenuObject.getString("Crust"));
crust.add(subMenuObject.getString("Crust"));
Log.i("Description",
subMenuObject.getString("Description"));
description.add(subMenuObject.getString("Description"));
JSONArray extraItemEntityArray = subMenuObject
.getJSONArray("ExtraItemEntity");
}
}
crustSP = (Spinner) findViewById(R.id.sp_crust);
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
sizeSP = (Spinner) findViewById(R.id.sp_pizza_size);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Output of this
Call this method to get distinct descriptions and then set the adapter using the return value of this function...
public static ArrayList<String> removeDuplicatesFromList(ArrayList<String> descriptions)
{
ArrayList<String> tempList = new ArrayList<String>();
for(String desc : descriptions)
{
if(!tempList.contains(desc))
{
tempList.add(desc);
}
}
descriptions = tempList;
tempList = null;
return descriptions;
}
For instance
description = Utils.removeDuplicatesFromList(description);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
NOTE:
I would suggest you make a new class call it Utils.java and place the above method inside it and then call it i have mentioned above.
Like this...
import java.util.ArrayList;
public class Utils
{
private Utils()
{
//Its constructor should not exist.Hence this.
}
public static ArrayList<String> removeDuplicatesFromList(ArrayList<String> descriptions)
{
ArrayList<String> tempList = new ArrayList<String>();
for(String desc : descriptions)
{
if(!tempList.contains(desc))
{
tempList.add(desc);
}
}
descriptions = tempList;
tempList = null;
return descriptions;
}
}
I hope it helps.

How to add spinner inside a listview

i'd like each for row in listview has a spinner. But can not. please help me.
//Setting player
adapter = new SimpleAdapter(this, list, R.layout.custom_listitem_edit,
new String[] { "cat", "duration", "order", "id_pos"}, new int[] {
R.id.spn_edibt_selectcat,
/*R.id.spn_editbt_selectpos,*/
R.id.txt_editbt_dur,
R.id.txt_editbt_order,
R.id.txt_edit_idpos
});
populateList();
setListAdapter(adapter);
static final ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
/* Set thong tin cho listview */
private void populateList() {
cursor_position_mycurrent = dbHelper_position_mycurrent.fetchAllPositionMyCurrentById(id_bt);
startManagingCursor(cursor_position_mycurrent);
Log.e("SO dong lay duoc la", String.valueOf(cursor_position_mycurrent.getCount()));
if (cursor_position_mycurrent != null) {
cursor_position_mycurrent.moveToFirst();
while (cursor_position_mycurrent.isAfterLast() == false) {
HashMap<String, String> tmp = new HashMap<String, String>();
Log.e("DUR", cursor_position_mycurrent.getString(5));
Log.e("DUR", cursor_position_mycurrent.getString(6));
tmp.put("duration", cursor_position_mycurrent.getString(5));
tmp.put("order", cursor_position_mycurrent.getString(6));
tmp.put("id_pos", cursor_position_mycurrent.getString(0));
//Setting spinner category
cursor_position_allposition =dbHelper_position_allposition.fetchAllPositions();
array_spinner_category = new String[cursor_position_allposition.getCount()];
if (cursor_position_allposition != null) {
int i = 0;
cursor_position_allposition.moveToFirst();
while (cursor_position_allposition.isAfterLast() == false) {
array_spinner_category[i] = cursor_position_allposition.getString(0);
cursor_position_allposition.moveToNext();
i++;
}
cursor_position_allposition.close();
}
Log.e("ALL POS", String.valueOf(cursor_position_allposition.getCount()));
Spinner spinner = (Spinner) findViewById(R.id.spn_edibt_selectcat);
int m = 3;//Integer.parseInt(camping.rulesList.getMaxPers().get(camping.tipSel));
String[] array_spinner=new String[m];
for (int indice = 0; indice < m; indice++)
{
if (indice == 0) array_spinner[indice] = String.format("%d persona", indice+1);
else array_spinner[indice] = String.format("%d persone", indice+1);
}
final ArrayAdapter<String> aa = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, array_spinner);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(aa);
list.add(tmp);
cursor_position_mycurrent.moveToNext();
}
}
}

Categories

Resources