I want to use SharedPreferences to save the selected item that's chosen in the spinner
here is my coding
package com.mulder.jip.schoolroosterbeta2;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class CustumMaandag extends Activity {
Context Context = this;
private Spinner les1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custum_maandag);
{
les1 = (Spinner) findViewById(R.id.les1);
List<String> list = new ArrayList<String>();
list.add("Test1");
list.add("Test2");
list.add("Test3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_dropdown_item,list);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
les1.setAdapter(dataAdapter);
les1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object obj = parent.getItemAtPosition(pos);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Context);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString("object", obj.toString());
prefsEditor.commit();
}
public void onNothingSelected(AdapterView<?> parent) { }
});
}
}
}
What am I doing wrong?
Try using this inside onItemSelected(...){ *here }
String selectedText = les1.getSelectedItem().toString();
SharedPreferences.Editor editor = getSharedPreferences("your_prefs_name", MODE_PRIVATE).edit();
editor.putString("your_key", selectedText);
editor.commit();
try this.
String selecteditem = les1 .getSelectedItem().toString();
and save in shared pref like this
prefsEditor.putString("object", selecteditem );
Related
I am wanting to delete my authToken that was set on the LoginActivity but I cannot from my LogoutFragment which is part of the the MainActivity. Wondering where I could be going wrong. I seen a few threads about this but none seem to work. I am able to easily clear the shared pref when in the LoginActivity
Thanks
package com.mpl.mpl.ui.logout;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.mpl.mpl.LoginActivity;
import com.mpl.mpl.databinding.FragmentLogoutBinding;
import com.mpl.mpl.ui.logout.LogoutViewModel;
public class LogoutFragment extends Fragment {
private LogoutViewModel logoutViewModel;
private FragmentLogoutBinding binding;
private WebView webView;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
logoutViewModel =
new ViewModelProvider(this).get(LogoutViewModel.class);
binding = FragmentLogoutBinding.inflate(inflater, container, false);
View root = binding.getRoot();
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
Intent intent = new Intent(getActivity(), LoginActivity.class);
SharedPreferences preferences = getContext().getSharedPreferences("authToken", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
startActivity(intent);
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
The LoginFragment:
package com.mpl.mpl.ui.login;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.mpl.mpl.MainActivity;
import com.mpl.mpl.R;
import com.mpl.mpl.databinding.FragmentLoginBinding;
import com.mpl.mpl.restClient.MplRestClient;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginFragment extends Fragment implements View.OnClickListener {
private LoginViewModel loginViewModel;
private FragmentLoginBinding binding;
private WebView webView;
private Button button;
private Button forgottenPasswordBtn;
private Button registerBtn;
private EditText email;
private EditText password;
private EditText errorMessageField;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
loginViewModel =
new ViewModelProvider(this).get(LoginViewModel.class);
binding = FragmentLoginBinding.inflate(inflater, container, false);
View root = binding.getRoot();
webView = (WebView) root.findViewById(R.id.loginWebView);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
SharedPreferences pref;
pref = getActivity().getPreferences(Context.MODE_PRIVATE);
String token = pref.getString("authToken", null);
if (token != null) {
webView.loadUrl("javascript:testFunction('" + token + "');");
}
try {
getLoginStatus();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
webView.loadUrl("hidden");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new IJavascriptHandler(), "cpjs");
password = (EditText) root.findViewById(R.id.passwordField);
email = (EditText) root.findViewById(R.id.emailField);
errorMessageField = (EditText) root.findViewById(R.id.statusMessage);
button = (Button) root.findViewById(R.id.buttonTest);
button.setOnClickListener(this);
registerBtn = root.findViewById(R.id.registerBtn);
registerBtn.setOnClickListener(this);
forgottenPasswordBtn = (Button) root.findViewById(R.id.forgottenPasswordBtn);
forgottenPasswordBtn.setOnClickListener(this);
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
#Override
public void onClick(View v) {
//do what you want to do when button is clicked
switch (v.getId()) {
case R.id.buttonTest:
try {
getLoginStatus();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case R.id.forgottenPasswordBtn:
Uri uri = Uri.parse("hidden"); // missing 'http://' will cause crashed
Intent forgottenIntent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(forgottenIntent);
break;
case R.id.registerBtn:
NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment_login_content_main);
navController.navigate(R.id.nav_register);
break;
}
}
public void getLoginStatus() throws JSONException {
MplRestClient.post("ajax/logintest.php?eml=" + email.getText().toString() + "&pwdr=" + password.getText().toString(), null, new JsonHttpResponseHandler() {
#SuppressLint("SetTextI18n")
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
try {
String message = response.getString("status");
switch (message) {
case "verify":
errorMessageField.setText("Please Verify Your Email");
errorMessageField.setVisibility(View.VISIBLE);
break;
case "success":
String token = response.getString("token");
errorMessageField.setText("");
errorMessageField.setVisibility(View.GONE);
webView.loadUrl("javascript:testFunction('" + token + "');");
break;
default:
errorMessageField.setText("Please Check Your Details");
errorMessageField.setVisibility(View.VISIBLE);
break;
}
} catch (Exception e) {
Toast.makeText(getActivity(), "fail",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
}
});
}
final class IJavascriptHandler {
IJavascriptHandler() {
}
#JavascriptInterface
public void sendToAndroid(String text) {
if (text.length() > 11) {
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putString("authToken", text);
edt.commit();
pref = getActivity().getPreferences(Context.MODE_PRIVATE);
String id = pref.getString("authToken", null);
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
}
}
}
The LoginFragment is part of the LoginActivity, the shared preference is set in the IJavascriptHandler part
Your Problem
This is how you're setting the preference:
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putString("authToken", text);
edt.commit();
This is how you're clearing:
SharedPreferences preferences = getContext().getSharedPreferences("authToken", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
See the difference?
When you set the preferences with getActivity().getPreferences(Context.MODE_PRIVATE) you're setting it to an Activity-specific file named after the activity: see the documentation.
When you get the preferences with getContext().getSharedPreferences("authToken", Context.MODE_PRIVATE) you're trying to access an app-wide set of preferences named "authToken": see the documentation.
So you're writing to one place and reading from another so of course it's not going to match up.
A Solution
Be consistent in how you get and set preferences. The easiest way to go about that is to use PreferenceManager.getDefaultSharedPreferences for app-wide preferences.
To set:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity())
SharedPreferences.Editor edt = pref.edit();
edt.putString("authToken", text);
edt.apply();
To clear:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext())
SharedPreferences.Editor editor = preferences.edit();
editor.remove("authToken")
editor.apply();
I have XML layout like this:
[....textedit....][addbutton]
=======list1=========
=======list2=========
=======list3=========
=======list4=========
What to do if I want to Load and Show the list onCreate from SharePreferences, be able to Add "item" to the list, and save it to SharedPreferences? Any extra simple beginner explanation are welcome since I'm a total newb.
My code below is a big mess, and I got it 100% from stitching from one example to another example that I got from anywhere.
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ListAdapter;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Toast;
import android.view.View;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends Activity {
String FileName = "myFile";
Button BtnSave;
EditText editName;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnSave = findViewById(R.id.btn1);
BtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
lv = (ListView) findViewById(R.id.list1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,empty);
lv.setAdapter(adapter);
//Setting onClickListener on ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"Item Clicked: "+i,Toast.LENGTH_SHORT).show();
}
});
editName = findViewById(R.id.edit1);
}
private void saveFile() {
String strName = editName.getText().toString();
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", strName);
editor.commit();
Toast.makeText(this,"Data Saved Successfully",Toast.LENGTH_SHORT).show();
}
}
I think this should help you.
fun addProduct(productsItem: Product) {
sharedPreferences=context.getSharedPreferences(TAG,Context.MODE_PRIVATE)
var gson=Gson()
var cartProduct=getAllProducts()
cartProduct.add(productsItem)
var json=gson.toJson(cartProduct)
println(json)
sharedPreferences.edit().putString("cart_products",json).apply()
}
fun getAllProducts(): ArrayList<Product?> {
sharedPreferences=context.getSharedPreferences(TAG,Context.MODE_PRIVATE)
val listType =
object : TypeToken<List<Product?>?>() {}.type
var productsItemList:ArrayList<Product?> = ArrayList();
val json=sharedPreferences.getString("cart_products",null)
if (json !=null){
var gson=Gson()
productsItemList=gson.fromJson(json,listType)
}
return productsItemList
}
Okay, so you need to:
1)input some word in EditText
2) show it in ListView
3) save it to preferences
right?
I think you must do next steps:
Create private ArrayList<String> list = new ArrayList();
When you input something in EditText and clicked on button, call list.add(editName.getText.toString()); and then call saveFile and save list.toString();
When you need to load file, create function
private void loadFile() {
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
String string = sharedPref.getString("name", "");
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(string.split(", ")));
}
Load in adapter your newList.
I have made this app where in one particular activity i have a all the items listed in a list view. when you click the list item it goes to another activity where similar thing is happening. after that i was the clicked list items to be converted into a strings and transported into a 3rd activity where i can display those.
when i try to display them this shows in the text view where the clicked text item should have appeared:
this is code for the first activity:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.internal.Objects;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TicketCategory extends AppCompatActivity {
public static String Category;
public String getCategory() {
return Category;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_category);
populateTicketCategoryList();
final ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Category = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(TicketCategory.this, Subcategory.class);
startActivity(intent);
}
}
});
}
private void populateTicketCategoryList()
{
ArrayList<CompTicketCategory> arrayOfTicket = CompTicketCategory.getTicket();
CompTicketCategoryAdapter adapter = new CompTicketCategoryAdapter(this, arrayOfTicket);
ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setAdapter(adapter);
}
}
the code for the second activity is:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class Subcategory extends AppCompatActivity {
public String Category;
public static String Subcat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcategory);
populateSubcategoryList();
final ListView listView = (ListView) findViewById(R.id.lvSubcategory);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(Subcategory.this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Subcat = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
startActivity(intent);
}
});
and this is the code for the activity where both of the clicked items should be displayed:
public class SubmitTicket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_ticket);
Spinner spinner = (Spinner) findViewById(R.id.spinner_priority);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priority_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button butt = findViewById(R.id.submit);
butt.setOnClickListener(new View.OnClickListener()
{
public void onClick (View view){
Toast.makeText(getApplicationContext(), "The ticket has been submitted", Toast.LENGTH_SHORT).show();
}
});
TextView textView = (TextView)findViewById(R.id.Category_submit_report);
textView.setText(TicketCategory.Category);
TextView tv = (TextView)findViewById(R.id.Subcategory_submit_report);
tv.setText(Subcategory.Subcat);
}
Please help me. i would appreciate any output. thanks!
UPDATE:
after trying
CompTicketCategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory();
this error is shown;
screenshot
You can use Intent Extra Feature.
In the First Activity,
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
switch1.putExtra("deviceID", listView.getItemAtPosition(i).toString(););
startActivity(intent);
Then Next activity recall them,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
Try this in your TicketCategory actvity
Use this:
CompSubcategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory(); // or use getter setter method
Instead of this:
Category = listView.getItemAtPosition(i).toString();
I am trying to save a ArrayAdapter to shared preferences. I can get one string recovered using this code, but only one, I was not able to recover the entire ArrayAdapter.
package com.example.eduleito.listacompras;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edt_item;
private Button btn_limpar;
private ImageButton btn_adcionar;
private ListView lst_item;
private ArrayAdapter adp_item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
edt_item = (EditText) findViewById(R.id.edt_item);
btn_limpar = (Button) findViewById(R.id.btn_limpar);
btn_adcionar = (ImageButton) findViewById(R.id.btn_adcionar);
lst_item = (ListView) findViewById(R.id.lst_item);
btn_adcionar.setOnClickListener(this);
btn_limpar.setOnClickListener(this);
adp_item = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
lst_item.setAdapter(adp_item);
loadSavedPreferences();
}
private void loadSavedPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String item = sharedPreferences.getString("storeditem", "");
adp_item.add(item);
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
if (v == btn_adcionar) {
String item = edt_item.getText().toString();
adp_item.add(item);
savePreferences("storeditem", item);
edt_item.setText("");
} else if (v == btn_limpar) {
adp_item.clear();
}
}
}
Google:
Storage Options on developer.android.com
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.
I have some dummy problem, I need to get Spinner Item Position from the Fragment to this class:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.objects.Person;
import com.example.nortti.politrange.objects.Site;
import com.example.nortti.politrange.utils.WebApiAdapter;
import com.example.nortti.politrange.views.GeneralFragment;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class PersonCatalog implements ICatalog{
private final String COMMAND_PREFIX = "/api/stats/1";
private final WebApiAdapter apiAdapter = new WebApiAdapter(COMMAND_PREFIX);
private ArrayList<Person> catalogList = new ArrayList<Person>();
private Site site;
public PersonCatalog(Site site) {
this.site = site;
}
#Override
public ArrayList<Person> getCatalogList() {
return catalogList;
}
public void populateData() {
JSONArray jsonObject = null;
try {
jsonObject = (JSONArray)(new JSONParser()).parse(apiAdapter.select(null));
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
catalogList.clear();
Iterator<JSONObject> iterator = jsonObject.iterator();
while(iterator.hasNext()) {
JSONObject o = iterator.next();
catalogList.add(new Person((String)o.get("personName"),(int)(long)o.get("rank")));
}
}
}
I broke my head, I don't know how to do it. Please help! Should I use some Intents or create some getters?
UPD: Fragment Code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.example.nortti.politrange.R;
import com.example.nortti.politrange.adapters.GenAdapter;
import com.example.nortti.politrange.adapters.SiteAdapter;
import com.example.nortti.politrange.intefaces.ICatalog;
import com.example.nortti.politrange.intefaces.impls.PersonCatalog;
import com.example.nortti.politrange.intefaces.impls.SitesCatalog;
import com.example.nortti.politrange.objects.Site;
public class GeneralFragment extends Fragment implements OnClickListener, OnItemSelectedListener {
private Button genApply;
private Spinner spinner;
private ListView genList;
private View header;
private ICatalog siteCatalogImpl;
private ICatalog personCatalogImpl;
public int Num;
public void setSpinnerSource(ICatalog siteCatalogImpl) {
this.siteCatalogImpl = siteCatalogImpl;
spinData();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.general_fragment, container,false);
header = inflater.inflate(R.layout.gen_head, null);
spinner = (Spinner) v.findViewById(R.id.wSpin);
spinner.setOnItemSelectedListener(this);
genApply = (Button) v.findViewById(R.id.genApply);
genApply.setOnClickListener(this);
genList = (ListView) v.findViewById(R.id.genList);
genList.addHeaderView(header);
this.setSpinnerSource(new SitesCatalog());
Intent i = new Intent();
i.putExtra("spin", spinner.getSelectedItemPosition()+1);
return v;
}
private void spinData() {
siteCatalogImpl.populateData();
spinner.setAdapter(new SiteAdapter(getActivity(), siteCatalogImpl.getCatalogList()));
}
private void listData(Site site) {
personCatalogImpl = new PersonCatalog(site);
personCatalogImpl.populateData();
genList.setAdapter(new GenAdapter(getActivity(), personCatalogImpl.getCatalogList()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
int siteIndex = spinner.getSelectedItemPosition();
switch (v.getId()) {
case R.id.genApply:
listData((Site)siteCatalogImpl.getCatalogList().get(siteIndex));
break;
}
}
}
I calling PersonCatalog at the listdata method.
Try this.
final ArrayList<String> providerlist= new ArrayList<String>();
Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = providerlist.get(position);
// Showing selected spinner item
Toast.makeText(this,
"Selected Country : " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});