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
Related
I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);
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.
My custom adapter for notification
public class SchoolTagAdapter extends BaseAdapter {
Context context;
SharedPreferences prefs;
LayoutInflater inflater;
Boolean toggle_status;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public SchoolTagAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener
{
private int mPosition;
OnItemClickListener(int position)
{
mPosition = position;
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
SchoolDetails schoolDetail = (SchoolDetails)context;
schoolDetail.onItemClick(mPosition);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView id;
TextView name;
final ToggleButton toogle;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.schooltag_list, parent, false);
// Get the position
resultp = data.get(position);
id = (TextView)itemView.findViewById(R.id.textView1);
name = (TextView)itemView.findViewById(R.id.tagname);
toogle = (ToggleButton)itemView.findViewById(R.id.toggleButton1);
name.setText(resultp.get(SchoolDetails.NAME));
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
toggle_status = preferences.getBoolean("NameOfThingToSave",true);
Log.d("TOGGLE_STATUS", toggle_status+"");
if(toggle_status==true)
{
toogle.setChecked(true);
}
else if(toggle_status==false)
{
toogle.setChecked(false);
}
toogle.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//TODO Auto-generated method stub
if (toogle.isChecked())
{
prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefEditor = prefs.edit();
prefEditor.putBoolean("NameOfThingToSave",true);
prefEditor.commit();
}
else if(!toogle.isChecked())
{
prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefEditor = prefs.edit();
prefEditor.putBoolean("NameOfThingToSave",false);
prefEditor.commit();
}
}
});
itemView.setOnClickListener(new OnItemClickListener(position));
return itemView;
}
}
This is my Activity
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.schoolzine.adapters.SchoolTagAdapter;
import com.example.schoolzine.asyncimages.ImageLoader;
import com.example.schoolzine.database.DatabaseHandler;
import com.example.schoolzine.models.SchoolTag;
import com.example.schoolzine.utils.JsonParsor;
import com.example.schoolzine.utils.WebserviceUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class SchoolDetails extends Activity {
public static String id;
public int t,parn,stud,stff;
TextView Name,City,State,Street,Tag;
Button back, next;
String schoolName,schoolStreet,schoolCity,schoolState,schoolImage,schoolId,schoolUrl,schoolid,
schoolPOBox,schoolPhone,schoolWebsite,schoolPrefix,schoolURL,schoolnotId,schoolnotifName;
int schoolnotifId;
public String TAG1,TAG2,TAG3,spinnerValue;
ImageView Image;
ImageLoader SchoolImageLoader = new ImageLoader(SchoolDetails.this);
JSONObject jobject, jobj;
public ProgressDialog p_dialog;
ArrayList<HashMap<String, String>> arraylist;
Spinner spin;
HashMap queryValues;
DatabaseHandler dbHandler;
SharedPreferences pref;
boolean toggle_status;
SharedPreferences preferences;
public static String ID = "id";
public static String NAME = "name";
public static String DESCRIPTION = "description";
ListView listview;
SchoolTagAdapter sadapter;
ArrayList<SchoolTag> schoolTAG;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schooldetails);
dbHandler = new DatabaseHandler(SchoolDetails.this);
if(android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
getActionBar().hide();
Image = (ImageView)findViewById(R.id.schoolimage);
Name = (TextView)findViewById(R.id.name);
Street = (TextView)findViewById(R.id.street);
City = (TextView)findViewById(R.id.city);
State = (TextView)findViewById(R.id.state);
Tag = (TextView)findViewById(R.id.tagname);
listview = (ListView)findViewById(R.id.listView1);
spin = (Spinner)findViewById(R.id.spinner1);
back = (Button)findViewById(R.id.back);
next = (Button)findViewById(R.id.next);
schoolTAG = new ArrayList<SchoolTag>();
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
toggle_status = preferences.getBoolean("NameOfThingToSave", false);
if(WebserviceUtil.isConnectingToInternet(SchoolDetails.this)) {
new SchoolDetailTask().execute(WebserviceUtil.WEBSERVICE_URL+"school/"+id+".json");
}
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
if(arg2 == 0) {
// schoolTAG.clear();
if(WebserviceUtil.isConnectingToInternet(SchoolDetails.this)) {
new SchoolNotifTag1Task().execute();
}
// schoolTAG.clear();
// sadapter = new SchoolTagAdapter(SchoolDetails.this, R.layout.schooltag_list, schoolTAG);
// listview.setAdapter(sadapter);
}
if(arg2 == 1) {
// schoolTAG.clear();
if(WebserviceUtil.isConnectingToInternet(SchoolDetails.this)) {
new SchoolNotifTag2Task().execute();
}
// schoolTAG.clear();
// sadapter = new SchoolTagAdapter(SchoolDetails.this, R.layout.schooltag_list, schoolTAG); ;
// listview.setAdapter(sadapter);
}
if(arg2 == 2) {
// schoolTAG.clear();
if(WebserviceUtil.isConnectingToInternet(SchoolDetails.this)) {
new SchoolNotifTag3Task().execute();
}
// schoolTAG.clear();
// sadapter = new SchoolTagAdapter(SchoolDetails.this, R.layout.schooltag_list, schoolTAG); ;
// listview.setAdapter(sadapter);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inten = new Intent(SchoolDetails.this, StateSchoolList.class);
startActivity(inten);
finish();
}
});
if(dbHandler.doesIdExist(id)) {
next.setVisibility(View.INVISIBLE);
}
else {
next.setOnClickListener(new OnClickListener() {
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
queryValues = new HashMap();
queryValues.put("sId", schoolid);
queryValues.put("sName", schoolName);
queryValues.put("sStreet", schoolStreet);
queryValues.put("sState", schoolState);
queryValues.put("sCity", schoolCity);
queryValues.put("sPOBox", schoolPOBox);
queryValues.put("sPhone", schoolPhone);
queryValues.put("sWebsite", schoolWebsite);
queryValues.put("sImage", schoolImage);
queryValues.put("sURL", schoolURL);
queryValues.put("sPrefix", schoolPrefix);
dbHandler.insertSchoolDetails(queryValues);
Intent intent = new Intent(SchoolDetails.this, Registration.class);
startActivity(intent);
}
});
}
}
private class SchoolDetailTask extends AsyncTask<String, String, String>
{
public ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(SchoolDetails.this, "Loading Data", "Please Wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#SuppressWarnings({ "rawtypes" })
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(WebserviceUtil.WEBSERVICE_URL+"school/"+id+".json");
queryValues = new HashMap();
try {
JSONObject jobj = jobject.getJSONObject("school");
schoolid = jobj.getString("id");
schoolName = jobj.getString("name");
schoolStreet = jobj.getString("physical_street");
schoolCity = jobj.getString("physical_city");
schoolState = jobj.getString("physical_state");
schoolPOBox = jobj.getString("physical_postcode");
schoolPhone = jobj.getString("phone");
schoolWebsite = jobj.getString("website");
schoolPrefix = jobj.getString("prefix");
schoolImage = jobj.getString("logo");
schoolURL = jobj.getString("url");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "sucess";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if(p_dialog != null) {
p_dialog.dismiss();
}
// sadapter.notifyDataSetChanged();
super.onPostExecute(result);
if(result.compareTo("sucess") == 0) {
Name.setText(schoolName);
Street.setText(schoolStreet);
City.setText(schoolCity);
State.setText(schoolState);
SchoolImageLoader.DisplayImage(schoolImage, Image);
}
}
}
private class SchoolNotifTag1Task extends AsyncTask<Void, Void, Void> {
public ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(SchoolDetails.this, "Loading Data", "Please Wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
arraylist = new ArrayList<HashMap<String, String>>();
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(WebserviceUtil.SCHOOL_NOTIF_TAG1);
try {
JSONArray jarray = jobject.getJSONArray("groups");
System.out.println("TAG1_JARRAY = "+jarray);
for (int i=0; i<jarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jarray.getJSONObject(i);
map.put("id", jobj.getString("id"));
map.put("name", jobj.getString("name"));
map.put("description", jobj.getString("description"));
arraylist.add(map);
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
p_dialog.dismiss();
listview = (ListView)findViewById(R.id.listView1);
sadapter = new SchoolTagAdapter(SchoolDetails.this, arraylist);
listview.setAdapter(sadapter);
}
}
private class SchoolNotifTag2Task extends AsyncTask<Void, Void, Void> {
public ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(SchoolDetails.this, "Loading Data", "Please Wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
arraylist = new ArrayList<HashMap<String, String>>();
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(WebserviceUtil.SCHOOL_NOTIF_TAG2);
try {
JSONArray jarray = jobject.getJSONArray("groups");
System.out.println("TAG2_JARRAY = "+jarray);
for (int i=0; i<jarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jarray.getJSONObject(i);
map.put("id", jobj.getString("id"));
map.put("name", jobj.getString("name"));
map.put("description", jobj.getString("description"));
arraylist.add(map);
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
p_dialog.dismiss();
listview = (ListView)findViewById(R.id.listView1);
sadapter = new SchoolTagAdapter(SchoolDetails.this, arraylist);
listview.setAdapter(sadapter);
}
}
private class SchoolNotifTag3Task extends AsyncTask<Void, Void, Void> {
public ProgressDialog p_dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p_dialog = ProgressDialog.show(SchoolDetails.this, "Loading Data", "Please Wait...", true);
p_dialog.setCancelable(true);
p_dialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
arraylist = new ArrayList<HashMap<String, String>>();
JsonParsor json = new JsonParsor();
JSONObject jobject = json.getJSONFromUrl(WebserviceUtil.SCHOOL_NOTIF_TAG3);
try {
JSONArray jarray = jobject.getJSONArray("groups");
System.out.println("TAG3_JARRAY = "+jarray);
for (int i=0; i<jarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jobj = jarray.getJSONObject(i);
map.put("id", jobj.getString("id"));
map.put("name", jobj.getString("name"));
map.put("description", jobj.getString("description"));
arraylist.add(map);
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
p_dialog.dismiss();
listview = (ListView)findViewById(R.id.listView1);
sadapter = new SchoolTagAdapter(SchoolDetails.this, arraylist);
listview.setAdapter(sadapter);
}
}
public static void values(String ID) {
// TODO Auto-generated method stub
id = ID;
}
public void onItemClick(int mPosition) {
// TODO Auto-generated method stub
toggle_status = preferences.getBoolean("NameOfThingToSave", true);
if (toggle_status == true) {
// Toast.makeText(SchoolDetails.this, "Toogle "+toggle_status+" at position "+mPosition,
// Toast.LENGTH_SHORT).show();
// player.start();
// Log.d("MUSIC pLAYER", "STARTED");
}
else if (toggle_status == false) {
// Toast.makeText(SchoolDetails.this, "Toogle "+toggle_status+" at position "+mPosition,
// Toast.LENGTH_SHORT).show();
// player.stop();
// Log.d("MUSIC pLAYER", "STOPPED");
}
}
}
I tried to parse JSON values into a custom ListView.
My custom ListView contains a TextView and a toggle button. It's a notification activity. I turn notifications on and off by using a toggle button in a custom ListView.
The JSON values parsed fine. I limited my ListView height to 150dp.
My problem is that, suppose if my ListView contains 20 values parsed. When I put on first list item and when I scrolled down, the last few items also automatically turned on. I think it may because of recreating ListView, but I don’t know how to solve it.
What I want is to save state of each toggle button in ListView I turned on/off.
Anybody have any idea?
if (convertView == null) {
//inflating views
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
In my program i am showing multilevel Listview, but whenever i am calling another Activity then Fragment Tabs are not appearing.
I am using this great tutorial: http://www.androidbegin.com/tutorial/android-actionbarsherlock-viewpager-tabs-tutorial/
See below Images, 1st Level ListView:
2nd Level ListView:
ListCategoryFragment.xml:-
public class ListCategoryFragment extends SherlockFragment implements OnItemClickListener {
ListView lview3;
ListCategoryAdapter adapter;
private ArrayList<Object> itemList;
private ItemBean bean;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragment_category_tab, container, false);
prepareArrayList();
lview3 = (ListView) view.findViewById(R.id.listView1);
adapter = new ListCategoryAdapter(getActivity(), itemList);
lview3.setAdapter(adapter);
lview3.setOnItemClickListener(this);
return view;
}
private static final int categoryFirst = 0;
private static final int categorySecond = 1;
private static final int categoryThird = 2;
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// Set up different intents based on the item clicked:
switch (position)
{
case categoryFirst:
Intent intent1 = new Intent(getActivity(), ListItemActivity.class);
intent1.putExtra("category", "Category - 1");
startActivity(intent1);
break;
case categorySecond:
Intent intent2 = new Intent(getActivity(), ListItemActivity.class);
intent2.putExtra("category", "Category - 2");
startActivity(intent2);
break;
case categoryThird:
Intent intent3 = new Intent(getActivity(), ListItemActivity.class);
intent3.putExtra("category", "Category - 3");
startActivity(intent3);
break;
default:
break;
}
}
public void prepareArrayList()
{
itemList = new ArrayList<Object>();
AddObjectToList("Category - 1");
AddObjectToList("Category - 2");
AddObjectToList("Category - 3");
}
// Add one item into the Array List
public void AddObjectToList(String title)
{
bean = new ItemBean();
bean.setTitle(title);
itemList.add(bean);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
}
ListItemActivity.java:-
public class ListItemActivity extends SherlockFragmentActivity {
static String URL = "http://www.site.url/tone.json";
static String KEY_CATEGORY = "item";
static final String KEY_TITLE = "title";
ListView list;
ListItemAdapter adapter;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_item_list);
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.listView1);
adapter = new ListItemAdapter(this, itemsList);
list.setAdapter(adapter);
Bundle bdl = getIntent().getExtras();
KEY_CATEGORY = bdl.getString("category");
if (isNetworkAvailable()) {
new MyAsyncTask().execute();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(ListItemActivity.this).create();
alertDialog.setMessage("The Internet connection appears to be offline.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
intent.putExtra(Intent.EXTRA_TEXT, "TEXT");
startActivity(Intent.createChooser(intent, "Share via"));
return intent;
}
/** The event listener for the Up navigation selection */
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch(item.getItemId())
{
case android.R.id.home:
finish();
break;
case R.id.menu_item_share:
getDefaultShareIntent();
break;
}
return true;
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null);
}
class MyAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
private ProgressDialog progressDialog = new ProgressDialog(
ListItemActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading, Please wait.....");
progressDialog.show();
}
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet(URL);
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Convert this response into a readable string
String jsonString = null;
try {
jsonString = StreamUtils.convertToString(response.getEntity()
.getContent());
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create a JSON object that we can use from the String
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
itemsList.add(map);
}
return itemsList;
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list = (ListView) findViewById(R.id.listView1);
adapter = new ListItemAdapter(ListItemActivity.this, itemsList);
list.setAdapter(adapter);
TextView lblTitle = (TextView) findViewById(R.id.text);
lblTitle.setText(KEY_CATEGORY);
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = itemsList.get(position);
Intent in = new Intent(ListItemActivity.this, ListItemDetailActivity.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
startActivity(in);
}
});
}
}
}
This is the normal behavior because you are moving from the Fragment Activity to a normal Activity. But only your first activity has the tabs.
The correct way of doing this is to remove the intents and the new activities. Instead it should be replaced with fragments itself.
For example, in the list item click, stop calling the Intent to the new fragment activity, and replace it calling a fragment itself.
There will be only one Activity and that will be the one which is holding the tabs and all others should be fragments. You just need to replace the fragments from within the same activity.
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.
}
});