Update City Spinner with notifyDataSetChanged after state is selected - java

How do I update my city spinner once the user selects a state?
Both fields are populated using a DataCall.class that returns JSON data and parses the info into an array for the spinner.
My code below sets the city adapter to a defualt "Select State" value and once the user gets selects the state it should use notifyDataSetChanged since the default array for the city spinner is updated with the new city names. The errors I am getting are commented in my code below.
public class SearchActivity extends Activity{
private static final String TAG = "MyApp";
ArrayAdapter<String> adapter2;
String city_values[] = new String[]{"Please select a state."};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final Spinner zipspinner = (Spinner) findViewById(R.id.zipspinner);
final Spinner cityspinner = (Spinner) findViewById(R.id.cityspinner);
adapter2 = new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item, city_values);
adapter2.setDropDownViewResource(R.layout.city_spinner_layout);
cityspinner.setAdapter(adapter2);
JSONArray jsonArray;
try {
String spinnerContentType = "state";
String spinnerURL = "getStoreState.php";
String spinner_data = DataCall.getJSON(spinnerURL,spinnerContentType);
Log.d(TAG, spinner_data);
jsonArray = new JSONArray(spinner_data);
final String[] array_spinner = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++) {
String styleValue = jsonArray.getJSONArray(i).getString(0);
Log.d(TAG, styleValue);
array_spinner[i] = styleValue;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
adapter.setDropDownViewResource(R.layout.state_spinner_layout);
zipspinner.setAdapter(adapter);
zipspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
int item = zipspinner.getSelectedItemPosition();
if(item != 0){
String item_value = array_spinner[item];
String spinnerContentType = "city";
String spinnerURL = "getStoreCity.php?state=" + item_value;
Log.d(TAG, spinnerURL);
String city_data = DataCall.getJSON(spinnerURL,spinnerContentType);
Log.d(TAG, city_data);
JSONArray cityArray = null;
try {
cityArray = new JSONArray(city_data);
} catch (JSONException e) {
e.printStackTrace();
}
final String[] city_spinner = new String[cityArray.length()];
for (int i=0; i<cityArray.length(); i++){
String styleValue = null;
try {
styleValue = cityArray.getJSONArray(i).getString(0);
Log.d(TAG, styleValue);
} catch (JSONException e) {
e.printStackTrace();
}
city_spinner[i] = styleValue;
}
city_values = city_spinner;
adapter2.notifyDataSetChanged();
String test_string = "NOTIFY UPDATE";
Log.d(TAG, test_string);
} else {
// finish();
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
int item = zipspinner.getSelectedItemPosition();
if(item != 0){
}else{
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}catch (JSONException e) {
e.printStackTrace();
}
}
}

Well, this is how I will suggest,
First of all check that you are getting values in city_values.
Then, notify the adapter.... adapter2.notifyDataSetChanged();
And finally cityspinner.setSelection(0);
UPDATE:
I would suggest to trake ArrayList<String> instead of String[]
Thanks...

public class SearchActivity extends Activity {
ArrayAdapter<String> adapter2;
String city_values[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final Spinner zipspinner = (Spinner) findViewById(R.id.zipspinner);
final Spinner cityspinner = (Spinner) findViewById(R.id.cityspinner);
String city_values[] = new String[]{"Please select a state."};
adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, city_values);
adapter2.setDropDownViewResource(R.layout.city_spinner_layout);
cityspinner.setAdapter(adapter2);
JSONArray jsonArray;
final JSONArray cityArray;
try {
String spinnerContentType = "state";
String spinnerURL = "getStoreState.php";
String spinner_data = DataCall.getJSON(spinnerURL, spinnerContentType);
jsonArray = new JSONArray(spinner_data);
final String[] array_spinner = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
String styleValue = jsonArray.getJSONArray(i).getString(0);
array_spinner[i] = styleValue;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_spinner);
adapter.setDropDownViewResource(R.layout.state_spinner_layout);
zipspinner.setAdapter(adapter);
zipspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
int item = zipspinner.getSelectedItemPosition();
String item_value = array_spinner[item];
String spinnerContentType = "city";
String spinnerURL = "getStoreCity.php?state=" + item_value;
String city_data = DataCall.getJSON(spinnerURL, spinnerContentType);
cityArray = new JSONArray(city_data); //The final local variable cityArray cannot be assigned, since it is defined in an enclosing type
final String[] city_spinner = new String[cityArray.length()];
for (int i = 0; i < cityArray.length(); i++) {
String styleValue = cityArray.getJSONArray(i).getString(0); //Unhandled exception type JSONException
city_spinner[i] = styleValue;
}
city_values = city_spinner; //Unhandled exception type JSONException
adapter2.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView parent {
// Do nothing.
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
now try

Declare the city_array variable at the place where you assign a new JSONArray(). Anyways you are using it temporarily. Just set the adapter again.

Related

filtering listview results after selecting spinner value

I have 3 spinners in my project named standard, division and age. They contain values from json data. When I select a value from each individual spinner it shows all data of students in a listview respectivly (fetched from json).
I'm working with the following JSON data:
[
{
"name":"aarti",
"surname":"singh",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"seema",
"surname":"desai",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"tina",
"surname":"joshi",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"megha",
"surname":"kale",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"swati",
"surname":"marathe",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"rekha",
"surname":"surve",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"madhu",
"surname":"dalvi",
"age":"18",
"div":"B",
"standard":"6"
}
I am trying to do it like this way:
When I select standard 7 from the spinner it should display students information studying in 7th standard ("aarti", "seema", "megha", "rekha") and their other information too.
Then I am selecting value from division spinner say "A", it should take above result granted and accordingly display students from standard 7 and division "A". It should shows the result as ("aarti", "megha", "rekha") and their other informations too.
Finally when I am selecting value from age spinner say "17", it should take above result granted and accordingly display students from standard 7 and division "A" and age "17". Accordingly it shows "megha" and "rekha".
Can anyone please assist me
This is my MainActivity.java class:
public class MainActivity extends AppCompatActivity {
ArrayList<String> AllStandards = new ArrayList<>();
ArrayList<String> AllDivision = new ArrayList<>();
ArrayList<String> AllAge = new ArrayList<>();
JSONArray jsonArray;
Spinner spinner_std, spinner_div, spinner_age;
private ArrayList<StudInfo> studentVOList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<String> item_Std = getStandard("data.json");
final List<String> items_div = getDivision("data.json");
final List<String> items_age = getAge("data.json");
/*spinner for standard*/
spinner_std = (Spinner) findViewById(R.id.spinnerStandard);
ArrayAdapter<String> adapter_std = new ArrayAdapter<String>(this, R.layout.spinner_standard_layout, R.id.textViewStandard, item_Std);
adapter_std.getFilter().filter(txt);
spinner_std.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)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setStandard(jsonObject.getString("standard"));
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_std.setAdapter(adapter_std);
/*spinner for division*/
spinner_div = (Spinner) findViewById(R.id.spinnerDiv);
ArrayAdapter<String> adapter_div = new ArrayAdapter<String>(this, R.layout.spinner_division_layout, R.id.textViewDivision, items_div);
adapter_div.getFilter().filter(txt);
spinner_div.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String division = AllDivision.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String div = jsonObject.getString("div");
// Collections.sort(AllDivision);
if (div.equalsIgnoreCase(division)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setDiv(div);
studentVOList.add(studentVO);
}
}
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_div.setAdapter(adapter_div);
/*spinner for age*/
spinner_age = (Spinner) findViewById(R.id.spinerAge);
ArrayAdapter<String> adapter_age = new ArrayAdapter<String>(this, R.layout.spinner_age_layout, R.id.textViewAge, items_age);
adapter_age.getFilter().filter(txt);
spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
String age = AllAge.get(i);
if (studentVOList.size() > 0)
studentVOList.clear();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
String age_list = jsonObject.getString("age");
Collections.sort(AllAge);
if (age_list.equalsIgnoreCase(age)) {
StudInfo studentVO = new StudInfo();
studentVO.setName(jsonObject.getString("name"));
studentVO.setSurname(jsonObject.getString("surname"));
studentVO.setDiv(jsonObject.getString("div"));
studentVO.setStandard(jsonObject.getString("standard"));
studentVO.setAge(jsonObject.getString("age"));
studentVO.setAge(age_list);
studentVOList.add(studentVO);
}
}
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_age.setAdapter(adapter_age);
}//onCreate Method
private List<String> getStandard(String fileName) {
jsonArray = null;
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;
}
private List<String> getDivision(String fileName) {
jsonArray = null;
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");
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("div");
if (!AllDivision.contains(stand)) {
AllDivision.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllDivision;
}
private List<String> getAge(String fileName) {
jsonArray = null;
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");
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String stand = jsonObject.getString("age");
if (!AllAge.contains(stand)) {
AllAge.add(stand);
}
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return AllAge;
}
this is my ListAdapter.java class
public class ListAdapter extends ArrayAdapter<StudInfo> {
int vg;
ArrayList<StudInfo> list;
Context context;
public ListAdapter(Context context, int vg, int id, ArrayList<StudInfo> list) {
super(context, vg, id, list);
this.context = context;
this.vg = vg;
this.list = list;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(vg, parent, false);
TextView textViewName = (TextView) itemView.findViewById(R.id.txtName);
TextView textViewSurname = (TextView)itemView.findViewById(R.id.txtSurname);
TextView textViewAge = (TextView) itemView.findViewById(R.id.txtAge);
TextView textViewDiv = (TextView) itemView.findViewById(R.id.txtDiv);
TextView textViewStd = (TextView) itemView.findViewById(R.id.txtStandard);
textViewName.setText(list.get(position).getName());
textViewSurname.setText(list.get(position).getSurname());
textViewAge.setText(list.get(position).getAge());
textViewDiv.setText(list.get(position).getDiv());
textViewStd.setText(list.get(position).getStandard());
return itemView;
}
}
this is my StudentsInfo.java class
public class StudentsInfo extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.studentsinfo_layout);
Bundle b = getIntent().getBundleExtra("bundle");
ArrayList<StudInfo> studentVOList = (ArrayList<StudInfo>) b.getSerializable("list");
ListView listView = (ListView) findViewById(R.id.listViewShow);
ListAdapter listAdapter = new ListAdapter(this, R.layout.list_layout, R.id.txtName, studentVOList);
listView.setAdapter(listAdapter);
}
}
this is my StudInfo.java class,
import java.io.Serializable;
public class StudInfo 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;
}
}
i tried googling to find out solution but the questions i found all are based on searching listview items using edittext.i didn't found ant similar post matching with my question which solve my problem.can anyone please help me to solve this??
1. Override getFilter method in your adapter class
2. Use adapter.getFilter().filter(txt) in your spinner selection
package com.hughesnet.adapters;
import com.hughesnet.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<StudInfo> {
int vg;
ArrayList<StudInfo> list;
Context context;
ItemFilter mFilter;
ArrayList<StudInfo> filteredData;
public ListAdapter (Context context, int vg, int id, ArrayList<StudInfo> list) {
super (context, vg, id, list);
this.context = context;
this.vg = vg;
this.list = list;
}
public View getView (int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate (vg, parent, false);
TextView textViewName = (TextView) itemView.findViewById (R.id.txtName);
TextView textViewSurname = (TextView) itemView.findViewById (R.id.txtSurname);
TextView textViewAge = (TextView) itemView.findViewById (R.id.txtAge);
TextView textViewDiv = (TextView) itemView.findViewById (R.id.txtDiv);
TextView textViewStd = (TextView) itemView.findViewById (R.id.txtStandard);
textViewName.setText (list.get (position).getName ());
textViewSurname.setText (list.get (position).getSurname ());
textViewAge.setText (list.get (position).getAge ());
textViewDiv.setText (list.get (position).getDiv ());
textViewStd.setText (list.get (position).getStandard ());
return itemView;
}
ItemFilter mFilter = new ItemFilter ();
public Filter getFilter () {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering (CharSequence constraint) {
String filterString = constraint.toString ().toLowerCase ();
FilterResults results = new FilterResults ();
int count = list.size ();
final ArrayList<StudInfo> nlist = new ArrayList<StudInfo> (count);
String filterableString;
for (int i = 0; i < count; i++) {
StudInfo info = list.get (i);
// Check for standard, division and age here
if (info.getAge().contains(filterString) || info.getStandard().contains(filterString ) || info.getDiv().contains(filterString )) {
nlist.add (filterableString);
}
}
results.values = nlist;
results.count = nlist.size ();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<StudInfo>) results.values;
notifyDataSetChanged();
}
}
}

accessing specific itemview in listview in button onclick method

public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "**";
private static String url_update_bet = "**";
// Progress Dialog
private ProgressDialog pDialog;
private ProgressDialog tDialog;
private BetDisplayer currentitem;
private HashMap<String, String> userhash = new HashMap<>();
private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
private HashMap<String, String> useroutcomes = new HashMap<>();
private HashMap<String, String> finalhash = new HashMap<>();
private ArrayList<Map<String, String>> passtocheck = new ArrayList<>();
private HashMap<String, HashMap<String, String>> passtocheckver2 = new HashMap<>();
private String name;
private HashMap<String, String> allopens = new HashMap<>();
JSONParser jsonParser = new JSONParser();
// Creating JSON Parser object
JSONParsers jParser = new JSONParsers();
ArrayList<HashMap<String, String>> bet;
// url to get all products list
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BET = "bet";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_USER = "user";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray allgames = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
name = (getIntent().getExtras().getString("user")).toLowerCase();
Log.d("name", name);
// Hashmap for ListView
bet = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllGames().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
// *//**
// * Before starting background thread Show Progress Dialog
// *//*
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Games. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
}
// *//**
// * getting All products from url
// *//*
protected String doInBackground(String... args) {
// Building Parameters
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_all_games);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", name));
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Response:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
Log.d("sb", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("json", jObj.toString());
try {
allgames = jObj.getJSONArray(TAG_BET);
Log.d("allgames", allgames.toString());
ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
Log.d("id", id);
Log.d("user", user);
Log.d("returns", returns);
Log.d("stake", stake);
Log.d("status", status);
Log.d("teams", Teams);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
if (status.equals("open")) {
useroutcomes.put(id.substring(0, 10), Teams);
}
listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, Teams));
// adding HashList to ArrayList
bet.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
String ultparam = "";
int i = 0;
for (HashMap<String, String> a : bet) {
String teams = a.get(TAG_TEAMS);
Map<String, String> listofteams = new HashMap<>();
Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
Matcher m = p.matcher(teams);
Log.d("printa", teams);
while (m.find()) {
listofteams.put(m.group(1), m.group(2));
}
Log.d("dede", listofteams.toString());
String c = "";
for (String x : listofteams.keySet()) {
String b = x + ",";
c = c + b;
}
Log.d("C", c);
c = c.substring(0, c.lastIndexOf(","));
// Log.d("Cproc", c);
if (a.get(TAG_STATUS).equals("open")) {
ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
passtocheck.add(listofteams);
allopens.put(Integer.toString(i), a.get(TAG_STATUS));
i++;
}
i++;
}
ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
Log.d("ULTPARAM", ultparam);
CheckBet checker = new CheckBet(ultparam, passtocheck);
HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
Log.d("Finaloutcomes", finaloutcomes.toString());
for (String x : finaloutcomes.keySet()) {
for (int p = 0; p < listwriter.size(); p++) {
if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
for (int r = 0; r < finaloutcomearray.length; r++) {
Log.d("finaloutcomearray", finaloutcomearray[r]);
Log.d("useroutcomearray", useroutcomearray[r]);
String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
String[] induseroutcomearray = useroutcomearray[r].split("\\)");
for (int d = 0; d < indfinaloutcomesarray.length; d++) {
Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
Log.d("induseroutcome", induseroutcomearray[d]);
finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));
}
}
Log.d("FINALHASHfinal", finalhash.toString());
Log.d("USERHASHfinal", userhash.toString());
listwriter.get(p).setStatus("won");
for (String id : userhash.keySet()) {
if (finalhash.get(id).equals("null")){
listwriter.get(p).setStatus("open");
}
else if (!(finalhash.get(id).equals(userhash.get(id)))) {
listwriter.get(p).setStatus("lost");
break;
}
}
finalhash.clear();
userhash.clear();
currentitem = listwriter.get(p);
new UpdateBetStatus().execute();
}
}
}
Log.d("USEROUTCOMES", useroutcomes.toString());
PopulateList();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_display_all_bets, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class UpdateBetStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* *
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
tDialog = new ProgressDialog(DisplayAllBets.this);
tDialog.setMessage("Loading your bets! Good luck!");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
}
/**
* Creating product
* *
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", currentitem.getId()));
params.add(new BasicNameValuePair("stake", Integer.toString(currentitem.getStake())));
params.add(new BasicNameValuePair("user", name));
params.add(new BasicNameValuePair("returns", Integer.toString(currentitem.getReturns())));
params.add(new BasicNameValuePair("teams", currentitem.getSelections()));
params.add(new BasicNameValuePair("status", currentitem.getStatus()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_bet,
"POST", params);
// check log cat fro response
Log.d("Printing", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* * * *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
private class MyListAdapter extends ArrayAdapter<BetDisplayer> {
public MyListAdapter() {
super(DisplayAllBets.this, R.layout.activity_singletotalbet, listwriter);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.activity_singletotalbet, parent, false);
}
BetDisplayer currentwriter = listwriter.get(position);
Log.d("TESTING", currentwriter.getSelections());
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setTag(Integer.toString(position));
Log.d("TESTING2", currentwriter.getSelections());
String selections = currentwriter.getSelections();
int numberofselections = 0;
for (int i = 0; i < selections.length(); i++) {
if (selections.charAt(i) == '/') {
numberofselections++;
}
}
if (numberofselections == 1) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Single");
} else if (numberofselections == 2) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Double");
} else if (numberofselections == 3) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Treble");
} else {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Accumulator" + "(" + numberofselections + ")");
}
TextView status = (TextView) itemView.findViewById(R.id.status);
status.setText(currentwriter.getStatus());
return itemView;
}
}
private void PopulateList() {
ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.betslistviews);
list.setAdapter(adapter);
}
public void Viewdetails(View v) {
Button b = (Button) v;
int position = Integer.parseInt((String) v.getTag());
final ListView list = (ListView) findViewById(R.id.betslistviews);
String stake;
String winnings;
String token;
String teams;
String typeofbet;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
I have a populated listview. Each item in the list contains a button and a few TextViews, in the following format.
I created a method which is run when any of the buttons is clicked. What I need it to do is to retrieve that particular itemView at that position in the listview so I can access the TextViews in that itemview. This is my code but it isn't working atm.
public void Viewdetails(View v) {
Button b = (Button) v;
int position = Integer.parseInt((String) v.getTag());
final ListView list = (ListView) findViewById(R.id.betslistviews);
String stake;
String winnings;
String token;
String teams;
String typeofbet;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
View selItem = (View) list.getItemAtPosition(position);
TextView status = (TextView) selItem.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
Assuming your ListView listener starts here.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
View selItem = (View) list.getItemAtPosition(position);
TextView status = (TextView) selItem.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
You don't have to write
View selItem = (View) list.getItemAtPosition(position);
since you already got reference to the particular View in ListView from the overridden onItemClick method.
So you can skip that line and directly access TextView
TextView status = (TextView) v.findViewById(R.id.status);
Finally the code will be like
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
//Already got reference to View v
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
To catch onListItemClick add listener in PopulateList() method:
private void PopulateList() {
ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.betslistviews);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
// Change children of list item here
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
To catch click on button in your list item you need in your adapter's getView() method add click listener to button:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Handle button click
}
});
}
EDIT:
To store data create fields in Activity and setters for it:
private String text1;
private String text2;
public void setText1(String text){
text1 = text;
}
public void setText2(String text){
text2 = text;
}
Then set it in button click listener:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv1 = (TextView) itemView.findViewById(R.id.textview1_id);
TextView tv2 = (TextView) itemView.findViewById(R.id.textview2_id);
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText1(tv1.getText());
setText2(tv2.getText());
}
});
}

"returnRes cannot be resolved to a variable" error in android

I had tested the function of endless Scrolling function in a dummy projects, it works fine but if i paste the same code in my original project m getting "loadMoreListItems cannot be resolved to a variable" on the variable "loadMoreListItems" and "returnRes cannot be resolved to a variable" on the variable, even i checked for android.R imports and layout name everything is correct dont know where is the mistake.
public class Home extends ListActivity {
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;
LinearLayout line1,line2;
ImageView menu;
boolean loadingMore = false;
ArrayList<String> songsList1;
LayoutInflater inflater;
static int jsonpage = 0;
JSONParser jParser;
JSONObject json;
TextView loadtext;
// All static variables
static final String URL = "http://www.exm.com/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView) findViewById(android.R.id.list);
// get the LayoutInflater for inflating the customomView
// this will be used in the custom adapter
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
songsList = new ArrayList<HashMap<String, String>>();
_loaddata();
LayoutInflater li = LayoutInflater.from(getBaseContext());
View footerView = li.inflate(com.exm.com.R.layout.listfooter, null);
loadtext = (TextView) footerView.findViewById(R.id.empty);
loadtext.setEnabled(false);
loadtext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "poda",
Toast.LENGTH_LONG).show();
}
});
this.getListView().addFooterView(footerView);
// Getting adapter by passing json data ArrayList
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(
getApplicationContext(),
"Click ListItem Number "
+ songsList.get(position).get("title"),
Toast.LENGTH_LONG).show();
}
});
this.getListView().setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// int first = view.getFirstVisiblePosition();
// int count = view.getChildCount();
//
// if (scrollState == SCROLL_STATE_IDLE
// || (first + count > adapter.getCount())) {
// list.invalidateViews();
// }
if (scrollState == SCROLL_STATE_IDLE) {
_loaddata();
adapter.notifyDataSetChanged();
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
#SuppressWarnings("unused")
private void _loaddata() {
try {
// getting JSON string from URL
jParser = new JSONParser();
jsonpage = jsonpage + 1;
json = jParser
.getJSONFromUrl("http://india.exm.net/ads/page/"
+ jsonpage + "/?json=get_recent_posts");
posts = json.getJSONArray(KEY_POSTS);
if (posts.length() > 0) {
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
// authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for (int j = 0; j < atta.length(); j++) {
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images
.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL,
url);
// adding HashList to ArrayList
songsList.add(map);
}
} else
loadtext.setText("Data ivlo thaan irukku k va summa look-u vidatha");
} catch (JSONException e) {
e.printStackTrace();
}
// Runnable to load the items
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
songsList1 = new ArrayList<String>();
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
runOnUiThread(returnRes);
}
};
// Since we cant update our UI from a thread this Runnable takes care of
// that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
if (songsList1 != null && songsList1.size() > 0) {
for (int i = 0; i < songsList1.size(); i++)
adapter.add(songsList1.get(i));
}
// Update the Application title
setTitle("Neverending List with "
+ String.valueOf(adapter.getCount()) + " items");
// Tell to the adapter that changes have been made, this will cause
// the list to refresh
adapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
This has nothing to do with Android resources.
The variable loadMoreListItems is used in onCreate(), but it is defined in _loaddata(). You cannot define a variable in one method and use it in another method.
You could return loadMoreListItems from _loaddata()
private Runnable _loaddata() {
...
return loadMoreListItems;
}
and use it in onCreate() like
Runnable loadMoreListItems = _loaddata();
...
Thread thread = new Thread(null, loadMoreListItems);
And you use returnRes in Runnable loadMoreListItems before it is defined later in the same method. You must first define and initialize returnRes and then you can use it in loadMoreListItems. So moving returnRes before loadMoreListItems should solve this one.

Listview becomes empty after giving the keyword in search bar in android

Currently i'm working on How to find the items from the listview when given the keyword for the item in edittext, the listview becomes empty and the output is displaying in toast message, can anybody help like how to make the found "item" to display it in listivew?
public class Home extends ListActivity {
//how many to load on reaching the bottom
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> songsList;
ListView list;
LazyAdapter adapter, adapter1;
JSONArray posts;
//ArrayList thats going to hold the search results
ArrayList<HashMap<String, String>> searchResults;
LayoutInflater inflater;
// All static variables
static final String URL = "http://abc.net/ads/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
private static final String DEBUGTAG = null;
protected static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
//clear the initial data set
searchResults.clear();
for (int i = 0; i < songsList.size(); i++) {
String playerName = songsList.get(i).get("title").toString();
if (textLength <= playerName.length()) {
//compare the String in EditText with Names in the ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
Toast.makeText(getApplicationContext(), playerName, 1).show();
Home.this.adapter.getFilter();
searchResults.add(songsList.get(i));
Log.d(TAG, "title");
}
}
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>
(Home.this,
R.layout.activity_home));
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
Home.this.adapter.getFilter();
}
});
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>(Home.this, R.layout.activity_home));
You are not giving any data set to populate the ListView.
Just like you initially populated the ListView with songsList data
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
use:
adapter = new LazyAdapter(this, searchResults);
list.setAdapter(adapter);
try this,
edittext code for search
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter1.getFilter().filter(s.toString());
}
........
add arraylist to listview to display
adapter1 = new MyAdapter(MainActivity.this, mProductArrayList);
lvProducts.setAdapter(adapter1);
Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
private ArrayList<Product> mOriginalValues; // Original Values
private ArrayList<Product> mDisplayedValues; // Values to be displayed
LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Product> mProductArrayList) {
this.mOriginalValues = mProductArrayList;
this.mDisplayedValues = mProductArrayList;
inflater = LayoutInflater.from(context);
}
..........
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.llContainer = (LinearLayout)convertView.findViewById(R.id.llContainer1);
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(mDisplayedValues.get(position).name);
holder.tvPrice.setText(mDisplayedValues.get(position).price+"");
holder.llContainer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, mDisplayedValues.get(position).price.toString() , Toast.LENGTH_SHORT).show();
}
});
return convertView;
}

populate city spinner after state spinner has been selected

This is my question:
How do I have two spinners "State" and "City" but the city will be empty until the user selects a state first.
I am building my spinners dynamically using json data and you will see in my code below that once the state spinner value is != 0 then I use the item value of the state spinner and do another database call for my cities.
My only error is showing when I create my new ArrayAdapter to hold to the city data. I hate to post all of my code for my activity but not sure where my issue is.
public class SearchActivity extends Activity{
private static final String TAG = "MyApp";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final Spinner zipspinner = (Spinner) findViewById(R.id.zipspinner);
final Spinner cityspinner = (Spinner) findViewById(R.id.cityspinner);
JSONArray jsonArray;
final JSONArray cityArray;
try {
//GET STATE VALUES FROM DATACALL (DATABASE)
String spinnerContentType = "state";
String spinnerURL = "getStoreState.php";
String spinner_data = DataCall.getJSON(spinnerURL,spinnerContentType);
jsonArray = new JSONArray(spinner_data);
final String[] array_spinner = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++)
{
String styleValue = jsonArray.getJSONArray(i).getString(0);
array_spinner[i] = styleValue;
}
//ADD STATE VALUES TO SPINNER
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
adapter.setDropDownViewResource(R.layout.state_spinner_layout);
zipspinner.setAdapter(adapter);
zipspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = zipspinner.getSelectedItemPosition();
//IF ITEM IN STATE IS SELECTED NOW GET CITIES FROM DATABALL
if(item != 0){
try {
String item_value = array_spinner[item];
String spinnerContentType = "city";
String spinnerURL = "getStoreCity.php?state=" + item_value;
String city_data = DataCall.getJSON(spinnerURL,spinnerContentType);
cityArray = new JSONArray(city_data);
final String[] city_spinner = new String[cityArray.length()];
for (int i=0; i<cityArray.length(); i++)
{
String styleValue = cityArray.getJSONArray(i).getString(0);
city_spinner[i] = styleValue;
}
//THIS IS WHERE MY ISSUE IS TRYING TO ADD THE CITIES TO THEIR SPNNER
ArrayAdapter<String> adapter2 =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,city_spinner);
adapter2.setDropDownViewResource(R.layout.city_spinner_layout);
cityspinner.setAdapter(adapter2);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = cityspinner.getSelectedItemPosition();
if(item != 0){
String item_value = array_spinner[item];
String nameContentType = "name";
String shopURL = "getStoreList.php?city=" + item_value;
String name_data = DataCall.getJSON(shopURL,nameContentType);
Bundle bundle = new Bundle();
bundle.putString("shopData", name_data);
Log.v(TAG,name_data);
/** Intent myIntent = new Intent(SearchActivity.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0); */
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Set all your Adapters and String arrays first and then just call adapter.notifyDatasetChanged() while you got the data for city. something like this:
String city_values[] = new String[]{"Please select a state."};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item, city_spinner);
adapter2.setDropDownViewResource(R.layout.city_spinner_layout);
cityspinner.setAdapter(adapter2);
for the zipspinner implement a OnItemSelectedListener.
zipspinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
String value = state_values[pos];
// now get your city list against value.
city_values = yourWayOfGettingData(value);
adapter2.notifyDatasetChanged();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});

Categories

Resources