I am fetching the values from Database using JSON and inserting them into spinner. This process is running successfully.
But I am receiving a Spinner hint two times, when I click on spinner; how can I remove the first default value from spinner...
This is snapshot :- hope you understand my problem :
This is my code:-
private class GetCategories extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES,
ServiceHandler.GET);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
categoriesList.clear();
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(
catObj.getString("bus_type_id"),
catObj.getString("bus_type"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinner();
}
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
lables.add("Choose Type");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getbus_type());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
typeSpinner.setAdapter(spinnerAdapter);
typeSpinner.setOnItemSelectedListener(typeSelectedListener);
}
private OnItemSelectedListener typeSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (typeSpinner.getSelectedItem().toString() == "Choose Type") {
str = "";
typeSpinnercity.getSelectedView();
typeSpinnercity.setEnabled(false);
} else {
ok.setEnabled(true);
str = typeSpinner.getSelectedItem().toString();
typeSpinnercity.getSelectedView();
typeSpinnercity.setEnabled(true);
if (Utils.checkInternet(CutomerOfferActivity.this)) {
new GetCategoriesCity().execute();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
Use the ArrayAdapter and Override the method - getDropDownView..
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View v = null;
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
v = super.getDropDownView(position, null, parent);
}
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
Use the above mentioned code and remove the default value in the dropdown.
Related
I want EditText become AutoComplete when user start typing in the EditText field. I have create this code
public class PegawaiFragment extends Fragment {
public static PegawaiFragment newInstance() {
PegawaiFragment fragment = new PegawaiFragment();
return fragment;
}
String namapegawai;
AutoCompleteTextView textAutoComplete;
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://192.168.43.241/Android/MyKoperasi/PegawaiDashboard.php";
List<String> IdList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pegawai, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
namapegawai = prefs.getString(MainActivity.UserName,MainActivity.UserName);
TextView NamaPegawai = v.findViewById(R.id.TextViewNamaPegawai);
NamaPegawai.setText(namapegawai);
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
StudentListView = v.findViewById(R.id.listview2);
progressBar = v.findViewById(R.id.progressBar1);
new GetHttpResponse(getActivity()).execute();
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
//Intent intentSemuaMemberLihat = new Intent(getActivity(),SemuaMemberLihat.class);
// Sending ListView clicked value using intent.
//intentSemuaMemberLihat.putExtra("ListViewValue", IdList.get(position).toString());
//startActivity(intentSemuaMemberLihat);
}
});
return v;
}
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}
}
This code shows perfect, but when I start typing in EditText which in autoCompleteTextView1, no suggestion name come out. I think this is in here
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1);
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
But why the EditText doesn't show the suggestions? instead, my ListView works perfect there.
Here is my XML code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.network.poeja.mykoperasi.PegawaiFragment">
<TextView
android:id="#+id/TextViewNamaPegawai"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<AutoCompleteTextView
android:layout_weight="1"
android:id="#+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Text Auto Complete"
android:layout_below="#+id/TextViewNamaPegawai">
<requestFocus />
</AutoCompleteTextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:layout_below="#+id/autoCompleteTextView1">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/listview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_below="#+id/logos"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dip"/>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
</RelativeLayout>
</FrameLayout>
===============ADAPTER CLASS
public class ListAdapterClass extends BaseAdapter {
Context context;
List<Member> valueList;
public ListAdapterClass(List<Member> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listview_item, null);
viewItem.TextViewNama = convertView.findViewById(R.id.textViewNama);
viewItem.TextViewNrp = convertView.findViewById(R.id.textViewNrp);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.TextViewNama.setText(valueList.get(position).nama);
viewItem.TextViewNrp.setText(valueList.get(position).nrp);
return convertView;
}
}
class ViewItem
{
TextView TextViewNama, TextViewNrp;
}
You need to provide Array containing data on ArrayAdapter. Its the source of data where adapter will search. Here is an example how to use ArrayAdapter and AutoCompleteTextView -
public class MainActivity extends Activity {
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, data);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
}
Based on your code of AutoCompleteTextView. I made a solution.
String[] data = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};
GetHttpResponse getHttpResponse = new GetHttpResponse(getActivity());
getHttpResponse.execute();
textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
List<Member> studentList = getHttpResponse.getStudentList();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, studentList.toArray(new String[studentList.size()]));
textAutoComplete.setAdapter(adapter);
textAutoComplete.setThreshold(1);
Add a method to get studentList from GetHttpResponse class -
// JSON parse class started from here.
class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<Member> studentList;
public GetHttpResponse(Context context)
{
this.context = context;
}
public ArrayList<Member> getStudentList(){
return this.studentList;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
Member member;
studentList = new ArrayList<Member>();
for(int i=0; i<jsonArray.length(); i++)
{
member = new Member();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
member.nama = jsonObject.getString("nama").toString();
//member.nrp = jsonObject.getString("nrp").toString();
studentList.add(member);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
if(studentList != null) {
ListAdapterClass adapter = new ListAdapterClass(studentList, context);
StudentListView.setAdapter(adapter);
}else
{
Toast.makeText(context, "Tidak ada data ditampilkan", Toast.LENGTH_SHORT).show();
}
}
}
now i am using autocompleteTextview for showing suggestion , i get the data from webservice and and i set the adapter.
i dont get an error but when i click the Textview it wont show anything.and then I check the list and its contains the data.
am i doing a mistake here ?
here is my code
<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/acCustomer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etCustomerOther"
android:layout_marginBottom="10dp"
android:layout_alignLeft="#+id/spCustomer"/>
--class--
private static List<String> customerList;
private class LoadCustomer extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setVisibility(View.VISIBLE);
pBar.setIndeterminate(false);
pBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
try {
RESTClient client = new RESTClient(URLService+"get?method=getallcustomerlist&value=");
client.Execute(RESTClient.RequestMethod.GET);
responseCustomer = client.getResponse();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try{
responseCustomer = responseCustomer.replace("\\\"","\"");
responseCustomer = responseCustomer.substring(1, responseCustomer.length() - 1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(responseCustomer);
String Status = jsonObject.get("Status").toString();
if (Status == "true"){
// JSONArray structure = (JSONArray) jsonObject.get("DataList");
String dataku = jsonObject.get("DataList").toString();
try {
dataku = CRYYPT.decrypt(Enc_Pass, dataku);
}catch (GeneralSecurityException e){
//handle error - could be due to incorrect password or tampered encryptedMsg
}
JSONParser parser = new JSONParser();
JSONArray structure = (JSONArray) parser.parse(dataku);
customerList = new ArrayList<String>();
customerList.add("--Choose--");
for (int i = 0; i < structure.size(); i++) {
JSONObject customerlist = (JSONObject) structure.get(i);
customerList.add(customerlist.get("CustomerName").toString());
}
customerList.add("Other");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(WorkflowActivity.this, android.R.layout.simple_list_item_1, customerList);
acCustomer.setAdapter(adapter);
}else {
}
}
catch(Exception e)
{
e.printStackTrace();
}
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setClickable(true);
pBar.setVisibility(View.GONE);
}
}
--List Customer Item--
public class ListCustomerItem {
public String CustName;
/*public String CustLocation;
public String CustID;*/
}
--List Customer Adapter--
public class ListCustomerAdapter extends ArrayAdapter<ListCustomerItem> {
public ListCustomerAdapter(Context context, List<ListCustomerItem> items)
{
super(context, R.layout.style_fragment_list_customer, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.style_fragment_list_customer, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.tvCustName = (TextView) convertView.findViewById(R.id.tvCustName);
// viewHolder.tvCustLocation = (TextView) convertView.findViewById(R.id.tvCustLocation);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListCustomerItem item = getItem(position);
viewHolder.tvCustName.setText(item.CustName);
// viewHolder.tvCustLocation.setText(item.CustLocation);
return convertView;
}
private static class ViewHolder {
TextView tvCustName;
TextView tvCustLocation;
}
}
Have you tried using android:completionThreshold="1" inside AutoCompleteTextView?
or called mAutoCompleteTextView.setThreshold(1) to AutoCompleteTextView reference?
mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
Set your AutoCompleteTextView with Custom Adapter
mAutoCompleteTextView.setSelection(0);
mCustomAutoFilterAdapter = new CustomAutoFilterAdapter(this,R.layout.spinner_row, yourList);
mAutoCompleteTextView.setThreshold(1);
mAutoCompleteTextView.setAdapter(mCustomAutoFilterAdapter);
In your Custom Adapter Class include
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
return v;
}
#Override
public Filter getFilter() {
return nameFilter;
}
Filter nameFilter = new Filter() {
#Override
public String convertResultToString(Object resultValue) {
String str = "get your values from resultValue";
return str;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null) {
suggestions.clear();
"DO your Activities"
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
"Do your Activities here"
}
};
_doctorSpinner = (Spinner) findViewById(R.id.input_doctor);
final ArrayList<String> docList = new ArrayList<String>();
DataUtil.getDoctorList(this.getApplicationContext(), new ServerCallBack() {
#Override
public void onSuccess(JSONObject result) {
}
#Override
public void onSuccess(String result) {
}
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
} catch (JSONException e) {
}
}
});
final ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, docList);
docAdapter.notifyDataSetChanged();
docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
_doctorSpinner.setAdapter(docAdapter);
_doctorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
In the above code i am getting a list of strings from server and populating in the spinner. When the activity is loaded i am unable to see the first item in the list("Select a doctor"). But when i click on spinner, i could see the items and select. Again then selected item is not visible as selected. Could anybody help me?
Thanks in advance.
_doctorSpinner = (Spinner) findViewById(R.id.input_doctor);
final ArrayList<String> docList = new ArrayList<String>();
DataUtil.getDoctorList(this.getApplicationContext(), new ServerCallBack() {
#Override
public void onSuccess(JSONObject result) {
}
#Override
public void onSuccess(String result) {
}
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
final ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, docList);
docAdapter.notifyDataSetChanged();
docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
_doctorSpinner.setAdapter(docAdapter);
_doctorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (JSONException e) {
}
}
});
webservice call work in background thread so ypou get list size zero when u set adapter so inialize and setadapter when call finish
Call notifyDataSetChanged(); after your data is added to the list.
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
if (null != docAdapter)
docAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
EDIT :
My bad I read the question incorrectly.
If you cannot see the text inside your spinner try this:
ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, docList);
And I don't believe you need to use docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
This ListView class where i bring different element from my server with help of php and JSON calls to my listview. The problem is i would like to send the ID of element to another view when i click of specific element on listview. and in another View i would like to publish the detail information about the element that i clicked. Any wan have idea about that?
public class Forestillinger extends AppCompatActivity {
ListView dagensaktivitet;
TextView txt;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
JSONParser jsonParser = new JSONParser();
JSONObject hc = null;
JSONArray fstilling;
public String hk = "";
int success;
String msg;
final Context c = this;
StableArrayAdapter adb;
private static final String url_Forestillinger = "http://barnestasjonen.no/test/db_get_forestillinger.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forestillinger);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dagensaktivitet = (ListView) findViewById(R.id.forestillinglist);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems) {
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView txt = (TextView) view.findViewById(android.R.id.text1);
txt.setTextColor(Color.WHITE);
return view;
}
};
dagensaktivitet.setAdapter(adapter);
Log.d("i oncreate", adapter.toString());
//if(!fromLocalDB())
try {
new getShows().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//JSONObject tickets = task.getJSon();
adapter.notifyDataSetChanged();
dagensaktivitet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), Forestilling.class);
i.putExtra("selectedItem", listItems.get(position));
startActivity(i);
}
});
}
public void fromExtDB() throws JSONException {
fstilling = hc.getJSONArray("forestillinger");
for (int i = 0; i < fstilling.length(); i++) {
listItems.add(fstilling.getJSONObject(i).getString("tittel")+fstilling.getJSONObject(i).getString("id"));
}
}
#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_forestillinger, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void forestillingResult(){
new AlertDialog.Builder(Forestillinger.this)
.setTitle("OBS!!!")
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
hk = "";
finish();
}
})
.show();
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
List<Integer> trialId;
public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects, List<Integer> objectId) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); i++)
mIdMap.put(objects.get(i), i);
trialId = objectId;
}
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
public int getActualId(int position)
{
return trialId.get(position);
}
}
class getShows extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
Log.d("TEST", "jeg er her");
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("id", "adam#gmail.com"));
//params.add(new BasicNameValuePair("type", "android"));
JSONObject json = jsonParser.makeHttpRequest(url_Forestillinger, "POST", params);
try {
if (json != null) {
success = Integer.parseInt(json.getString("success"));
msg = json.toString();
System.out.println("Vi er her:" + msg + " " + success);
}
if (success == 1) {
hc = json;
System.out.println("jojo"+json.toString());
}
else
{
msg=json.getString("message");
System.out.println(msg);
msg= Html.fromHtml(msg).toString();
hk = msg;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//run code
try {
Log.d("TAG23", "vi er in onpostExecute");
if(success == 1) {
fromExtDB();
}else{
forestillingResult();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and here is the second view.
public class Forestilling extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forestilling);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*Bundle extras = getIntent().getExtras();
Log.d("TAG:", "" + extras.getInt("TryThis"));*/
Bundle extras = getIntent().getExtras();
String s = extras.getString("selectedItem");
Log.d("TAG:", "" + s);
TextView tit = (TextView)findViewById(R.id.tittel);
TextView dato = (TextView)findViewById(R.id.dato);
}
#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_forestilling, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm not allowed to flag at this moment, but this might be a duplicate of how can i use the number from textfield of each row in listview and make a call on this number?
Anyway, my answer given there might solve your problem:
Here is what I do:
private class MyAdapter extends BaseAdapter {
private ListView listView;
...
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
this.listView = (ListView) viewGroup;
and then in each View.OnClickListener I can get the position of the clicked item by
#Override
public void onClick(View view) {
...
MyAdapter.this.listView.getPositionForView((View) view.getParent()));
I am putting my data in spinners.Data is coming from URL.How to make spinner so that when syllabus is ICSE is chosen it reflect only those grade, subject which has ICSE?
My JSON
{
"results":[
{
"syllabus":"CBSE",
"grade":"5",
"subject":"Kannada",
"topic":"Grammar Level 1",
"id":28
},
{
"syllabus":"CBSE",
"grade":"5",
"subject":"Science",
"topic":"The Natural Calamities",
"id":16
},
{
"syllabus":"CBSE",
"grade":"6",
"subject":"Science",
"topic":"Movement in Animals",
"id":116
},
{
"syllabus":"CBSE",
"grade":"6",
"subject":"Social Studies",
"topic":"Contact With Distant Lands",
"id":59
},
{
"syllabus":"CBSE",
"grade":"6",
"subject":"Social Studies",
"topic":"Gupta Empire",
"id":34
},
"id":148
},
{
"syllabus":"ICSE",
"grade":"6",
"subject":"Computers",
"topic":"Introduction to QBASIC Programming",
"id":44
},
{
"syllabus":"ICSE",
"grade":"6",
"subject":"Social Studies - History",
"topic":"The Vedic Age",
"id":42
},
{
"syllabus":"Entrance Exam - Karnataka CET",
"grade":"12",
"subject":"Mathematics",
"topic":"Previous Year Question Papers",
"id":121
},
{
"syllabus":"Entrance Exam - Karnataka CET",
"grade":"12",
"subject":"Science - Biology",
"topic":"Previous Year Question Papers",
"id":117
},
{
"syllabus":"Entrance Exam - Karnataka CET",
"grade":"12",
"subject":"Science - Chemistry",
"topic":"Previous Year Question Papers",
"id":110
},
{
"syllabus":"Entrance Exam - Karnataka CET",
"grade":"12",
"subject":"Science - Physics",
"topic":"Previous Year Question Papers",
"id":104
}
}
Any help will be great for me
MainActivity Class
public class MainActivity extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
JSONArray jsonarray2;
JSONObject jsonobject2;
ArrayList<String> worldlist;
ArrayList<String> worldlist2;
ArrayList<String> worldlist3;
ArrayList<Results> world;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.topic);
// Download JSON file AsyncTask
new DownloadJSON().execute();
}
// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
world = new ArrayList<Results>();
// Create an array to populate the spinner
worldlist = new ArrayList<String>();
worldlist2 = new ArrayList<String>();
worldlist3 = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL("https://www.wonderslate.com/funlearn/topicsMap");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Results worldpop = new Results();
worldpop.setSyllabus(jsonobject.optString("syllabus"));
worldpop.setGrade(jsonobject.optString("grade"));
worldpop.setSubject(jsonobject.optString("subject"));
worldpop.setId(jsonobject.optString("id"));
world.add(worldpop);
worldlist.add(jsonobject.optString("syllabus"));
worldlist2.add(jsonobject.optString("grade"));
worldlist3.add(jsonobject.optString("subject"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
final Spinner mySpinner = (Spinner) findViewById(R.id.syllabus);
final Spinner mySpinner2 = (Spinner) findViewById(R.id.grade);
Spinner mySpinner3 = (Spinner) findViewById(R.id.subject);
// Spinner adapter
final LinkedHashSet<String>[] listToSet = new LinkedHashSet[]{new LinkedHashSet<String>(worldlist)};
//Creating Arraylist without duplicate values
final List<String> worldlistnew = new ArrayList<String>(listToSet[0]);
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlistnew));
//Creating ArrayList without duplicate values
listToSet[0] = new LinkedHashSet<String>(worldlist3);
//Creating Arraylist without duplicate values
final List<String> worldlistnew3 = new ArrayList<String>(listToSet[0]);
mySpinner3
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlistnew3));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
if (mySpinner.getSelectedItem().toString().equals("CBSE")) {
// if (mySpinner.getId() == R.id.syllabus)
listToSet[0] = new LinkedHashSet<String>(worldlist2);
final List<String> worldlistnew2 = new ArrayList<String>(listToSet[0]);
mySpinner2
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlistnew2));
textView.setText("21");
} else if (mySpinner.getSelectedItem().toString().equals("ICSE")) {
textView.setText("31");
} else if (mySpinner.getSelectedItem().toString().equals("Entrance Exam - Karnataka CET"))
{
textView.setText("41");
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private void resetGrade(String grade) {
}
}
Remove these lines first from doInBackground method. No need to create separate arraylist here..
worldlist.add(jsonobject.optString("syllabus"));
worldlist2.add(jsonobject.optString("grade"));
worldlist3.add(jsonobject.optString("subject"));
Declare these arraylist globally...
ArrayList<String> syllabuslist;
ArrayList<String> gradlist;
ArrayList<String> subjectlist;
and initialize these spinner in OnCreate method before calling Async task(DownloadJSON())
Spinner mySpinner = (Spinner) findViewById(R.id.syllabus);
Spinner mySpinner2 = (Spinner) findViewById(R.id.grade);
Spinner mySpinner3 = (Spinner) findViewById(R.id.subject);
Now set spinner in onPostExecute() method....remove extra code you have written in onPostExcute...just copy my code
#Override
protected void onPostExecute(Void args) {
// Spinner adapter
syllabuslist = new ArrayList<String>();
for (Results bean : world) {
syllabuslist.add(bean.getSyllabus());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, syllabuslist);
adapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String syllabus_name = mySpinner.getItemAtPosition(arg2).toString();
gradlist = new ArrayList<String>();
for (int i = 0; i < world.size(); i++) {
if (world.get(i).getSyllabus().equals(syllabus_name)) {
gradlist.add(world.get(i).getGrade());
}
}
setGradeSpinner();//its a method to create grade spinner
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void setGradeSpinner(){
if(gradlist!=null && gradlist.size()>0)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, gradlist);
adapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner2.setAdapter(adapter);
mySpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String grade_name = mySpinner2.getItemAtPosition(arg2).toString();
subjectlist = new ArrayList<String>();
for (int i = 0; i < world.size(); i++) {
if (world.get(i).getGrade().equals(grade_name)) {
subjectlist.add(world.get(i).getSubject());
}
}
// setSubjectSpinner();//its a method to create subject spinner like as I do for garde spinner
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Hope this will help you...
In your onitemclick listener of your first spinner, depending on the item selected change the list data of your second spinner and call.
spinner2Adapter.notifyDatasetChanged();
You dont have to create a new adapter and list every time you change selection in spinner1.
#Shwetabh Singh I cannt understand your question.But i have done one city select example. You can refere it. Here In first Spinner i list city name. and based on the city select second spinner area is refcted
{
"City": [
{
"name": "Ahmedabad",
"City_area1" : "Ghatlodia",
"City_area2" : "Chandlodia",
"City_area3" : "Other"
},
{
"name": "Hydarabad",
"City_area1" : "IIT",
"City_area2" : "Faridabad",
"City_area3" : "Other"
},
{
"name": "Noida",
"City_area1" : "Sector-50",
"City_area2" : "Sector-41",
"City_area3" : "Other"
}
]
}
MainActivity.java
public class MainActivity extends Activity {
Spinner selectcityspinner;
ArrayList<String> citylist;
ArrayList<city> cityandarealist;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectcityspinner = (Spinner)findViewById(R.id.selectcityspin);
citylist = new ArrayList<>();
new cityAsynTask().execute("Jason data url");//put your url over here
}
public class cityAsynTask extends AsyncTask<String,Void,Boolean>
{
#Override
protected Boolean doInBackground(String... params) {
cityandarealist = new ArrayList<city>();
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jobjcity = new JSONObject(data);
JSONArray jarray = jobjcity.getJSONArray("City");
for (int i = 0;i < jarray.length();i++){
city city = new city();
JSONObject jrealobject = jarray.getJSONObject(i);
city.setCity(jrealobject.getString("name"));
city.setArea1(jrealobject.getString("City_area1"));
city.setArea2(jrealobject.getString("City_area2"));
city.setArea3(jrealobject.getString("City_area3"));
cityandarealist.add(city);
citylist.add(jrealobject.getString("name"));
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(aBoolean == false){
Toast.makeText(MainActivity.this,"data isnot recieved",Toast.LENGTH_SHORT).show();
} else {
ArrayAdapter<String> adapter = new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_spinner_item,citylist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectcityspinner.setAdapter(adapter);
selectcityspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
String Country = String.valueOf(parent.getItemAtPosition(position));
Spinner selectareaspinner = (Spinner) findViewById(R.id.selectareaspin);
List<String> AreaList = new ArrayList<String>();
AreaList.add(cityandarealist.get(position).getArea1());
AreaList.add(cityandarealist.get(position).getArea2());
AreaList.add(cityandarealist.get(position).getArea3());
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, AreaList);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter1.notifyDataSetChanged();
selectareaspinner.setAdapter(adapter1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
}
}