What I'd like to accomplish is the String array names[] be what you see in the spinner, but I cannot seem to figure out how to do this. I have tried looking off of other similar questions, but everything I try results in a crash in my app, saying that it is unable to instantiate the activity. Below, I have included the onPostExecute, where I am generating the string array, and also my addListenerOnSpinnerSelection() method. Any guidance would be great.
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
Related
I have a spinner populated with custom adapter.
My code used to bind data to spinner is
private void setOperatorSpinnerAdapter(Spinner spinner, String data) {
listOperator = new ArrayList<>();
try {
jsonObject = new JSONObject(data);
jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
model2 = new LiabModel();
model2.setName(jsonObject.optString("name"));
listOperator.add(model2);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter_liab = new CustomListAdapter_liab(LiabilitiesActivity.this, listOperator);
spinner.setAdapter(adapter_liab);
}
My issue is with item selection. I am getting error as
java.lang.ClassCastException: java.lang.Integer cannot be cast to Model.LiabModel
My spinner item click code is
spnr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
LiabModel model2 = (LiabModel) parent.getItemAtPosition(position);
liab_type = model2.getName();
}
catch (Exception e){
Log.e("exc",""+e);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Im getting Class Cast exception in
"LiabModel model2 = (LiabModel) parent.getItemAtPosition(position);" this line. Why is that happening?
you can get selected value either by this
LiabModel model2 = (LiabModel) spnr.getItemAtPosition(position);
or by if listOperator is accessable
LiabModel model2 = listOperator.get(position);
I am loading some json into a list view and want to delete items from the list on click and for the item to be deleted from the json. The delete functionality seems to be working. The method delete is called, the items are removed on click and debugging shows the item being removed. However after going to another activity and viewing the list again, the deleted items come back. what am i doing wrong? This is my class:
public class edit extends AppCompatActivity
{
public ListView pizzaList;
ListView addicList;
ArrayAdapter<String> arrayAdapter;
String appreciations;
String currentPizza;
ArrayList<String> list = new ArrayList<String>();
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
pizzaList = (ListView) findViewById(R.id.pizzas);
registerForContextMenu(pizzaList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
pizzaList.setAdapter(arrayAdapter);
pizzaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
delete(view,position);
arrayAdapter.notifyDataSetChanged();
}
});
try {
FileManager fileManager = new FileManager();
String str = fileManager.ReadFile(this);
if (str != null) {
JSONArray jarray = new JSONArray(str);
String outputText = "";
for (int i = 0; i < jarray.length(); i++) {
JSONObject jsonObject = jarray.getJSONObject(i);
String pizzaName = jsonObject.getString("name");
int price = jsonObject.getInt("price");
outputText = outputText + " " + pizzaName + " " + " $" + price + "\n";
appreciations = outputText;
list.add(appreciations);
arrayAdapter.notifyDataSetChanged();
outputText = "";
}
} else {
Toast to = Toast.makeText(getApplicationContext(), "No saved Pizzas", Toast.LENGTH_LONG);
to.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void delete(View view, int pos)
{
try {
FileManager fileManager = new FileManager();
String str = fileManager.ReadFile(this);
if (str != null)
{
JSONArray jarray = new JSONArray(str);
JSONObject jsonObject = jarray.getJSONObject(pos);
jarray.remove(pos);
list.remove(pos);
arrayAdapter.notifyDataSetChanged();
JSONArray jsArray = new JSONArray(jarray);
arrayAdapter.notifyDataSetChanged();
} else {
Toast to = Toast.makeText(getApplicationContext(), "No saved Pizzas", Toast.LENGTH_LONG);
to.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You would need to remove the item from the database, use asynchronous request such as volley or robospice for it. Then instead of making the request when coming back you would use the data stored on the cache the second time and only make the request again when data has been changed. You can create your cache logic in your application class to make it visible throughout your app.
I have made a spinner dynamically during a login process. I'd like to be able to return the value of the spinner when I click on an option but it doesn't seem to work.
I make the spinner here:
public Spinner page_spinner;
protected void onCreate(Bundle savedInstanceState){
...
page_spinner = (Spinner) findViewById(R.id.page_spinner);
...
//MAKE ARRAY HERE
GraphRequest requestPage = GraphRequest.newGraphPathRequest(
currentAccessToken,
"/me/accounts",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONObject().getJSONArray("data");
for(int i=0; i < jsonArray.length(); i++){
JSONObject page = jsonArray.getJSONObject(i);
String pageName = page.getString("name");
if(!pageName.equals("")) {
//Push names into the array
pages_array.add(pageName);
} else {
pages_array.clear();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle pageParameters = new Bundle();
pageParameters.putString("fields", "name,access_token,picture{url}");
requestPage.setParameters(pageParameters);
requestPage.executeAsync();
...
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(StartPage.this, android.R.layout.simple_spinner_item, pages_array);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
page_spinner.setAdapter(spinnerArrayAdapter);
spinnerArrayAdapter.notifyDataSetChanged();
then I try to use the spinner here:
page_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("***********", "THIS ");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("***********", "THIS ");
}
});
I don't ever get the Log.d or even if I made Toast there, it doesn't fire. Not sure why this is stopping and I'm not getting any errors.
Any ideas?
Declare the spinner as a global variable and without final
and try this:
page_spinner = (Spinner) findViewById(R.id.page_spinner);
...
//MAKE ARRAY HERE
GraphRequest requestPage = GraphRequest.newGraphPathRequest(
currentAccessToken,
"/me/accounts",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONObject().getJSONArray("data");
for(int i=0; i < jsonArray.length(); i++){
JSONObject page = jsonArray.getJSONObject(i);
String pageName = page.getString("name");
if(!pageName.equals("")) {
//Push names into the array
pages_array.add(pageName);
} else {
pages_array.clear();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(StartPage.this, android.R.layout.simple_spinner_item, pages_array);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
page_spinner.setAdapter(spinnerArrayAdapter);
spinnerArrayAdapter.notifyDataSetChanged();
}
});
Your error seems somewhat correct. You are not notifying adapter about the changes in dataset.
Firstly, Your request is executed Async. So, your code execution will continue to next lines. So I guess, a blank array (size 0) is passed to ArrayAdapter<> and then the adapter is set to Spinner and then you are calling notifyDataSetChanged().
I think you should call spinnerArrayAdapter.notifyDataSetChanged();as below:
#Override
public void onCompleted(GraphResponse response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONObject().getJSONArray("data");
for(int i=0; i < jsonArray.length(); i++){
JSONObject page = jsonArray.getJSONObject(i);
String pageName = page.getString("name");
if(!pageName.equals("")) {
//Push names into the array
pages_array.add(pageName);
} else {
pages_array.clear();
}
}
spinnerArrayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
I've tested your codes and everything seems Right here. First I tried Adding 10 Items at spinner. Everything worked fine. And I tested adding List of String which contains only one Item.
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Item 1");
My OnItemSelectedListener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
But what happened is the code everything worked fine before was not working after because there is only one item in spinnerArray. Toast was shown when Activity loads and not called when item is selected. You may have the same issue there. So my suggestion is give priority to your Array which may contain only one item.
Friends !! I have two Spinner and Data is coming from JSON. I am able to PARSE data and display into Spinner. In first Spinner There are number of nodes which have number s of Details. So my requirement is to populate Second Spinner Based on Selection of First Spinner .. Please help me
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
c = c.getJSONObject("LearningStandards");
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
/*String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);*/
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
/*map.put(TAG_NAME, name);
map.put(TAG_API, api);*/
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("ref_id"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
Use: spinner.setOnItemSelectedListener
I have created Category and Subcategory spinners. Subcategory values are showed based on Category selection.
Following is the code sample:
spn_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String selection = spn_category.getSelectedItem().toString();
ArrayAdapter<String> selection_subcat = new ArrayAdapter<String>(ServiceProviderProfileEdit.this,
android.R.layout.simple_spinner_dropdown_item, CategoryInfo.getSubCategories(selection));
spn_subcategory.setAdapter(selection_subcat);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here (optional)
}
});
Hope it will help you..!
//Answer to your comment:
JSONArray data = jsonObject.getJSONArray("LearningStandards");
ArrayAdapter<String> adapter_standard_title = .... //parse standard_title here
spn_title.setAdapter(adapter_standard_title); //set adapter of standard_titles to spinner
//use setOnItemSelectedListener on spn_title
//in onItemSelected you will receive the clicked category
//you can convert it in string using:
String selected_title = spn_title.getSelectedItem().toString();
//parse ref_id/other req field based on this selected_title
Below I have attached my code for trying to add my string array, names, to the spinner as the options. As of now, I am not getting anything populating the array, and I am really not sure what I'm doing wrong. I have looked over other similar questions on this site, as well as using Google, and have come up empty. Can anyone give me some guidance? Thanks
public class RunesActivity extends Activity {
public static String page;
TextView textName;
Spinner spinner;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rune_activity);
GetRunes getRunes = new GetRunes();
getRunes.execute();
spinner = (Spinner) findViewById(R.id.rune_selector);
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
class GetRunes extends AsyncTask<String, String, JSONObject> {
private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
String region = MainActivity.region.toLowerCase();
String id = StatsActivity.sumID;
String encodedKey = null;
String encodedRegion = null;
String encodedId = null;
String url = null;
// JSON Node Names
String TAG_NAME = "name";
String TAG_CURRENT = "current";
String TAG_SLOTS = "slots";
String TAG_RUNEID = "runeId";
String TAG_RUNESLOTID = "runeSlotId";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
// Assign views
textName = (TextView) findViewById(R.id.name);
// Encode URL variables
encodedId = URLEncoder.encode(id, "UTF-8");
encodedKey = URLEncoder.encode(api_key, "UTF-8");
encodedRegion = URLEncoder.encode(region, "UTF-8");
url = "http://prod.api.pvp.net/api/lol/" + region + "/v1.4/summoner/" + id + "/runes?api_key=" + api_key;
Log.i("..........", url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.i("............", "" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this..
before calling addListenerOnSpinnerSelection(); method set adapter for that spinner.
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
spinner.setAdapter(adapter );
addListenerOnSpinnerSelection();