Android Dev - Spinner - android

I am stuck in a situation. I'm trying to use spinners in order for users to select locations. I am populating the spinners via sqlite. The idea is sometimes there is a country, province, city and sub-areas, however any field can be blank (if not populated in database).
I would like the spinners to be "hidden" if they do not have the values stored in the database. However, only the "next step down" (ex: country to province) is hidden and not all the "other steps down" (city and sub-area)
I hope I am being clear enough, if not I can clarify.
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
if (parent.getId() == R.id.spinner_query_country)
{
country.selected = (class_location)country.spinner.getSelectedItem();
get_province();
}
else if (parent.getId() == R.id.spinner_query_province)
{
province.selected = (class_location)province.spinner.getSelectedItem();
get_city();
}
else if (parent.getId() == R.id.spinner_query_city)
{
city.selected = (class_location)city.spinner.getSelectedItem();
get_sub_area();
}
else if (parent.getId() == R.id.spinner_query_sub_area)
{
sub_area.selected = (class_location)sub_area.spinner.getSelectedItem();
}
}
public void onNothingSelected(AdapterView<?> parent)
{
// TODO Auto-generated method stub
}
void get_country()
{
make_spinner(country, db.getAll("SELECT * FROM country"));
}
void get_province()
{
make_spinner(province, db.getAll("SELECT * FROM province WHERE country_key=" + country.selected._key));
}
void get_city()
{
make_spinner(city, db.getAll("SELECT * FROM city WHERE province_key=" + province.selected._key));
}
void get_sub_area()
{
make_spinner(sub_area, db.getAll("SELECT * FROM sub_area WHERE city_key=" + city.selected._key));
}
void make_spinner(_structure structure, List<class_location> location_list)
{
if (location_list.size() > 0)
{
class_location location_array[] = location_list.toArray(new class_location[location_list.size()]);
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this, android.R.layout.simple_spinner_item, location_array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
structure.spinner.setAdapter(adapter);
structure.spinner.setVisibility(View.VISIBLE);
structure.textview.setVisibility(View.VISIBLE);
}
else
{
structure.spinner.setAdapter(null);
structure.spinner.setVisibility(View.GONE);
structure.textview.setVisibility(View.GONE);
}
}

You are hidding only one spinner, not all of them simply because you are setting the visibility at make_spinner() and you only check one step down on your onItemSelected(if else strict). To make it clear, your code sets the visibility or invisibility of the components on a method that is never called for the "others steps down".
P.S.: Your code is kinda messy and do not follow the conventions or guidelines of Android. This is bad. Try to checkout some guidelines, help your collaborators :)

Related

Getting String from Spinner, and using it on conditional statements

I have this program that will change the hours and minutes of the values I get from Calendar.
So I'm changing only the hour, I'm doing a Timezone thing here. So, what I do is I make an array of the TimeZones at Strings.xml and put it on a spinner. And then, when I change the item on the spinner, I set the text of a textview to the selected value on the spinner.
I can do it up to here.
My problem lies in the conditional statements. I have a button that gets the text in the TextView and I will use that in my If statements. This is my Syntax.
This gets me the values from the Spinner to the TextView.
Spinner TimezoneSelect = (Spinner)findViewById (R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.timzones, R.layout.support_simple_spinner_dropdown_item);
TimezoneSelect.setAdapter(adapter);
//final String SelectedTimeZone = TimezoneSelect.getSelectedItem().toString();
TimezoneSelect.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TimeZoneStatus = parent.getItemAtPosition(position).toString();
TimeZoneDisplay.setText(TimeZoneStatus);
And this is the faulty If statement.
public void onClick(View v) {
// TODO Auto-generated method stub
int newhour;
String TimeZoneNow = TimeZoneStatus.trim().toString();
String Jakarta = "UTC+7:00 (Jakarta)";
if ((TimeZoneNow == "UTC+7:00(Jakarta)") || (TimeZoneNow == Jakarta))
//^lol desperate code
{
newhour = hour - 1;
TimeText.setText(newhour + ":" + minutes);
}
}
});
Help! :c
try this way
if(TimeZoneNow.equals(Jakarta)
used .equals() method for string comparison
use this code
if ((TimeZoneNow .equalsIgnoreCase(Jakarta))
//^lol desperate code
{
newhour = hour - 1;
TimeText.setText(newhour + ":" + minutes);
}
Try this:
In your case replace == with eqauls().
Explanation:
== operator is used to compare reference.
equals() is used to compare content.

Drag-drop not working in nhaarman's ListviewAnimation library

I am using nhaarman's ListviewAnimation library https://github.com/nhaarman/ListViewAnimations which works great.
But I am facing following issues:
The main problem I am facing is, I am not able to debug my code. I have directly copy/pasted the four required libraries into libs folder. Placing a debug point inside any of the listview methods like onItemLongClick() does not work.
The second problem is, drag-drop listView is not working in my code. Whenever I try to drag any list item, on dropping the list item, the item takes the same position from which it was dragged.
Here's the code I have used:
listview.enableDragAndDrop();
listview.setDraggableManager(new TouchViewDraggableManager(
R.id.list_row_draganddrop_textview));
listview.setOnItemMovedListener(this);
listview.setOnItemLongClickListener(this);
#Override
public void onItemMoved(final int originalPosition, final int newPosition) {
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(getApplicationContext(), "Moved"
+ swingBottomInAnimationAdapter.getItem(newPosition)
+ newPosition, Toast.LENGTH_SHORT);
mToast.show();
}
#Override
public boolean onItemLongClick(final AdapterView<?> parent,
final View view, final int position, final long id) {
if (listview != null) {
listview.startDragging(position - listview.getHeaderViewsCount());
}
return true;
}
Whenever I try to drag any list item, on dropping the list item, the item takes the same position from which it was dragged.
Of course. Handling the change in position is your responsibility, and you should take care of it inside the onItemMoved callback:
#Override
public void onItemMoved(final int originalPosition, final int newPosition) {
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(getApplicationContext(), "Moved"
+ swingBottomInAnimationAdapter.getItem(newPosition)
+ newPosition, Toast.LENGTH_SHORT);
mToast.show();
// Adapt the following to your implementation
if (originalPosition != newPosition) {
YourObject item = (YourObject) yourAdapter.getItem(originalPosition);
yourAdapter.moveItem(item, newPosition);
}
}
The method mentioned above would look something like:
public void moveItem(YourObject item, int newIndex) {
if (mEntries != null) {
mEntries.remove(item);
mEntries.add(newIndex, item);
notifyDataSetChanged();
}
}
If you go through the source code, you'll see that what you are dragging around is a Bitmap. The list item is sitting at its original position.
For others having the same problem - Niek Haarman has answered this question on GitHub here.
Don't see GitHub going down soon, but as it is good tone to paste the answer too, here it is:
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return true;
}
position is not a stable id here. You need a stable id for the item
which does not depend on the position.
use
import com.nhaarman.listviewanimations.ArrayAdapter;
instead of
import android.widget.ArrayAdapter;
that is the reason it doesn't calling onItemMoved

Issue with ViewHolder in ArrayAdapter - Android

I have a custom adapter that renders two (2) checkboxes, a picture and the name of the client. All the information needed for the adapter is fetched from an ArratList that contains the Client class.
Every row needs to have both checkboxes checked (selected) for the client in order to process the purchase order, in case that a particular client has one checkbox checked-off and the other checkbox not, that raises a flag as MISMATCH. To make a valid order both checkboxes need to be checked-off.
We are implementing a button for verification, which will find any mismatch in the adapter and then hightlight the mismatches.
EDITION: After pressing the verificationBtn I am able to identify if any row has mismatch on checkboxes, for example, if checkbox1 was checked and checkbox2 not. that will mark the row as mismatch. I am using the position of my checkboxes based on clientList that is an arraylist of List clientList.
QUESTION: How can I get the position that the viewHolder has in order compare against the clientList position? Is there any way I can force the viewHolder to store the position and get it back and make the comparison with cli.getClient_number() ?
So far I have tested two different ways with no luck:
Method 1:
viewHolder.clientName.setBackgroundColor((Interger.parseInt(cli.getClient_number()) ) == position ? Color.GREEN : Color.TRANSPARENT);
Method 2
viewHolder.clientName.setBackgroundColor(Color.GREEN);
here the code that I am implementing.
// This goes in my main Client Activity
Button verificationBtn = (Button) findViewById(R.id.verificationBtn);
verificationBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buffer.setLength(0);
mismatchTv.setText("");
for (Client cli : clientList) {
if (cli.isCheckboxOneSelected() != cli.isCheckboxTwoSelected()) {
//We had defined above the following buffer = new StringBuffer();
buffer.append((ah.parseInt(cli.getClient_number(), 0) - 1) + ", ");
cli.setMismatch(true);
//We are passing here the ID that correspond to the client mismatch
list_adapter.setBackgroundColor(Integer.parseInt(cli.getClient_number()) - 1);
setListAdapter(list_adapter);
Log.w("cli.getClient_number() ", String.valueOf(Integer.parseInt(cli.getClient_number()) - 1));
}
}
// We display any mismatch on a TextView on top of the screen
if (buffer.length() != 0) {
//This is a TextView on top of the screen
mismatchTv.setText("Error en Client(s) "
+ buffer.toString());
}
// This goes inside of the ClientArrayAdapter
public void setBackgroundColor(int position) {
Log.w("inside of setBackgroundColor method", "True");
switchIndex = 1;
positionFetched = position;
}
// This goes inside of the ClientArrayAdapter
// and inside the body of public View getView(int position, View convertView, ViewGroup parent) {
switch (switchIndex) {
case 1:
viewHolder.cbone
.setButtonDrawable(R.drawable.btn_checkbox_selector);
viewHolder.cbtwo
.setButtonDrawable(R.drawable.btn_checkbox_selector);
Log.w("switch 1 was called ", "True");
for (Client cli : clientList) {
if (cli.isCheckboxOneSelected() != cli.isCheckboxTwoSelected()) {
Client cli = getItem(positionFetched);
if (cli.isMismatch()) {
cli.setColor(Color.BLACK);
Log.e("if (cli.isMismatch()) ", "");
//HERE WE ARE TRYING TO HIGHLIGHT THE ROW WITH MISMATCH
//WHY THIS LINE DOES NOT WORK?
//THE ISSUE THAT I AM GETTING IS THAT I CANNOT CONTROL WHAT ROW TO AFFECT
//IN THE VIEW HOLDER
viewHolder.clientName.setBackgroundColor(Color.GREEN);
}
}
}
break;
default:
viewHolder.cbone.setButtonDrawable(R.drawable.disabled_cb);
viewHolder.cbtwo.setButtonDrawable(R.drawable.disabled_cb);
break;
}
// This goes inside of the ClientArrayAdapter
static class ViewHolder {
public TextView clientName;
public TextView clientNumber;
public ImageView imageView;
public CheckBox cbtwo;
public CheckBox cbone;
public int position;
}
After three days trying to figure out what's wrong with this code, I finally found the solution moving the Method #1 just at the very end of the getView method. :-)

Event TableFixHeader

I download a custom table from this site.
I want to show the value of the cell I click.
TableFixHeaders table = (TableFixHeaders) findViewById(R.id.table_1);
table.setAdapter(new MyAdapter(this));
table.setOnLongClickListener(new OnLongClickListener(){
#Override
public boolean onLongClick(View v) {
TextView Cl = (TextView) table.getChildAt(1);
Toast.makeText(this, Cl.getText().toString(), Toast.LENGTH_LONG).show();
return false;
}
});
The problem is I can't intercept any event in my main activity.
I also have downloaded this very nice widget with scrolling columns and rows. And I also needed to get a response on a click at a certain cell. It didn't come, but I found the reason here:
In TableFixHeaders.java, module OnTouchEvent(MotionEvent event) add this line at the beginning:
super.onTouchEvent(event);
This call will make sure that other touch methods gets called! So it should also work for longclicks as well!
I have added my click-handler to the specific view (cell) in module GetView(int row, int column, View convertView, ViewGroup parent) when convertView is inflated first time. Then I an able to have different handlers to different cells (columns-headers, data-cells etc).
Here is the detailed code:
private View getBody(final int row,final int column, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.item_table, parent, false);
}
/*if(row == 8){
convertView.setBackgroundResource(R.color.row8); //if row8 need different colour
}*/else {
//Change table color using bg_table_col
convertView.setBackgroundResource(row % 2 == 0 ? R.drawable.bg_table_color1 : R.drawable.bg_table_color2);
}
((TextView) convertView.findViewById(android.R.id.text1)).setText(records.get(row).getItem(column + 1));
convertView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
detailsearchPaperID = records.get(row).getItem(0);
final String S;
S = detailsearchPaperID + " : " + records.get(row).getItem(column + 1);
Log.d(TAG, S);
Toast.makeText(getApplicationContext(), S, Toast.LENGTH_SHORT).show();
//...
// we will not start intent here but after performing search
return true;
}
});
return convertView;
}
If you add the listener as explained in previous post (when convertView is inflated first time), this will work only on the first view, before performing any scroll.
My code works even if you have performed scroll. Of course you need to add
super.onTouchEvent(event);
as explained earlier
I'm using this wrapper for InqBarna's library.
This is a code snippet of how to achieve the click events on table body.
You can see more ellaborated examples here.
TableFixHeaderAdapter.ClickListener<List<String>, BasicCellViewGroup> clickListenerBody = new TableFixHeaderAdapter.ClickListener<List<String>, BasicCellViewGroup>() {
#Override
public void onClickItem(List<String> array, BasicCellViewGroup viewGroup, int row, int column) {
viewGroup.vg_root.setBackgroundColor(ContextCompat.getColor(context, R.color.colorYellow));
Snackbar.make(viewGroup, "Click on " + viewGroup.textView.getText() + " (" + row + "," + column + ")", Snackbar.LENGTH_SHORT).show();
}
};
and so on for the rest of the table cells:
adapter.setClickListenerFirstHeader(clickListenerHeader);
adapter.setLongClickListenerFirstHeader(longClickListenerHeader);
adapter.setClickListenerHeader(clickListenerHeader);
adapter.setLongClickListenerHeader(longClickListenerHeader);
adapter.setClickListenerFirstBody(clickListenerBody);
adapter.setLongClickListenerFirstBody(longClickListenerBody);
adapter.setClickListenerBody(clickListenerBody);
adapter.setLongClickListenerBody(longClickListenerBody);
adapter.setClickListenerSection(clickListenerBody);
adapter.setLongClickListenerSection(longClickListenerBody);
Hope it helps you.

Android Gallery visible ImageView is null?

I want to draw a check mark for the image view I click on and uncheck the imageview I clicked on before using the following code snip. I store last checked position in mDeviceAdapter. When I try to uncheck old position, the image view always gives null even for the partial visible image view. I am really confused because I thought only invisible one is recycled... Newbie in Android and any comment is appreciated.
public void CheckableImageView#setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
invalidate();
}
}
mDeviceGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckableImageView viewToCheck = (CheckableImageView) view;
if (!viewToCheck.isChecked()) {
int oldCheckedPosition = mDeviceAdapter
.getCheckedPosition();
mDeviceAdapter.setCheckedPosition(position);
View checkedView = mDeviceGallery
.getChildAt(oldCheckedPosition);
Log.d(TAG, "old position="+oldCheckedPosition + "old view="+checkedView);
if (checkedView != null) {
((CheckableImageView) checkedView)
.setChecked(false);
Log.d(TAG, "uncheck position="
+ oldCheckedPosition);
}
viewToCheck.setChecked(true);
That's not the right approach.
You need to add to your data type a boolean field (i.e mIsChecked).
On the onItemClick method set the value of that variable to true and keep its INDEX as a member of the adapter. When another item is clicked set the value of that item to true and set the value of the saved one to false (change the value of the datatype in you ArrayList in the INDEX you stored in the previous click).
Now, in the getView() method, you must have if/else statement. Something like:
if (item.isChecked())
{
checkedView.setChecked(true);
}
else
{
checkedView.setChecked(false);
}
Example to the onClick method: (just a general direction)
if (item.isChecked())
{
checkedView.setChecked(false);
yourList.get(position).setChecked(true);
yourList.get(mLastCheckedIndex).setChecked(false);
mLastCheckedIndex = position;
notifyDataSetChanged();
}
else
{
//same but opposite.
}
Hope this helps!

Categories

Resources