How to Pass an Int from non-activity class to Activity class - java

Android is similar to Java in terms of convention but why does my setter and getter methods won't work.
I have a spinner(which is a non-activity class) with code like this:
int finalposition;
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
for(int i=0; i<40; i++) {
if (i==pos){
setPosition(pos);
}
}
}
public void setPosition(int position){
finalposition= position;
}
public int getPosition(){
return finalposition;
}
and in onCreate(), here is my MainActivity(which extends Activity):
//spinner
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(new CustomOnItemSelectedListener2());
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CustomOnItemSelectedListener2 coisl2= new CustomOnItemSelectedListener2();
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});
What I need to do is that if I select the item at position 1 in my spinner and clicked gPath button, a toast saying "It Works!" should be displayed. However, it does not work. I put a toast(displaying the position that was taken from calling getPosition()) on the button. When I selected the item at position 1 and click the button, it returned position:0. So that's why it won't enter the if-condition that I implemented and I'm wondering why. I do this in Java but why am I having troubles in Android. What is wrong/missing in my code?
Any help is appreciated

Try this.
You are creating a new instance of the listener on each onClick, and that listener would obviously not know which item was selected in the spinner, since it isn't effectively listening over anything.
//declare this as a class object
CustomOnItemSelectedListener2 coisl2= new CustomOnItemSelectedListener2();
//This follows in your onCreate
//spinner
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(coisl2);
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});

You Can try this:
Under MainActivity.java
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
coisl2= new CustomOnItemSelectedListener2(MainActivity.this,spinner2);
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});
Under CustomOnItemSelectedListener2.java( You can create this class like below)
public class CustomOnItemSelectedListener2
{
int finalposition;
public CustomOnItemSelectedListener2(Context context,Spinner spinner)
{
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
setPosition(pos);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
public void setPosition(int position){
finalposition= position;
}
public int getPosition(){
return finalposition;
}
}
Hope this is what you want...

Related

Error on execution due to setOnItemClickListener

I've tried to execute this code in my phone and in a AVD but unfortunately the app tp2 has stopped however the gradle build finished with no errors.
Could someone help me with that please ?
public class MainActivity extends Activity {
Spinner spinner;
EditText field;
Button addBtn,UpdateBtn,clearBtn;
ArrayAdapter<String> adapter;
ArrayList<String> films = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner= (Spinner) findViewById(R.id.spinner1);
field = findViewById(R.id.field);
addBtn= (Button) findViewById(R.id.addbtn);
UpdateBtn= (Button) findViewById(R.id.updatebtn);
clearBtn= (Button) findViewById(R.id.clearbtn);
//ADAPTER
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,films);
spinner.setAdapter(adapter);
spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
field.setText(films.get(i));
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add();
}
});clearBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delete();
}
});
UpdateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
update();
}
});
}
//methods
private void add(){
String film=field.getText().toString();
if(!film.isEmpty() && film.length() >0){
adapter.add(film);
adapter.notifyDataSetChanged();
field.setText("");
Toast.makeText(getApplicationContext()," Ajoute" + film, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "Rien a ajouter", Toast.LENGTH_SHORT).show();
}
}
private void update() {
String film = field.getText().toString();
int pos = spinner.getSelectedItemPosition();
if (!film.isEmpty() && film.length() > 0) {
adapter.remove(films.get(pos));
adapter.insert(film,pos);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext()," Modifie" + film, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext()," Pas Modifie" + film, Toast.LENGTH_SHORT).show();
}
}
private void delete(){
int pos = spinner.getSelectedItemPosition();
if(pos > -1){
adapter.remove(films.get(pos));
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext()," Supprime" , Toast.LENGTH_SHORT).show();
field.setText("");
}
else{
Toast.makeText(getApplicationContext()," Rien a supprimer" , Toast.LENGTH_SHORT).show();
}
}
}
It seems to be working but actually it crashes. The activity crashes and I can't find out why because nothing else (id) is displayed. Sorry for the bad english
setOnItemClickListener cannot be used with a Spinner. Use this setOnItemSelectedListener instead.
Try cast field to EditText
field = (EditText)findViewById(R.id.field);
if there's still a problem please share the error message

Passing spinner selection between activities

I have 4 activity with spinner inside every activity and this spinner include 3
string data (drop-down selection), when I pass from activity to another one I must pass this selected data inside spinner like if I have chosen data x from the list in the spinner and click in button the selected data must be in second activity spinner as x too.
I read several solutions without any solving. I hope to solve it here and this is my code for spinner and where to put the intent code
public class Page1 extends AppCompatActivity {
Spinner spinner;
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
spinner = (Spinner)findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this,R.array.film_type,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
switch (position)
{case 0:
btn[0] = (FloatingTextButton) findViewById(R.id.btn);
btn[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
double thick = Double.valueOf(editText1.getText().toString());
double width = Double.valueOf(editText2.getText().toString());
}
});
break;
case 1:
btn[0] = (FloatingTextButton) findViewById(R.id.btn);
btn[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
} catch (NumberFormatException e) {
//not a double
}
}
});
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
First save the position of selected data from spinner in a String variable,
int positionOfSelectedDataFromSpinner;
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
positionOfSelectedDataFromSpinner= position;
}
Then on button click send intent to Another activity with putExtra
Intent i = new Intent (this, activity2.class);
i.putExtra("position", positionOfSelectedDataFromSpinner);
startActivity(i);
get int from getIntent in another activity
Intent intent = getIntent();
int positionToShowToSpinner = intent.getStringExtra("position");
then set the position to spinner
spinner.setSelection(positionToShowToSpinner);
I think this my solve your problem.
this is the most painless way i can think of:
make a new class or a static member of an existing class but the second solution makes the code less understandable.
public class SpinnerPosHolder{
public static int poition;
}
then in all 4 of them:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
SpinnerPosHolder.position = spinner.getSelectedItemPosition();
For using it:
spinner.setSelection(SpinnerPosHolder.position)
You can do it in this way
String selectedItem=spinner1.getSelectedItem().toString();
And that String you can pass using Intent

Spinner Default Value / Change position

Hello to the community,
got a problem with the implementation of my project, which I hope someone can give me because some clarity.
Short description of my project:
I want to change from the Activity_A means of a button onclick events the default position of a spinner in the Activity_B. In my sample code I've tried using an Intent, Value Activity_A to the spinner in the Activity_B in an if - to give statement which then starts the spinner in the corresponding position.
Here is my code:
Activity_A:
public class Start extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
Button button = (Button) findViewById(R.id.button_1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Start.this, Spinnerwert.class);
intent.putExtra("position", "3");
startActivity(intent);
}
});
}
}
Activity_B:
public class Spinnerwert extends Activity {
private TextView beschreibung_1;
private TextView beschreibung_2;
private Spinner s1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_wert);
// TextView issue of Spinner
beschreibung_1 =(TextView)findViewById(R.id.tV_spinner_1);
// TextView output Intent worth
beschreibung_2 =(TextView)findViewById(R.id.tV_spinner_2);
// Intent data receiving
Intent i = getIntent();
String selected = i.getStringExtra("position");
beschreibung_2.setText(selected);
s1 = (Spinner) findViewById(R.id.spinner_1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.auswahl, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Spinner position - Response to Intent worth handover --------
s1.setSelection(position);
if (position == 0) {
s1.setSelection(0);
} else if (position == 1) {
s1.setSelection(1);
} else if (position == 2) {
s1.setSelection(2);
}
beschreibung_1.setText((CharSequence) parent.getItemAtPosition(position));
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
It seems as though your intent is passing a String extra, and only changing a text view within the second activity. If I am correct at understanding your question, you are wanting to place the spinner in a certain position based on the intent passed from the first activity.
Using the calls similar to those in your IF statement, simply parse the selected String to an int and call s1.setSelection on it.
It should look something like this:
s1 = (Spinner) findViewById(R.id.spinner_1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.auswahl, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setSelection(Integer.parseInt(selection));
I hope this helped!
It looks like you're never setting the spinner to the selected index. Your if statements in onItemSelected aren't doing anything since "position" is a value that gets passed in from the spinner and not the previous intent.
Try putting this
s1.setSelection(Integer.parseInt(selected));
after you set your adapter.
Spinner variant with equals value
public class Spinnerwert_2 extends Activity {
private TextView beschreibung_3;
private TextView beschreibung_4;
private Spinner s2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_wert_2);
beschreibung_3 =(TextView)findViewById(R.id.tV_spinner_3);
beschreibung_4 =(TextView)findViewById(R.id.tV_spinner_4);
Intent intent_spinner_2 = getIntent();
String spinner_2_auswahl = intent_spinner_2.getStringExtra("position_spinner_2");
beschreibung_4.setText(spinner_2_auswahl);
// #2 Spinner + Funktion(Auswahl aus Resource values/array.xml)
s2 = (Spinner) findViewById(R.id.spinner_2);
ArrayAdapter<CharSequence> adapter_2 = ArrayAdapter.createFromResource(this, R.array.auswahl, android.R.layout.simple_spinner_item);
adapter_2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(adapter_2);
// #2 SPINNER-ITEM POSITIONSEINSTELLUNG / ZUWEISUNG
s2.setSelection(adapter_2.getPosition(spinner_2_auswahl));
s2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (s2.getSelectedItem().toString().equals("Mercury")){
Toast.makeText(getApplicationContext(), "Auswahl Mercury", Toast.LENGTH_SHORT).show();
} else if (s2.getSelectedItem().toString().equals("Venus")){
Toast.makeText(getApplicationContext(), "Auswahl Venus", Toast.LENGTH_SHORT).show();
} else if (s2.getSelectedItem().toString().equals("Earth")){
Toast.makeText(getApplicationContext(), "Auswahl Earth", Toast.LENGTH_SHORT).show();
}
beschreibung_3.setText((CharSequence) parent.getItemAtPosition(position));
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}

How to get listview item string?

How to get item where i click in list-view?
Here is my code:
public class MainClass extends Activity {
ArrayList <String> listItems = new ArrayList<String>();
ArrayAdapter <String> adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listItems.add("Item 1");
listItems.add("Item 2");
listItems.add("Item 3");
adapter.notifyDataSetChanged();
listView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});
}
}
but it force closes everytime.
change:
listView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});
to:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), listView.getItemAtPosition(arg2).toString(), Toast.LENGTH_LONG).show();
}
});
You need to use a onItemClickListener if you want to interact with the items in the list. This has a position argument in the method which you can then use to retrieve the value at that position.
try :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent,
View view, int pos, long id) {
String item=(String)((TextView) view).getText();
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});

How to call activity from the items of the spinner

I have a page which consist of a spinner and a submit button. What I want to achieve is when user selects an item in the list and click on submit, it should take him to an other layout having a webview. Each item in the spinner should open different .html page in the layout.
What I have now is the item is being selected from the spinner, but I'm not sure how to perform onclick listener to it...
code for main activity.java is:
public class beef extends Activity {
private Spinner spinner1;
private ImageButton btnSubmit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beef);
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
btnSubmit = (ImageButton) findViewById(R.id.imageButton1);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId() == btnSubmit.getId())
{
Intent intent = new Intent(beef.this,display.class);
intent.putExtra("urlpath", "animalbites.html");
startActivity(intent);
}
}
});
}
}
code of CustomOnItemSelectedListener.java is:
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if (arg2 == 0) // First item selected
{
//Here I need to give an id for the .html file
}
else if (arg2 == 1) // Second
{
//Here I need to give an id for the .html file
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
and the display.java is:
public class display extends Activity implements OnClickListener {
private WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
Intent intent=getIntent();
String mUrl=intent.getStringExtra("urlpath");
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/www/"+mUrl);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
i am not exactly getting your problem, but i ll answer according to what i got:
Why are you concerned of adding an onClickListener to the spinner?
Just add onClickListener to the button and on the click of that button do:
String selecteditemName=(String)spinner1.getSelectedItem();
//spinner1 having items : "file1" , "file2"
Intent i=new Intent(this, yournewActivity.class);
i.putExtra("selected_item", selecteditemName);
startActivity(i);
Now in that activity (yournewActivity) containing the webview use this code in onCreate() method:
String item;
Intent i=getIntent();
item = i.getStringExtra("selected_item");
Now you have your spinner selection in the String 'item', you can now do whatever you want:
My point is that : You should use your spinner selection as ID for populating the webview.
If you still want to use any IDs other than the ones present in the spinner then
make an extra java class Idgetter,
class idgetter
{
public static String getID(String name)
{
if(name.equals("file1"))
return "requiredfile1.html";
else if(name.equals("file2"))
return "requiredfile2.html";
}
}
Now, Do exactly as the above code says and after you have the spinner selection in the variable item , use:
String id=idgetter.getID(item); //in younewActivity
You are finally done.
By using Intent's putExtra method.
Intent mIntent = new Intent(this, display.class);
mIntent.putExtra("urlpath", "put value in here");
startActivity(mIntent);
Populate the spinner with number of html pages and Use spinner.getSelectedItem().toString() inside the addListenerOnButton() method. By doing do, you will get the selected html page and pass it using intent to the next layout.
CODE:
`public class beef extends Activity {
private Spinner spinner1;
private ImageButton btnSubmit;
int final websiteA = 1;
int final websiteB = 2;
int final websiteC = 3;
String selectedHtmlPage = "";
.........
.........
.........
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
switch(arg2)
{
case websiteA :
selectedHtmlPage = "websiteA.html";
break;
case websiteB :
selectedHtmlPage = "websiteB.html";
break;
case websiteC :
selectedHtmlPage = "websiteC.html";
break;
}
}
public void addListenerOnButton()
{
btnSubmit = (ImageButton) findViewById(R.id.imageButton1);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if(v.getId() == btnSubmit.getId())
{
Intent intent = new Intent(beef.this,display.class);
intent.putExtra("urlpath", selectedHtmlPage);
startActivity(intent);
}
}
});
}
}`
Solved it, its simple. Here is what I did:
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(this);
}
- - -
#Override
public void onClick(View v) {
if(v.getId() == btnSubmit.getId())
{
Intent intent = new Intent(beef.this,display.class);
intent.putExtra("urlpath", mLink);
startActivity(intent);
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(arg2==0){
mLink="Beef html/BBQ_Meatballs_Recipes.html";
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}

Categories

Resources