Pass String to Parse query from spinner - android

I've got a spinner with a list of states in an array that when a user selects it currently outputs which state they selected to the log, this is working as expected. The issue I'm facing now is when a user clicks a button once they have selected their state is pulling the data that pertains to that state from parse. My code is below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
// Add your initialization code here
com.parse.Parse.initialize(new com.parse.Parse.Configuration.Builder(getApplicationContext())
.applicationId("appidhere")
.clientKey("clientkeyhere")
.server("http://server.compute-1.amazonaws.com:80/parse/")
.build());
// find spinner object here
final Spinner locSpinner = (Spinner) findViewById(R.id.locSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.state_list, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
locSpinner.setAdapter(adapter);
locSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(final AdapterView<?> parent, View view,
final int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
final String item = locSpinner.getSelectedItem().toString();
Button search = (Button) findViewById(searchBtn);
final TextView txtState = (TextView) findViewById(R.id.txtState);
final TextView txtName = (TextView) findViewById(R.id.txtName);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ParseQuery<ParseObject> query = ParseQuery.getQuery(item);
query.whereStartsWith("Name", "Paws");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.v("item", "Retrieved " + item.toString() + " state");
txtState.setText(item);
txtName.setText(item);
} else {
Log.d("item", "Error: " + e.getMessage());
}
}
});
}
});
}
I have initialized parse in onCreate but it am having trouble getting it to populate my TextView's with the fields. For right now all I'm trying to accomplish is getting the values returned and outputting it to log, but ultimate goal is to be able to have the values show up in the TextViews. Any help would be greatly appreciated!

If you haven't already, you can have parse log what it's doing like this:
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId(appId)
.clientKey("")
.server(serverUrl)
.addNetworkInterceptor(new ParseLogInterceptor())
.build()
You will also need this in your gradle file:
compile 'com.parse:parseinterceptors:0.0.2'
Most likely you're getting an HTML response, like a 404 or 500 or something like that, rather than the JSON that the parse SDK is expecting. 403 Not Authorized (off the top of my head, I might have the wrong code) is also common if the URL or application id is wrong. By logging the details you can see the URL it's using to initialize parse, and exactly what the response is in logcat.
Edit: in your state class define a method like this:
public String getName() {
return getString("name");
}
Then do this:
textView.setText(state.getName());

Related

Spinner Array needs to link it's items to existing layouts?

So the spinner I have currently picks from a programmatic array which fetches names and images based on what's in the array.
What I need is to only pick from items in the array if they exist based on the layouts I have.
eg. I have multiple accounts in my main activity list. I only want to be able to pick an account in my spinner based on the accounts I have available (user only has 2 of 3 accounts from the array, thus only display 2 items in the spinner not all 3)
Here's my current spinner code as well as the array:
SpinnerActivity:
public class SpinnerActivity extends AppCompatActivity {
private ArrayList<AccountItem> mAccountList;
private AccountAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transactions);
//the account_spinner is being pulled from the fragment_transactions xml
initList();
Spinner spinnerAccount = findViewById(R.id.account_spinner);
mAdapter = new AccountAdapter(this, mAccountList);
spinnerAccount.setAdapter(mAdapter);
spinnerAccount.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
AccountItem clickedItem = (AccountItem) parent.getItemAtPosition(position);
String clickedAccountName = clickedItem.getAccountName();
Toast.makeText(SpinnerActivity.this, clickedAccountName + " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/**
*This is the array, I need this to link each item to their respective accounts
*that are available
**/
private void initList() {
mAccountList = new ArrayList<>();
mAccountList.add(new AccountItem("Account1", R.drawable.account1_icon));
mAccountList.add(new AccountItem("Account2", R.drawable.account2_icon));
mAccountList.add(new AccountItem("Account3", R.drawable.account3_icon));
}
}
I just need an idea of where to start. As it stands I don't see a way to give my array items individual IDs so I'm not sure if I need to change my array?
You just change the array. If you need to fetch the account list asynchronously, you can call mAdapter.notifyDataSetChanged() in the async completion callback to tell the Adapter that its backing array has changed.

Custom adapter returning nothing in String array

I have a custom spinner in my Android app;
public void onDataChange(DataSnapshot dataSnapshot) {
resultList.clear();
listSpinner.clear();
listSpinner.add("All teams");
for(DataSnapshot matchSnapshot : dataSnapshot.getChildren()) {
matches match = matchSnapshot.getValue(matches.class);
resultList.add(match);
listSpinner.add(matchSnapshot.child("homeTeam").getValue().toString());
listSpinner.add(matchSnapshot.child("awayTeam").getValue().toString());
}
listSpinner = new ArrayList<String>(new LinkedHashSet<String>(listSpinner));
spinnerTitles = listSpinner.toArray(new String[0]);
CustomAdapter adapterSpin = new CustomAdapter(getContext(), spinnerTitles, spinnerImages, spinnerPopulation);
spinner.setAdapter(adapterSpin);
resultList.sort(Comparator.comparing(matches::getDateFormatted).thenComparing(matches::getTime));
resultList adapter = new resultList (getActivity(), resultList);
listViewResult.setAdapter(adapter);
}
This works great for populating the spinner, but when I then attempt to use the spinner, and select a item in the list I keep getting;
IndexOutOfBoundsException: Index: 2, Size: 0
The error is pointing to the forth line below;
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position,long id ) {
if(++check > 1) {
String getSpinTeam =(String)parent.getSelectedItem();
....
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
When I debug and check the values of what is being returned I can still see 2 records in the array, so I'm confused as to why it errors saying that the Size is 0 when it clearly is telling me something in the debugger.
My question is, this is the first custom spinner I've built, how I have handled the setOnItemSelectedListener is that the common way of handling returned data from the spinner (it is for the built in non-custom version) or have I missed something?
Any help appreciated.
I think the error is here:
String getSpinTeam =(String)parent.getSelectedItem();
It must be:
String getSpinTeam =(String)parent.getItemAtPosition(position);
Maybe you should try this, replace:
String getSpinTeam =(String)parent.getSelectedItem();
By
String getSpinTeam = spinnerTitles.get(position);
Hope this help

Android app - how to display a list of items and make them clickable

I need to display a list of text items to the screen and make them clickable. So it would be something like a list of links on a web application.
How can I do that in an Android Activity screen?
It would be some random number of items that I have to pull from a db and display all as links.
Any idea how that can be done?
You should read the doc about ListActivity, ListView and follow the Hello ListView tutorial.
Yes you can do it. Create a DataExchange class to fetch it from Db..
Store the Strings in an Array.
Create a ArrayAdapter to display the array of Strings you got from the database.
for Example
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] numbers = {"one","two","three","four"}
// here you store the array of string you got from the database
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, numbers));
// refer the ArrayAdapter Document in developer.android.com
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String num = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("number", num);
startActivity(i);
}
});
}
}
The secondActivity to display the Particular item you have clicked should be
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("number");
// displaying selected product name
txtProduct.setText(product);
}
}
you have to create various layout files accordingly..
Hope this helps you :)
You should use a ListView. It's very simple, just create a ListActivity, put your items inside an Adapter and then set it as the Adapter of your ListActivity.
You can read more about ListViews here
There is also a new paradigm called ListFragment.
I have used ListViews before but prefer the fragments approach now - it's just very straight forward and quite flexible esp on tablets since the interation with another area on the screen when selecting an item is quite flexible and only requires very little code.
Just one example:
public class Select_FoodCategories_Fragment extends android.app.ListFragment {
private static final boolean DEBUG = true;
#Override
public void onCreate(Bundle savedInstanceState) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
HoldingActivity a = (HoldingActivity) getActivity();
//accessing a variable of the activity is easy
a.visibleListViewInFragment = getListView();
List<XYZ> listTodisplay = a.getListToDisplay();
MyAdapter adapter = new MyAdapter(
getActivity(), 0, listTodisplay);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
XYZ item = (XYZ) getListAdapter()
.getItem(position);
}
}
More info here: http://developer.android.com/reference/android/app/ListFragment.html
By the way, I find it really worth it to get familiar with the new fragments concept - it just makes live much easier - esp on tablets!
ps I left the debug statements in on purpose - since it helps alto to understand the whole concept much faster in my experience

Spinner.setSelection doesn't trigger OnItemSelectedListener properly

I'm currently working on a Account Management Activity for my Android application and I'm having trouble figuring out why the setSelection() method from a spinner does not trigger the OnItemSelectedListener attached to said Spinner.
Here is what I have currently;
onCreate() method :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_management);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
retreiveLanguage();
initializeUI();
// Vérification si l'usager est déjà connecté
Globals appState = ((Globals) this.getApplication());
boolean userLoggedIn = appState.isUserLoggedIn();
boolean userInfoAvailable = appState.isUserInfoAvailable();
if (userLoggedIn && userInfoAvailable) {
fillUI();
}
}
Pertinent lines from the initializeUI() method which is called on the Activity's creation which shows the binding of the Spinner the Listener :
/** OnItemSelectedHandler for the Country Spinner */
mCountrySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.i(TAG, "onCountrySelected() was called, position : " + pos);
mProvinces = new ArrayList<String>();
mProvincesCode = new ArrayList<String>();
mXML.parseResponse(FileManager.getInstance().getPortalOptions());
for (int i = 0; i < mXML.getCountry(pos).sizeProvinces(); i++){
mProvinces.add(mXML.getCountry(pos).getProvince(i).getLabel(mLanguage));
mProvincesCode.add(mXML.getCountry(pos).getProvince(i).getCode());
}
mProvinceArrayAdapter = new ArrayAdapter<String>(ManageAccountActivity.this,
android.R.layout.simple_spinner_item, mProvinces);
mProvinceArrayAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
mProvinceSpinner.setAdapter(mProvinceArrayAdapter);
}
public void onNothingSelected(AdapterView<?> arg0) {
// Do Nothing ...
}
});
And again another couple lines, this time from the fillUI method() :
Log.i(TAG, "Setting country based on user information.");
((Spinner) findViewById(R.id.spin_country))
.setSelection(mCountriesCode.indexOf(mUser.getCountry()));
// TODO : Fix Provinces and States not being changed accordingly
Log.i(TAG, "Setting province based on user information.");
((Spinner) findViewById(R.id.spin_province))
.setSelection(mProvincesCode.indexOf(mUser.getProvince()));
So with this I would expect the OnItemSelectedListener to be called right after I set the selection in the fillUI() method, but that's not what's happening at runtime :S
Here's my LogCat extract that shows that the Listener isn't called when the selection is applied to the country spinner:
I/ManageAccountActivity(28108): Setting country based on user information.
I/ManageAccountActivity(28108): Setting province based on user information.
I/ManageAccountActivity(28108): onCountrySelected() was called, position : 1
As an experiment, I also tried putting the fillUI() call in the onStart method of my Activity but that didn't change how the application reacted.
Thanks in advance for any pointers, help or tips !
Have you tried to set the spinner by using two arguments, the second using a boolean:
.setSelection(mProvincesCode.indexOf(mUser.getProvince()), true);
From the developers page it shows:
setSelection(int position, boolean animate)
//Jump directly to a specific item in the adapter data.
Just use the following code:
ownerSpinnerVw.post(new Runnable() {
#Override
public void run() {
ownerSpinnerVw.setSelection(position);
}
});
I found the solution to my problem being adding this to the onCreate method. The program works but only for the first selection. The second time I select the program crashes the emulator.
spinner.setOnItemSelectedListener(this);

Spinner: getContentDescription().toString()

I want to get selected item in Spinner in my java file and try to convert that in string.
I didn't getting any clue for that, so if any body help me here, I feel greatfull to him/her.
Spinner mySpinner = (Spinner)findViewbyId(R.id.spinner);
String Text = mySpinner.getSelectedItem().toString();
Add the OnItemSelectedListener listener to your Spinner object and update a variable?
For example, my very simple Spinner listener looks like this:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Nothing to do here
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
selectedIP = parent.getItemAtPosition(position).toString();
Log.e(TAG, "Selected IP updated: " + selectedIP + " position: " + position);
}
});
(selectedIP is a String I have specified further up and TAG is also a String just containing the class name for logging)
You need to first find the selected item and can then ask the adapter (or the list from wich it got the data) for the items value:
int pos = spinner.getSelectedItemPosition();
String val = backingList.get(pos);
See this class for a full example.

Categories

Resources