onItemSelected method help - loading an Intent - android

I have tried Googling but couldn't get an answer specific to my problem.
I am trying to launch an activity when a item is clicked. The code is below:
public class ListOfCircuits extends Activity
{
String[] raceTrackList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_of_circuits);
raceTrackList = getResources().getStringArray(R.array.tracklist_array);
Spinner s1 = (Spinner) findViewById(R.id.circuitListSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, raceTrackList);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(),
"You have selected: " + raceTrackList[index],
Toast.LENGTH_SHORT).show();
String intentString;
String circuitChosen = raceTrackList[index].toString();
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
However at the moment it loads straight into the activity at the top of the list (TopGear). How do you get around this so that a user can see the list and select it i.e. not start an intent immediately - use an if statement?
Thanks.

This happens because the method is called the first time the Activity loads. There should be a better way to handle this but you could simply set a boolean flag
public class ListOfCircuits extends Activity
{
String[] raceTrackList;
boolean go = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
then set it to true the first time it is called and check it there
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
if (go)
{
// your code
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
else
{ go = true; }
}

CodeMagic think I have it working like a boss now:
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
if(go)
{
int index = arg0.getSelectedItemPosition();
if(index == 0)
{
Toast.makeText(getBaseContext(),
"Please select a race crcuit.",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(),
"You have selected: " + raceTrackList[index],
Toast.LENGTH_SHORT).show();
String intentString;
String circuitChosen = raceTrackList[index].toString();
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
}
else
{
go = true;
}
}
I only load Intents that I want (race circuits) and if a user selects "Choose from below:" only one relevant Toast gets displayed.
Thanks.

The answer to my answer was:
Add the Boolean as codeMagic suggested and amend my array to:
<string-array name="tracklist_array">
<item>Choose from below:</item>
<item>TopGear</item>
<item>Snetterton</item>
<item>Silverstone</item>
<item>Donnington</item>
</string-array>
From
<string-array name="tracklist_array">
<item>TopGear</item>
<item>Snetterton</item>
<item>Silverstone</item>
<item>Donnington</item>
</string-array>
And the final code is for Java - see below.
Thanks again.

Related

How to search an item string which is not written in search function activity file but in other java file?

I have plan to implement search function on a product based on name. The product are store in shoppingcarthelper.java as List. Another java file name as searchActivity.java is to preform the search function on List based on name of the product. How should i call the List on searchActivity.java? Mostly the example that i saw declare the array in the searchActivity.java or main activity file not in other java file.
Below shows the shoppingcarthelper.java.
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
private static List<product> catalog;
private static Map<product, ShoppingCartEntry> cartMap = new
HashMap<product, ShoppingCartEntry>();
public static List<product> getCatalog(Resources res){
if(catalog == null) {
catalog = new Vector<product>();
catalog.add(new product("Tudung", res
.getDrawable(R.drawable.tudung),res
.getDrawable(R.drawable.tudung1),res
.getDrawable(R.drawable.tudung2),
"Tudung testing.", 15.00, 0.20));
catalog.add(new product("Baju Kurung", res
.getDrawable(R.drawable.bajukurung),res
.getDrawable(R.drawable.bajukurung1),res
.getDrawable(R.drawable.bajukurung2),
"Baju kurung baju kurung.", 59.90, 0.50));
}
return catalog;
Here is my search function. How should i write my search function so it retrieve List from shoppingcarthelper.java?
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int
arg3) {
// When user changed the Text
main_activity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
This is kind of a duplicate, but you pointed out that you don't know where to start so I'll try to help like this: Use this answer: Custom Adapter for List View, and instead of 'Item' => 'product', and at the activity:
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow,
shoppingcarthelper.getCatalog(getResources()));
Or whatever you call the class that resides in shoppingcarthelper.java

Android dependent spinners - onItemSelected does not fire

I tryed to create two dependent spinners. I know there is more than enough of this type of question, but nothing fixed my problem. It seems onItemSelected does not fire at all. I want the second (townships_spinner) change when first spinner (divisions_spinner) is selected or changed. Let's say I have states and cities, when I select the state a want to display only cities from given state. Spinners are created dynamicaly.
That's my code:
public class RegistrationActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
createLayout();
}
public void createLayout(){
division_spinner = new Spinner(this);
ArrayAdapter division_adapter = new ArrayAdapter(this,R.layout.spinner,divisions.getList());
divisions_id = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
division_spinner.setAdapter(division_adapter);
division_spinner.setSelection(divisions.getIndex(divisions_id));
division_spinner.setOnItemSelectedListener(this);
township_spinner = new Spinner(this);
ArrayAdapter township_adapter = new ArrayAdapter(this,R.layout.spinner,townships_map.get(divisions_id));
if (divisions_id == null) {
township_spinner.setEnabled(false);
}
String value = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
township_spinner.setSelection(townships.getIndex(value, divisions_id));
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(RegistrationActivity.this, "Yes",Toast.LENGTH_LONG);
if(arg0.equals(division_spinner)) {
Toast.makeText(RegistrationActivity.this, "Yes - You got it!",Toast.LENGTH_LONG);
township_spinner.setEnabled(true);
ArrayAdapter township_adapter = new ArrayAdapter(this, R.layout.spinner, townships_map.get(((Division)division_spinner.getSelectedItem()).getDivisions_id().toString()));
township_spinner.setAdapter(township_adapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But "Yes" even "Yes - you got it!" toast does not appear.
I guess I miss something stupid, but I cant find it.
you're implementing AdapterView.onItemSelected.
...Just try this instead
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "selected", Toast.LENGTH_LONG).show();
//Call other spinner here to update.
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "nothing selected", Toast.LENGTH_LONG).show();
}
});
Edit: as Prasad says. If you don't have setContentView(View); your activity won't have an xml to inflate, so your views will never get created into anything.
I made a series of mistakes that led to the fact that it did not work as I expected.
First: I forgot to call **show()** on Toast.makeText()
Second: I make a huge mistake when creating ArrayList. I filled ArrayList with data, then I put the list to HashMap and after that I called ArrayList.**clear()**. Which led to override the HashMap values, and that was why it seemed, the spinner was not changing at all...
Well... I feel quite silly ...

prevent extra click on customdialogbox

I have one customdialog box which will appear on clicking the row of listview.And the data will display on customdialogbox from web service.Now ,if by mistake if i click twice, the customdialog box open twice.My custom dialog box is in Async class and i have call it on onPostexecute().
Every time i click on row of listview -it should called Async class in which customdialog box is there.
How to avoid to open it twice?
Please help.
I have checked some other condition but it is not working for me.
public void showCustomDialog() { // this is the dialog box i have created
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(context);
final List<String> list=new ArrayList<String>();
list.add("Low");
list.add("Normal");
list.add("High");
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.customdialoguniversalappointment);
final ListView listcustomuniversalappt=(ListView) dialog.findViewById(R.id.listcustomuniversalappt);
LinearLayout layoutsubject=(LinearLayout) dialog.findViewById(R.id.layoutsubject);
LinearLayout layoutappt=(LinearLayout) dialog.findViewById(R.id.layoutappt);
Spinner spinnerappt=(Spinner)dialog.findViewById(R.id.permissionspinner);
ImageView cancel=(ImageView)dialog.findViewById(R.id.imgcancel);
Button cancelappt=(Button)dialog.findViewById(R.id.btncancelappt);
Button confirmappt=(Button)dialog.findViewById(R.id.btnconfirmappt);
EditText subject=(EditText) dialog.findViewById(R.id.edtsubject);
subject.setText("Appointment");
TextView txtdateslot=(TextView) dialog.findViewById(R.id.txtdateslot);
txtdateslot.setText("Date:"+DoctorAppointmentAPTrequest.universalapt_date+" Time Slot:"+DoctorAppointmentAPTrequest.universalslot_time);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerappt.setAdapter(dataAdapter);
spinnerappt.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int index = arg0.getSelectedItemPosition();
selected_item=arg0.getItemAtPosition(arg2).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
System.out.println("APTCustomRequestResponse.runcustomuniversalappdata="+run_custom_universal_apptdata());
APTRequestCustomAdapter adap=new APTRequestCustomAdapter(context,run_custom_universal_apptdata());
listcustomuniversalappt.setAdapter(adap);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
System.out.println("hello");
}
});
cancelappt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
//confirm appt
confirmappt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(APT_CustomRequestResponse.radiostring.equals("checked")){
showdialogforconfirmappointment();
}else{
Toast.makeText(context, "Please Select a Patient to book a Appointment",2000).show();
}
}
});
getsubject=subject.getText().toString();
if(!dialog.isShowing()||dialog==null){//here i am checking condition where it should appear or not
dialog.show();
System.out.println(isMatch);
}else{
dialog.dismiss();
}
}
and in onPost method i have called it:
public class APT_CustomRequestResponse extends AsyncTask<String,String,String>{
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
showCustomDialog();//here i am calling custom dialog box
#Override
protected String doInBackground(String... params) {
String hunt= GetAPT_RequestCustomdata();
return hunt;
}
}
}
This async class i am calling in other class where my actual listview is :
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
APT_CustomRequestResponse APT=new APT_CustomRequestResponse(MainActivity.this);
APT.execute();
Use below provided code for reference toward solving this issue.
// Keep this as member variable to the class
final Dialog dialog = new Dialog(context);
// your new method model
public void showCustomDialog() {
// Here check this
if(dialog != null && dialog.isShowing()){
// Decide if you want to display a new one, if yes then write below code first
dialog.dismiss();
dialog = null;
// Display a new dialog code here
}else{
// Dialog is no visible, diaply it here
}
}
Instead of try to avoid twice call of showCustomDialog() method try to avoid start AsyncTask again if task is already running on ListView row click. you can do this using AsyncTask.Status :
public boolean isfirsttimeclick=true;
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
APT_CustomRequestResponse APT=new APT_CustomRequestResponse(MainActivity.this);
if(isfirsttimeclick || APT.getStatus() == AsyncTask.Status.FINISHED){
APT.execute();
}else{
/// show message to user already running
}
}
You should not send a request to the server when item is clicked twice.
Either show a progress dialog in between while first request is sent that will prevent user from clicking at the list item again.
OR check in onItem click like #ρяσѕρєя K said just to add to that use following code define APT_CustomRequestResponse object outside of onItemClick and in your activity:
In activity:
APT_CustomRequestResponse APT=null;
onItemClick:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(MainActivity.this.APT==null||MainActivity.this.APT.getStatus() == AsyncTask.Status.FINISHED){
MainActivity.this.APT=new APT_CustomRequestResponse(MainActivity.this);
MainActivity.this.APT.execute();
}
}
EDIT
In you Async task create a boolean to know if execution is complete:
boolean finished=false;
And in post execute set it to true:
finished=true;
and finally do this in your onItemClick:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(MainActivity.this.APT==null||MainActivity.this.APT.finished){
MainActivity.this.APT=new APT_CustomRequestResponse(MainActivity.this);
MainActivity.this.APT.execute();
}
}

android spinner is trigger by magic

I have a Spinner in my application which is installed and configured as follow:
final Spinner left = getLeftShiftSpinner(); //simple gets the Spinner by Id
left.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
left.setSelection(0);
try {
Log.d("test", "SHIFT_LEFT");
String s = content.shiftLeft(i);
content.clear();
updateScreen(s);
} catch (ScreenContent.WrongSyntaxException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
When I compile everything and the app starts on my device I get the Output "SHIFT_LEFT" from the Log.d(...) but I DID NOT click on anything at all. The application simply started and then by doing nothing the onItemSelectedListener is triggered?? Does anyone know why??
When the view is first inflated/activity loaded the spinner selects the first item in its list, triggering on the onItemSelected listener.
EDIT: example using boolean variable to ignore first trigger
boolean isInitTrigger = true;
final Spinner left = getLeftShiftSpinner(); // simple gets the Spinner by Id
left.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(isInitTrigger){
isInitTrigger = false;
return;
}
left.setSelection(0);
try {
Log.d("test", "SHIFT_LEFT");
String s = content.shiftLeft(i);
content.clear();
updateScreen(s);
} catch (ScreenContent.WrongSyntaxException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

how to get selected spinner item and send through SMS

I am Android Newbie here I do not know how to pass the selected spinner text to pass to SMS as SMS text to send to selected number by pressing a button. I am happy if someone can teach me here.
public class MainActivity extends Activity { //all starts here
String[] location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location = getResources().getStringArray(R.array.location_array);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, location);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have selected " + location[index], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){}
});
}
public void onClick(View v) { //<--**HERE IS THE PROBLEM**
sendSMS("5556", "+location [index]"); //<--**HERE IS THE PROBLEM**
}
//?sends an SMS message to another device?
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
//-must end here
put this sendSMS("5556", "+location [index]"); in
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Toast.makeText(getBaseContext(), "You have selected " + location[arg2], Toast.LENGTH_SHORT).show();
sendSMS("5556", location[arg2]);
}
First Save Selected value in one String Variable and then Send into SMS and another option is declare int index variable outside onItemSelected() function, sorry for my bad english communication but it will solve your problem, please see below link for more information.
Spinners in Android
and Use below code instead of your code.
public class MainActivity extends Activity { //all starts here
String[] location;
int index;
String mSelectedItem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location = getResources().getStringArray(R.array.location_array);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, location);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
index = arg0.getSelectedItemPosition();
//OR you can also store selected item using below line.
mSelectedItem=arg0.getSelectedItem().toString();
Toast.makeText(getBaseContext(), "You have selected " + location[index], Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){
}
});
}
public void onClick(View v) {
sendSMS("5556", location [index]);
//OR you can also send sms using below code.
sendSMS("5556", mSelectedItem);
}
//?sends an SMS message to another device?
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}

Categories

Resources