How do i initialized autoComplete? I cant use it with AutoCompleteTextView because it'll tell me that local variable is duplicated. Tried declaring it static as well but its not permitted.
Please advice!
public class Search extends Activity {
public void onCreate(Bundle savedInstanceSate) {
final int autoComplete;
super.onCreate(savedInstanceSate);
setContentView(R.layout.searchshop);
//The duplicate im talking about
AutoCompleteTextView autoCompletee = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, shops);
autoCompletee.setAdapter(adapter);
autoCompletee.setThreshold(1);
autoCompletee.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent intent;
int index=999;
for(int i=0;i<shops.length;i++) {
//The local variable autoComplete may not been initialized
if(shops[i].equals(Integer.toString(autoComplete))) {
index=i;
break;
}
}
switch(index) {
case 0:
intent=new Intent(Search.this, Adidas.class);
startActivity(intent);
break;
case 1:
intent=new Intent(Search.this, Affin.class);
startActivity(intent);
break;
}
}
});
}
static final String[] shops = new String[] {
"Adidas", "Affin Bank", "Alam Art", "Al Amin"
};
}
Modifying the int autoComplete to be static, final, etc won't matter one bit because the compiler is complaining about the fact that you already have a variable called "autoComplete". In your actual code example, you named your AutoCompleteTextView "autoCompletee" with two e's which is different from autoComplete so that will work. But I'd recommend using more meaningful variable names like int autoCompleteValue or something along those lines. Either way, the problem is that you have variables colliding. Once you have a variable in scope with a certain name, you cannot use that name again...
You have autoComplete field as local variable, which need to set to some default value.
just set final int autoComplete=0;
Move this as third statement in code, first two statements should be super.... and setContent(...)
Related
What I want to do is set the texts depends on the spinner item selected by users. But there is nothing that showed up when running the app and there is no errors either. Did I miss any steps that cause the outcome didn't come out?? I'm still new to android.
UPDATE:
I forgot to say that I have three different spinners depending on which button users liked in 1st activity so I think its because I only declare for the spinner's item but didn't declare which spinner is "Japan" referring to.
So this is my code for 1st activity, I will just put only one first :
btnAsia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
intent.putExtra("continent", "asia");
startActivity(intent);
}
});
This is the string array in strings.xml:
<string-array name="asia">
<item>Japan</item>
<item>Thailand</item>
<item>Vietnam</item>
<item>South Korea</item>
</string-array>
and this is the code in 2nd activity:
private void DestinationSpinner()
{
Bundle bundle=getIntent().getExtras();
if(bundle!=null) {
String continent = bundle.getString("continent");
switch (continent) {
case "asia":
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity2.this, R.array.asia, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinnerDestination.setAdapter(adapter); // Apply the adapter to the spinner
break; }
and lastly this is the code for retrieve selected item from spinner:
public void AvailableAirlines()
{
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected=spinnerDestination.getItemAtPosition(position).toString();
if (continent.equals("asia") && selected.equals("Japan"))
{
availableAirlines.setText("Available airports");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
and I also want to pass the keyidentifer from 1st activity to 2nd activity but I tried using getExtras and it didn't work maybe I do it wrongly or what.
I think the issue is this line if(selected=="Japan")
In Java you will need to use equals instead of the == operator.
The == checks if the two pointers are pointing to the same memory location.
Equals will compare their content.
Can someone help me with this error that I keep getting?
The program that I'm trying to make is online streaming radio.
I need to return the value "value" so i can use it in another java class.
ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ch);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public int onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), mPlayer.class);
i.putExtra("name", ch.get(position));
int value = listView.getItemAtPosition(position);
startActivity(i);
return value;
}
}
The problem occurs in this line:
int value = listView.getItemAtPosition(position);
getItemAtPosition() returns an Object, so you must convert it to an int before assigning it to an int variable. You should do this only if you're sure that your listView contains integers, otherwise you'll get a ClassCastException. Do it like this:
int value = (int)listView.getItemAtPosition(position);
Also, if you startActivity() before using the value anywhere, then it does not make much sense in getting it. Use putExtra to pass it to your next activity if you wish to use it there.
I am confused about calling the spinner widget through a custom function. I am create an app in which I use spinner 20-35 times a spinner widget in single layout or activity. So for this i want to avoid the spinner code repetition again and again. i am creating a method for this i add the items to the spinner but i want to pass item value on select to other activity which bind to that class
Here is my code
Spin_tester.class
public class Spin_tester {
public String result;
public Context ctx;
public Spin_tester(Spinner spinner, final ArrayList<String> arraylist, final Context ctx , final String value) {
this.ctx= ctx;
ArrayAdapter<String> adpts =
new ArrayAdapter<String>(ctx, android.R.layout.simple_dropdown_item_1line,arraylist);
spinner.setAdapter(adpts);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
result = arraylist.get(position);
value = result ; // This is not working
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Test_Activity.class
public class Test_Activity extends AppCompatActivity {
ArrayList<String> data_list = new ArrayList<>();
Spinner spins;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
spins = (Spinner)findViewById(R.id.spinner);
data_list.add("1");
data_list.add("2");
data_list.add("3");
data_list.add("4");
Spin_tester asd = new Spin_tester(spins,data_list,this,value);
TextView txt = (TextView)findViewById(R.id.textView17);
}
}
Please help
Thanks in advance
Java is a pass-by-value language, not pass-by-reference. What this means is that setting value in setOnItemSelectedListener will only change value within that method — the result won't be passed back anywhere.
I see that you've place the result in result. That is where the calling program will find the answer.
Remove all instances of value from Spin_tester and Test_Activity and then have your main activity get the result from asd.result
I'm going to get a little meta at this point: I've only answered the question you actually asked, but this code is wrong on so many levels that you're never going to get it to work. I strongly suggest you work your way through the examples and tutorials in the documentation before you try to proceed any further.
OK, I've read around and see that Java only passes by value, not by reference so I don't know how to accomplish this.
I've 6 Spinners in an Android Activity that are populated with different SQLite queries.
The code to populate each Spinner and set the OnItemSelectedListener is very similiar so I was hoping to refactor to one method and call it 6 times with each Spinner ID and Sqlite query.
How do I get the Spinner onItemSelectedListener to change the right instance member on each different Spinner?
public void fillSpinner(String spinner_name, final String field_name) {
// This finds the Spinner ID passed into the method with spinner_name
// from the Resources file. e.g. spinner1
int resID = getResources().getIdentifier(spinner_name, "id",
getPackageName());
Spinner s = (Spinner) findViewById(resID);
final Cursor cMonth;
// This gets the data to populate the spinner, e.g. if field_name was
// strength = SELECT _id, strength FROM cigars GROUP BY strength
cMonth = dbHelper.fetchSpinnerFilters(field_name);
startManagingCursor(cMonth);
String[] from = new String[] { field_name };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter months = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, cMonth, from, to);
months.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(months);
// This is setting the Spinner Item Selected Listener Callback, where
// all the problems happen
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
// This is the problem area.
object_reference_to_clas_member_of_field_name = theCursor
.getString(theCursor.getColumnIndex(field_name));
}
public void onNothingSelected(AdapterView<?> parent) {
// showToast("Spinner1: unselected");
}
});
}
You call this method like this fillSpinner("spinner1","strength");.
It finds the spinner with id spinner1 and queries the database for the strength field. field_name, which is strength in this example had to be declared a final variable to be used in the onItemSelectedListener or I'd get the error Cannot refer to a non-final variable field_name inside an inner class defined in a different method.
But how do I get the onItemSelectedListener to change the value of a different instance member when each different Spinner is used? This is the all important line of code:
object_reference_to_clas_member_of_field_name = theCursor .getString(theCursor.getColumnIndex(field_name));
I can't use a final String as the variable will obviously change when the user selects a different value. I've read around a good bit and am stumped to a solution. I can just copy and paste this code 6 times and forget about refactoring but I'd really like to know the elegant solution. Post a comment if you don't understand my question, I'm not sure if I explaned myself well.
You can do it, by passing additional class as parameter of fillSpinner method:
A. Create interface
public interface OnSpinnerValueSelected {
void onValueSelected(String selectedValue);
}
B. Change your method a bit:
public void fillSpinner(String spinner_name, final String field_name,
final OnSpinnerValueSelected valueChangeListener) {
// Prepare spinner
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
valueChangeListener.onValueSelected(theCursor
.getString(theCursor.getColumnIndex(field_name)));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
C. provide listener:
fillSpinner("spinner1","strength", new OnSpinnerValueSelected() {
public void onValueSelected(String selectedValue) {
yourObject.setField(selectedValue);
}
});
Refactor your listener to a new "class". Initialize with the right arguments/instances as required so that the repeated "code" is reusuable.
Right, this is how I managed it but I'm still open to new suggestions for an accepted answer and I also created a bounty.
I didn't create a new class like panzerschreck suggested so I'm posting this as a new answer to my own question. Bit of a hack but I just created an if..then..else statement in the listener to check what spinner was selected and then set a different instance member.
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Cursor theCursor = (Cursor) parent.getSelectedItem();
if (field_name.equalsIgnoreCase("strength")) {
strength=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("ring")) {
ring_gauge=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("country")) {
country=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("wrapper")) {
wrapper=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("length")) {
length=theCursor.getString(theCursor.getColumnIndex(field_name));
} else if (field_name.equalsIgnoreCase("price")) {
price=theCursor.getString(theCursor.getColumnIndex(field_name));
}
// showToast(category);
}
public void onNothingSelected(AdapterView<?> parent) {
// showToast("Spinner2: unselected");
}
});
Here are the class members
private String strength,ring_gauge,country,wrapper,length,price;
Bit of hack but without Java allowing objects to be really passed by reference, it's all I could do.
I have scoured SE and google and found what I thought were decent examples of how to implement putExtra() in tandem with getStringExtra().
The trouble I seem to be unable to resolve is that my putExtra data never appears to be getting retrieved from my getStringExtra call in the target activity.
I've tried numerous SE examples where others have asked this question countless times and yet it never seems to get me closer to a working base to expand on.
My primary activity's put is as follows;
(First, I tried this with no luck)
// Click handler for group list items
lvGroups.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int gid = groupIds.get(arg2);
Intent intent = new Intent(RadSMS_Activity.this, RadSMS_CreateGroup.class);
intent.putExtra("SELECTED_GROUP_ID", gid);
startActivity(intent);
finish();
}
});
(Then, I tried this. Also with no luck.)
// Click handler for group list items
lvGroups.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int gid = groupIds.get(arg2);
Intent target = new Intent();
target.putExtra("SELECTED_GROUP_ID", gid);
Intent intent = new Intent(RadSMS_Activity.this, RadSMS_CreateGroup.class);
startActivity(intent);
finish();
}
});
My target activity that I want to extract the value from is the following;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.creategroup);
String strGID = getIntent().getStringExtra("SELECTED_GROUP_ID");
selectedGID = new Long(strGID);
// ... additional code would be here
}
Function truncated for brevity's sake.
So, according to everything I've seen so far, it appears I'm doing it right, but when I put a breakpoint at the line where selectedGID gets assigned its value, strGID is always null. This is really beginning to make me crazy.
Can anyone please tell me if I have done something incorrect?
gid is an int.
You are putting an int.
You appear to be trying to retrieve a string.
Consider:
int gid= getIntent().getIntExtra("SELECTED_GROUP_ID",-1);
You are putting an integer value while getting it as a string. It will always return null. Use intent.getExtras().getInt() instead of intent.getStringExtra().