populate city spinner after state spinner has been selected - java

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.
}
});

Related

not getting data from arraylist

I have arraylists. I want the data from that arraylist. I am not getting the data. instead when i use arraylist.get(i) i get the whole arraylist.
Here is my code
This the main activity where onlick of listview item i am getting the values and passing it to next activity using putStringArrayListExtra.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String varr = history.get(position).getLati().toString();
ArrayList<String>clicklat=new ArrayList<String>();
clicklat.add(varr);
String var2 = history.get(position).getLongi().toString();
ArrayList<String>clicklong=new ArrayList<String>();
clicklong.add(var2);
String var3 = history.get(position).getDatetime().toString();
ArrayList<String>dttime=new ArrayList<String>();
dttime.add(var3);
Intent i = new Intent(HistoryActivity.this, DetailsActivity.class);
i.putStringArrayListExtra("clicklat", clicklat);
i.putStringArrayListExtra("clicklong", clicklong);
i.putStringArrayListExtra("clickdatetime", dttime);
startActivity(i);
}
});
Here is DetailsActivity
public class DetailsActivity extends AppCompatActivity {
private Toolbar toolbar;
String latitudee;
String longitudee;
String dateetime;
ArrayList<String> newLat;
ArrayList<String> newLong;
ArrayList<String> newDateTime;
ArrayList<DetailsPojo> details;
DetailsPojo detailsPojo;
DetailsAdapter adapter;
ListView detList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("History Details");
Intent intent = getIntent();
details = new ArrayList<DetailsPojo>();
newLat = new ArrayList<>();
newLong = new ArrayList<>();
newDateTime = new ArrayList<>();
newLat = intent.getStringArrayListExtra("clicklat");
newLong = intent.getStringArrayListExtra("clicklong");
newDateTime = intent.getStringArrayListExtra("clickdatetime");
for (int i = 0; i < newLat.size(); i++) {
detailsPojo = new DetailsPojo();
latitudee = newLat.get(i);
longitudee = newLong.get(i);
dateetime = newDateTime.get(i);
Log.e("detais latitude", "" + latitudee);
Log.e("detailos longitudee", "" + longitudee);
Log.e("detailos datetimeee", "" + dateetime);
detailsPojo.setDetailsdatetime(dateetime);
detailsPojo.setDetailslat(latitudee);
detailsPojo.setDetailslong(longitudee);
}
details.add(detailsPojo);
detList = (ListView) findViewById(R.id.detailsList);
adapter = new DetailsAdapter(DetailsActivity.this, details);
detList.setAdapter(adapter);
}
and this is DetailsAdapter
public class DetailsAdapter extends BaseAdapter {
private Context activity;
TextView dt_datetime;
TextView dt_lat;
TextView dt_long;
ArrayList<DetailsPojo> list;
private ArrayList<DetailsPojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public DetailsAdapter(Context a, ArrayList<DetailsPojo> details) {
// TODO Auto-generated constructor stub
activity = a;
list = details;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<DetailsPojo>();
this.arraylist.addAll(list);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(convertView == null) {
v = inflater.inflate(R.layout.details_item, parent, false);
}
final DetailsPojo pojo = list.get(position);
dt_datetime = (TextView) v.findViewById(R.id.detailsdatetime);
dt_lat = (TextView) v.findViewById(R.id.detailslat);
dt_long = (TextView) v.findViewById(R.id.detailslong);
dt_datetime.setText(pojo.getDetailsdatetime());
dt_lat.setText(pojo.getDetailslat());
dt_long.setText(pojo.getDetailslong());
return v;
}
}
This is the arraylist
latitude﹕ [21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121774, 21.121774]
UPDATE:
this is getLati and getLongi
public List<String> getLati(){
return this.lat;
}
public List<String> getLongi(){
return this.longi;
}
public void setLati(List<String> lat){
this.lat = lat;
}
public void setLongi(List<String> longi){
this.longi = longi;
}
Is there anything wrong? Please help me.
Try this code:
protected void onCreate(Bundle savedInstanceState) {
...
for (int i = 0; i < newLat.size(); i++) {
DetailsPojo detailsPojo = new DetailsPojo(); //changes here
latitudee = newLat.get(i);
longitudee = newLong.get(i);
dateetime = newDateTime.get(i);
Log.e("detais latitude", "" + latitudee);
Log.e("detailos longitudee", "" + longitudee);
Log.e("detailos datetimeee", "" + dateetime);
detailsPojo.setDetailsdatetime(dateetime);
detailsPojo.setDetailslat(latitudee);
detailsPojo.setDetailslong(longitudee);
details.add(detailsPojo); // and here
}
detList = (ListView) findViewById(R.id.detailsList);
adapter = new DetailsAdapter(DetailsActivity.this, details);
detList.setAdapter(adapter);
}
I've declared detailsPojo object inside the loop instead of a global variable.
PS: Make sure newLong and newDateTime have the same size as newLat to avoid IndexOutOfBoundsException.
UPDATE:
Change your click listener to:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArrayList<String>clicklat= new ArrayList<String>(history.get(position).getLati());
ArrayList<String>clicklong= new ArrayList<String>(history.get(position).getLongi());
ArrayList<String>dttime= new ArrayList<String>(history.get(position).getDatetime());
Intent i = new Intent(HistoryActivity.this, DetailsActivity.class);
i.putStringArrayListExtra("clicklat", clicklat);
i.putStringArrayListExtra("clicklong", clicklong);
i.putStringArrayListExtra("clickdatetime", dttime);
startActivity(i);
}
Try this code in HereActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
...
for (int i = 0; i < newLat.size(); i++) {
DetailsPojo detailsPojo = new DetailsPojo();
latitudee = newLat.get(i);
longitudee = newLong.get(i);
dateetime = newDateTime.get(i);
Log.e("detais latitude", "" + latitudee);
Log.e("detailos longitudee", "" + longitudee);
Log.e("detailos datetimeee", "" + dateetime);
detailsPojo.setDetailsdatetime(dateetime);
detailsPojo.setDetailslat(latitudee);
detailsPojo.setDetailslong(longitudee);
details.add(detailsPojo); // move it to here
}
// details.add(detailsPojo); // remove it
detList = (ListView) findViewById(R.id.detailsList);
adapter = new DetailsAdapter(DetailsActivity.this, details);
detList.setAdapter(adapter);
}
....
Hope this help
I think the problem here is that you are creating your lists inside the onClick listener. This means that everytime the user clicks a new List is created and then the value added. So you will always end up with 1 size lists. And if you are trying to use get() on a 1 size list you are getting the only element a.k.a. the whole list. Just move the instructions like:
ArrayList<String>clicklat=new ArrayList<String>();
outside the listener and you should be ok.

java.lang.NullPointerException : on android.widget.EditText.addTextchangedlistener

I am working on android app and put filtration functionality on Listview. But I got below error:
java.lang.RuntimeException: Unable to start activity
componentInfo:java.lang.NullPointerException: Attempt to invoke
virtual method void
android.widget.EditText.addTextchangedListener(android.text.TextWatcher)
on a Null object Reference
Below is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopdetail);
aq=new AQuery(this);
value=5;
GPSTracker gps = new GPSTracker(Shopdetail.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
getdatalatlog(latitude,longitude);
}else{
gps.showSettingsAlert();
}
Intent openStartingPoint=getIntent();
String city=openStartingPoint.getStringExtra("spinnerText");
bindcity(city);
final EditText inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
//Shopdetail.this.adapter.getFilter().filter(cs);
//((SimpleAdapter)Shopdetail.this.adapter).getFilter().filter(cs);
// ((SimpleAdapter)getListAdapter()).getFilter().filter(cs);
//get the text in the EditText
EditText inputSearch = (EditText)findViewById(R.id.inputSearch);
String searchString=inputSearch.getText().toString();
int textLength=searchString.length();
searchResults.clear();
for(int i=0;i<mCommentList.size();i++)
{
String shopName=mCommentList.get(i).get(TAG_TITLE).toString();
if(textLength<=shopName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.trim().equalsIgnoreCase(shopName.trim().substring(0,textLength))){
searchResults.add(mCommentList.get(i));
getdata();}
}
}
adapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
private void getdata() {
// TODO Auto-generated method stub
String[] data = new String[]{TAG_TITLE,TAG_USERNAME ,TAG_CONTACT ,TAG_MESSAGE ,TAG_LATITUDE , TAG_LONGITUDE };
int[] to= new int[] {R.id.shop_name,R.id.address,R.id.contact,R.id.distance,R.id.latitude,R.id.longitude};
final SimpleAdapter adapter = new SimpleAdapter(this, mCommentList,R.layout.single_post, data,to);
ListView lv = ( ListView ) findViewById(android.R.id.list);
lv.setAdapter(adapter);
}
Below is my code to firstly bind data.
private void getdatalatlog(double latitude, double longitude) {
// TODO Auto-generated method stub
//value=5;
String url = "http://192.168.2.4/PHP/webservice/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'&value='"+value+"'";
aq.progress(R.id.progressBar1).ajax(url, JSONObject.class, this,"jsonCallback");
}
#SuppressWarnings("unchecked")
public void jsonCallback(String url, JSONObject json, AjaxStatus status) {
if (json != null) {
List<String> city = new ArrayList<String>();
mCommentList = new ArrayList<HashMap<String, Object>>();
Gson gson = new GsonBuilder().create();
try {
JSONArray jsonResponse = json.getJSONArray("posts");
city = gson.fromJson(jsonResponse.toString(),List.class);
for (int i = 0; i < jsonResponse.length(); i++) {
JSONObject c = jsonResponse.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
String lat = c.getString(TAG_LATITUDE);
String log = c.getString(TAG_LONGITUDE);
String cont = c.getString(TAG_CONTACT);
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_LATITUDE, lat);
map.put(TAG_LONGITUDE, log);
map.put(TAG_CONTACT, cont);
// adding HashList to ArrayList
mCommentList.add(map);
searchResults=new ArrayList<HashMap<String,Object>>(mCommentList);
//HashMap<String, String> map1 = new HashMap<String, String>();
//map1.put(TAG_TITLE, title);
//sortdata;
}
}
catch (JSONException e) {
Toast.makeText(aq.getContext(), "Error in parsing JSON", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(aq.getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
String[] data = new String[]{TAG_TITLE,TAG_USERNAME ,TAG_CONTACT ,TAG_MESSAGE ,TAG_LATITUDE , TAG_LONGITUDE };
int[] to= new int[] {R.id.shop_name,R.id.address,R.id.contact,R.id.distance,R.id.latitude,R.id.longitude};
final SimpleAdapter adapter = new SimpleAdapter(this, mCommentList,R.layout.single_post, data,to);
ListView lv = ( ListView ) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent();
Bundle b = new Bundle();
String name= ((TextView) view.findViewById(R.id.shop_name)).getText().toString()+" , "+((TextView) view.findViewById(R.id.contact)).getText().toString();
String lati= ((TextView) view.findViewById(R.id.latitude)).getText().toString();
String longi= ((TextView) view.findViewById(R.id.longitude)).getText().toString();
b.putString("shop",name);
b.putString("lati",lati);
b.putString("long",longi);
intent.setClass(Shopdetail.this, Mapview.class);
intent.putExtras(b);
startActivity(intent);
}
});
}
}
When user type letter on EditText the data is filtered and its bind in listview according to that. Its not working. Please guide me.
Thanks so much in advance.
You forget to initialized inputSearch
inputSearch=(EditText)findViewById(R.id.editTextId);
OR move
EditText inputSearch = (EditText)findViewById(R.id.inputSearch);
before
inputSearch.addTextChangedListener(new TextWatcher() {
Invoking method on Null object reference will always throw java.lang.NullPointerException.
In your case, logs clearly indicate "Attempt to invoke method addTextchangedListener(android.text.TextWatcher) on a Null object Reference".
In short - inputSearch is null and should be initialized before any method invocations.

How to populate my Spinner based on the value on my TextView?

I am new to Android programming and I'm working on a project that fetches data from MySQL DB.
Now, I have two java files. The first fetches employees and their id, it has Spinners that when clicked, it copies the value of the name and id of the employees to the TextViews and transfer the data to the next Activity through Intent.
While the second fetches employees' schedule based on the employee id. This second activity should populate Spinner based on the id of the employees that was passes from the first activity.
First Activity:
public class FirstActivity extends Activity {
JSONObject jObj;
JSONArray jArray;
ProgressDialog pd;
ArrayList < String > aestheticianList;
ArrayList < Items > items;
Button btnTransact;
String service_name, price;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_farmers_aesthetician);
new DownloadJSON().execute();
btnTransact = (Button) findViewById(R.id.btnTransact);
btnTransact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersAestheticianActivity.this,
cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersDateTimeActivity.class);
String service_name = ((TextView) findViewById(R.id.service_name)).getText().toString();
String price = ((TextView) findViewById(R.id.price)).getText().toString();
String full_name = ((TextView) findViewById(R.id.full_name)).getText().toString();
String aid = ((TextView) findViewById(R.id.aid)).getText().toString();
i.putExtra("service_name", service_name);
i.putExtra("price", price);
i.putExtra("full_name", full_name);
i.putExtra("aid", aid);
startActivityForResult(i, 100);
}
});
TextView txtService_name = (TextView) findViewById(R.id.service_name);
TextView txtPrice = (TextView) findViewById(R.id.price);
Intent i = getIntent();
service_name = i.getStringExtra("service_name");
price = i.getStringExtra("price");
txtService_name.setText(service_name);
txtPrice.setText(price);
}
private class DownloadJSON extends AsyncTask < Void, Void, Void > {
#Override
protected Void doInBackground(Void...params) {
// TODO Auto-generated method stub
items = new ArrayList < Items > ();
aestheticianList = new ArrayList < String > ();
try {
jObj = JSONParser.getJSONfromURL("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_aesthetician2.php");
try {
jArray = jObj.getJSONArray("aesthetician");
for (int i = 0; i < jArray.length(); i++) {
jObj = jArray.getJSONObject(i);
Items item = new Items();
item.setFull_name(jObj.optString("full_name"));
item.setAid(jObj.optString("aid"));
items.add(item);
aestheticianList.add(jObj.optString("full_name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner spin = (Spinner) findViewById(R.id.spin_aesthetician);
spin.setAdapter(new ArrayAdapter < String > (FarmersAestheticianActivity.this,
android.R.layout.simple_spinner_dropdown_item, aestheticianList));
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView <? > arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
TextView txt_full_name = (TextView) findViewById(R.id.full_name);
TextView txt_aid = (TextView) findViewById(R.id.aid);
txt_full_name.setText(items.get(position).getFull_name());
txt_aid.setText(items.get(position).getAid());
////////////////////////////////
////////////////////////////////
}
#Override
public void onNothingSelected(AdapterView <? > parent) {
// TODO Auto-generated method stub
}
});
}
}
}
Second Activity:
public class SecondActivity extends Activity {
JSONObject jObj;
JSONArray jArray;
ProgressDialog pd;
ArrayList < String > dateTimeList;
ArrayList < Items > items;
Button btnTransact;
String service_name, price, full_name, aid, tid;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_farmers_datetime);
new DownService().execute();
btnTransact = (Button) findViewById(R.id.btnTransact);
btnTransact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersDateTimeActivity.this,
cp000l3.flawlessfaceandbodyclinic.project.transact.FarmersConfirmationActivity.class);
String service_name = ((TextView) findViewById(R.id.service_name)).getText().toString();
String price = ((TextView) findViewById(R.id.price)).getText().toString();
String aid = ((TextView) findViewById(R.id.aid)).getText().toString();
String full_name = ((TextView) findViewById(R.id.full_name)).getText().toString();
String tid = ((TextView) findViewById(R.id.tid)).getText().toString();
String datetime = ((TextView) findViewById(R.id.datetime)).getText().toString();
i.putExtra("service_name", service_name);
i.putExtra("price", price);
i.putExtra("aid", aid);
i.putExtra("full_name", full_name);
i.putExtra("tid", tid);
i.putExtra("date_time", datetime);
startActivityForResult(i, 100);
}
});
TextView txtService_name = (TextView) findViewById(R.id.service_name);
TextView txtPrice = (TextView) findViewById(R.id.price);
TextView txtFull_name = (TextView) findViewById(R.id.full_name);
TextView txtAid = (TextView) findViewById(R.id.aid);
Intent i = getIntent();
service_name = i.getStringExtra("service_name");
price = i.getStringExtra("price");
full_name = i.getStringExtra("full_name");
aid = i.getStringExtra("aid");
txtService_name.setText(service_name);
txtPrice.setText(price);
txtFull_name.setText(full_name);
txtAid.setText(aid);
}
private class DownService extends AsyncTask < Void, Void, Void > {
#Override
protected Void doInBackground(Void...params) {
// TODO Auto-generated method stub
items = new ArrayList < Items > ();
dateTimeList = new ArrayList < String > ();
/////////////////////////
List < NameValuePair > param = new ArrayList < NameValuePair > ();
param.add(new BasicNameValuePair("aid", aid));
/////////////////////////
try {
String jObj = JSONParser.makeHttpRequest2("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_time2.php", "GET", param); //("http://192.168.1.9:8013/flawlessadmin/storescripts/transaction/final/get_time.php");
try {
JSONObject jsonObj = new JSONObject(jObj);
for (int i = 0; i < jArray.length(); i++) {
jsonObj = jArray.getJSONObject(i);
Items item = new Items();
item.setDateTime(jsonObj.optString("date_time"));
item.setTid(jsonObj.optString("tid"));
items.add(item);
dateTimeList.add(jsonObj.optString("date_time"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner spin = (Spinner) findViewById(R.id.spin_datetime);
spin.setAdapter(new ArrayAdapter < String > (FarmersDateTimeActivity.this,
android.R.layout.simple_spinner_dropdown_item, dateTimeList));
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView <? > arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
TextView txt_datetime = (TextView) findViewById(R.id.datetime);
TextView txt_tid = (TextView) findViewById(R.id.tid);
txt_datetime.setText(items.get(position).getDateTime());
txt_tid.setText(items.get(position).getTid());
////////////////////////////////
////////////////////////////////
}
#Override
public void onNothingSelected(AdapterView <? > parent) {
// TODO Auto-generated method stub
}
});
}
}
}
in second Activity:
Bundle extras = getIntent().getExtras();
int id = extras.getInt("Id"); // get the id passed from first activty

"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.

Update City Spinner with notifyDataSetChanged after state is selected

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.

Categories

Resources