I have been working on an activity which has two edittext fields and two spinners. The text entered in the EditText fields doesn't show up in the toast that I generate, even though the selections done in the spinners does. What am I doing wrong ?
package com.goswami.pntgo.notifierdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.*;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class LoginScreen extends Activity {
String Course = null;
String Semester = null;
String univRollNo = null;
String name = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
final EditText tvname = (EditText) findViewById(R.id.name);
final EditText tvunivrn = (EditText) findViewById(R.id.univ_roll_no);
name = tvname.getText().toString();
univRollNo = tvunivrn.getText().toString();
Spinner course = (Spinner)findViewById(R.id.course);
Spinner semester = (Spinner)findViewById(R.id.semester);
ArrayAdapter cadapter = ArrayAdapter.createFromResource(this,R.array.courses,R.layout.courses);
ArrayAdapter sadapter = ArrayAdapter.createFromResource(this,R.array.semesters,R.layout.courses);
course.setAdapter(cadapter);
semester.setAdapter(sadapter);
course.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id){
Course = parent.getItemAtPosition(pos).toString();
}
});
semester.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Semester = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button login = (Button)findViewById(R.id.button);
login.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
Toast.makeText(LoginScreen.this,(name+" Roll No:"+univRollNo+"\n"+Course+" "+Semester),Toast.LENGTH_LONG).show();
}
});
}
}
You're setting the contents of univRollNo before anything has been entered into tvunivrn.
Add this line to the top of your login button OnClickListener:
univRollNo = tvunivrn.getText().toString();
Or just circumvent that and extract the text as such:
Toast.makeText(LoginScreen.this, name + " Roll No:" + tvunivrn.getText().toString() + "\n" + Course + " " + Semester, Toast.LENGTH_LONG).show();
Related
I have 2 different Fragments and in first Fragment, I am adding a new student entry to my custom Student ArrayList. I also have a ListView to show my student list in my second Fragment. However, when I go to my second Fragment, it doesn't update the latest ListView. So my question is that how can I update my ListView after I change my Fragment tab?
registerBtn simply adds a new entry to my studentsArrayList.
At first, I tried to use "Get" button to update my ListView but it didn't work. What I want to do is that refreshing my ListView whenever I pass to my StudentsFragment.
RegisterFragment.java:
package com.rawsly.android.schoolprogram;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class RegisterFragment extends Fragment {
private static final String TAG = "RegisterFragment";
public ArrayList<Students> studentsArrayList = new ArrayList<>();
private ArrayList<Long> idList = new ArrayList<>();
private TextView studentID;
private Button registerBtn, clearBtn, exitBtn;
private EditText editName, editLastName, editGender, editFaculty, editDepartment, editAdvisor;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_fragment, container, false);
studentID = (TextView) view.findViewById(R.id.studentID);
studentID.setText(String.valueOf(generateID()));
editName = (EditText) view.findViewById(R.id.editName);
editLastName = (EditText) view.findViewById(R.id.editLastName);
editGender = (EditText) view.findViewById(R.id.editGender);
editFaculty = (EditText) view.findViewById(R.id.editFaculty);
editDepartment = (EditText) view.findViewById(R.id.editDepartment);
editAdvisor = (EditText) view.findViewById(R.id.editAdvisor);
registerBtn = (Button) view.findViewById(R.id.registerBtn);
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = studentID.getText().toString();
String name = editName.getText().toString();
String lastName = editLastName.getText().toString();
String gender = editGender.getText().toString();
String faculty = editFaculty.getText().toString();
String department = editDepartment.getText().toString();
String advisor = editAdvisor.getText().toString();
studentsArrayList.add(new Students(id, name, lastName, gender, faculty, department, advisor));
Toast.makeText(getContext(), "New entry added.", Toast.LENGTH_SHORT).show();
}
});
clearBtn = (Button) view.findViewById(R.id.clearBtn);
clearBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editName.setText(null);
editLastName.setText(null);
editGender.setText(null);
editFaculty.setText(null);
editDepartment.setText(null);
editAdvisor.setText(null);
studentID.setText(String.valueOf(generateID()));
}
});
exitBtn = (Button) view.findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.exit(1);
}
});
return view;
}
// Generates a random ID.
public long generateID() {
Random rnd = new Random();
char [] digits = new char[11];
digits[0] = (char) (rnd.nextInt(9) + '1');
for(int i=1; i<digits.length; i++) {
digits[i] = (char) (rnd.nextInt(10) + '0');
}
long result = Long.parseLong(new String(digits));
if(idList.contains(result)) {
return generateID();
} else {
return result;
}
}
}
StudentsFragment.java:
package com.rawsly.android.schoolprogram;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class StudentsFragment extends Fragment {
private static final String TAG = "StudentsFragment";
private EditText txtSearch;
private ListView studentsListView;
private Button getStudents, updateStudent, deleteStudent, exitBtn;
public StudentsAdapter adapter;
public ArrayList<Students> studentsArrayList = new ArrayList<>();;
public int selectedItem = -1; // to update or delete the data
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.students_fragment, container, false);
// Dummy Data
studentsArrayList.add(new Students("1122334455", "Ahmet", "Özdemir", "Male", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
studentsArrayList.add(new Students("1234567890", "Ezgi", "İmamoğlu", "Female", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
studentsArrayList.add(new Students("0123456789", "Enise", "Usta", "Female", "Sosyal ve Beşeri Bilimler Fakültesi", "Uluslararası İlişkiler", "Murat Orhun"));
studentsArrayList.add(new Students("1122445588", "Sinem", "Ünver", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Zehra Yılmaz"));
studentsArrayList.add(new Students("2546882547", "Zehra", "Gürçay", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Şule Gündüz"));
adapter = new StudentsAdapter(getContext(), studentsArrayList);
studentsListView = (ListView) view.findViewById(R.id.studentsListView);
studentsListView.setAdapter(adapter);
studentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedItem = position;
Toast.makeText(getContext(), "Selected entry: " + (selectedItem+1), Toast.LENGTH_LONG).show();
}
});
// Opens a dialog window
getStudents = (Button) view.findViewById(R.id.getStudents);
getStudents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.notifyDataSetChanged();
studentsListView.invalidate();
}
}); // end of the add action
// To delete the selected School object
deleteStudent = (Button) view.findViewById(R.id.deleteStudent);
deleteStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedItem == -1) {
Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
} else {
studentsArrayList.remove(selectedItem);
selectedItem = -1;
adapter.notifyDataSetChanged();
Toast.makeText(getContext(), "Selected entry is deleted.", Toast.LENGTH_SHORT).show();
}
}
}); // end of the delete action
// To exit the program
exitBtn = (Button) view.findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.exit(1);
}
}); // end of the exit action
// To update the selected School object
updateStudent = (Button) view.findViewById(R.id.updateStudent);
updateStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedItem == -1) {
Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
} else {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.update_student);
dialog.setTitle("Update An Entry");
// Dialog components - EditText, Button
String id = studentsArrayList.get(selectedItem).id;
String name = studentsArrayList.get(selectedItem).name;
String lastName = studentsArrayList.get(selectedItem).lastName;
String gender = studentsArrayList.get(selectedItem).gender;
String faculty = studentsArrayList.get(selectedItem).faculty;
String department = studentsArrayList.get(selectedItem).department;
String advisor = studentsArrayList.get(selectedItem).advisor;
final TextView studentID = (TextView) dialog.findViewById(R.id.studentID);
final EditText editName = (EditText) dialog.findViewById(R.id.editName);
final EditText editLastName = (EditText) dialog.findViewById(R.id.editLastName);
final EditText editGender = (EditText) dialog.findViewById(R.id.editGender);
final EditText editFaculty = (EditText) dialog.findViewById(R.id.editFaculty);
final EditText editDepartment = (EditText) dialog.findViewById(R.id.editDepartment);
final EditText editAdvisor = (EditText) dialog.findViewById(R.id.editAdvisor);
studentID.setText(id);
editName.setText(name);
editLastName.setText(lastName);
editGender.setText(gender);
editFaculty.setText(faculty);
editDepartment.setText(department);
editAdvisor.setText(advisor);
Button updateStudent = (Button) dialog.findViewById(R.id.updateStudent);
Button clearStudent = (Button) dialog.findViewById(R.id.clearStudent);
Button cancelStudent = (Button) dialog.findViewById(R.id.cancelStudent);
// Updates the selected School object
updateStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = studentID.getText().toString();
String name = editName.getText().toString();
String lastName = editLastName.getText().toString();
String gender = editGender.getText().toString();
String faculty = editFaculty.getText().toString();
String department = editDepartment.getText().toString();
String advisor = editAdvisor.getText().toString();
studentsArrayList.get(selectedItem).setId(id);
studentsArrayList.get(selectedItem).setName(name);
studentsArrayList.get(selectedItem).setLastName(lastName);
studentsArrayList.get(selectedItem).setGender(gender);
studentsArrayList.get(selectedItem).setFaculty(faculty);
studentsArrayList.get(selectedItem).setDepartment(department);
studentsArrayList.get(selectedItem).setAdvisor(advisor);
adapter.notifyDataSetChanged();
Toast.makeText(getContext(), "An entry is updated.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
// Clears all fields
clearStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editName.setText(null);
editLastName.setText(null);
editGender.setText(null);
editFaculty.setText(null);
editDepartment.setText(null);
editAdvisor.setText(null);
}
});
// Dismisses the dialog
cancelStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
adapter.notifyDataSetChanged(); // notifying adapter about changes
}
}
}); // end of the update action
return view;
}
}
"Troubleshooting
If calling notifyDataSetChanged() doesn't work all the layout methods won't help either. Believe me the ListView was properly updated. If you fail to find the difference you need to check where the data in your adapter comes from.
If this is just a collection you're keeping in memory check that you actually deleted from or added the item(s) to the collection before calling the notifyDataSetChanged().
If you're working with a database or service backend you'll have to call the method to retrieve the information again (or manipulate the in memory data) before calling the notifyDataSetChanged().
The thing is this notifyDataSetChanged only works if the dataset has changed. So that is the place to look if you don't find changes coming through. Debug if needed."
duplicate: How to refresh Android listview?
I am trying to make a drop down menu that changes the text of a text view to "Player Selected: " and then a player selected from the drop down menu. However when i test the app on android, i can click a spinner item but it doesn't register anything. The textview doesn't change, and it doesn't log anything as if it wasn't registering the click listener at all. Here's my code
package com.example.buddyfizzturtles.stattracker;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.*;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends AppCompatActivity {
EditText input;
Button showBtn;
TextView showPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Players p = new Players();
// Pop-Up Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter Name");
builder.setIcon(R.drawable.basketball);
builder.setMessage("Enter a name for your player");
input = new EditText(this);
builder.setView(input);
//Set Positive Button
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String text = input.getText().toString();
Player x = new Player(text);
p.addPlayer(x);
Toast.makeText(MainActivity.this, "Added " + text + " to your player list", Toast.LENGTH_SHORT).show();
}
});
//Set Negative Button
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//Create Builder
final AlertDialog ad = builder.create();
//Button
showBtn = (Button) findViewById(R.id.addPlayerButton);
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ad.show();
}
});
//Spinner Items
Spinner dropNames = (Spinner) findViewById(R.id.choosePlayer);
dropNames.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Log.d("CLICKED:", "Successful Click");
showPlayer = (TextView) findViewById(R.id.showPlayer);
showPlayer.setText("Player Selected: " + );
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
ArrayAdapter<Player> adapter = new ArrayAdapter<Player>(this, android.R.layout.simple_spinner_item, p.returnList());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropNames.setAdapter(adapter);
}
}
You can try this. Let's see if it resolves
Spinner spinner=(Spinner)findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("CLICKED:", "Successful Click");
showPlayer = (TextView) findViewById(R.id.showPlayer);
showPlayer.setText("Player Selected: " + );
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Hope this helps
If the spinner is loading data, then I think this will help you (It's good to define showPlayer outside the listener).
Spinner dropNames = (Spinner) findViewById(R.id.choosePlayer);
TextView showPlayer = (TextView) findViewById(R.id.showPlayer);
dropNames.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
showPlayer.setText("Player Selected: " + String.valueOf(dropNames.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
My problem is that my code does not react accordingly whenever an user selects an item from an AutoCompleteTextView.
flag is a variable which is set to a value whenever one item from each AutoCompleteTextView has been selected. If it's set to 1, then it means it's right and it should proceed to main activity. Otherwise, a toast is displayed on click of button whose onClick calls the method callMainActivity.
There are no errors. Gradle build is successful, but clicking on that button (mentioned above) does nothing at all.
Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class Location extends AppCompatActivity {
private static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
int city = android.R.layout.simple_dropdown_item_1line;
int area = android.R.layout.simple_dropdown_item_1line;
int store = android.R.layout.simple_dropdown_item_1line;
String []city_array = getResources().getStringArray(R.array.City);
String []area_array= getResources().getStringArray(R.array.Area);
String []store_array= getResources().getStringArray(R.array.Store);
List<String> city_list= Arrays.asList(city_array);
List<String> area_list= Arrays.asList(area_array);
List<String> store_list= Arrays.asList(store_array);
ArrayAdapter<String> adapter_city = new ArrayAdapter(this,city, city_list);
ArrayAdapter<String> adapter_area = new ArrayAdapter(this, area, area_list);
ArrayAdapter<String> adapter_store = new ArrayAdapter(this, store, store_list);
final AutoCompleteTextView autocompleteView_city =
(AutoCompleteTextView) findViewById(R.id.City);
final AutoCompleteTextView autocompleteView_area =
(AutoCompleteTextView) findViewById(R.id.Area);
final AutoCompleteTextView autocompleteView_store =
(AutoCompleteTextView) findViewById(R.id.Store);
autocompleteView_area.setAdapter(adapter_area);
autocompleteView_city.setAdapter(adapter_city);
autocompleteView_store.setAdapter(adapter_store);
autocompleteView_area.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_area.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_city.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_city.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
autocompleteView_store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
autocompleteView_store.showDropDown();
if(autocompleteView_area.getListSelection()!= ListView.INVALID_POSITION)
flag=1;
else
flag=0;
}
});
//This is the newly updated part
autocompleteView_area.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
//... your stuff
if(autocompleteView_area.getListSelection()>0) {
flag = 1;
System.out.println(flag + "flag at area");
}else
flag=0;
}
});
}
public void callMainActivity(View view){
if(flag==1) {
Intent in = new Intent(getBaseContext(), MainActivity.class);
startActivity(in);
}
else
Toast.makeText(getBaseContext(),"Please select all fields properly",Toast.LENGTH_LONG);
}
}
The reason you are not seeing the Toast or changing activities, is because you are never calling callMainActivity(View view) in your code. Add this line to the end of all your OnClickListeners: callMainActivity(arg0) -- if this does not work, put some log statements in your OnClickListeners to check if they are triggering or not.
Also, if you want to trigger the call when an item from your AutoCompleteTextView result list is selected, you should use an AdapterView.OnItemClickedListener instead. This will notify you when an item is selected from the AutoCompleteTextView list, or when nothing is selected and then you can react accordingly.
my code is working and I am getting the value on textview but its not changing on first click, suppose my spinner pops up and I select other value than at the same time my textview value doesn't changes it changes on the next click.
package com.vedicrishiastro.kundli.Screens.Extras;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.vedicrishiastro.kundli.R;
import com.vedicrishiastro.kundli.Screens.AbstractActivity;
public class Settings extends AbstractActivity implements View.OnClickListener {
private LinearLayout linearSelectLang,linearSetDefault,linearSelectPanch;
private TextView txtSelectLang,txtSetDefault,txtSelectPanch;
private Spinner spinner1,spinner2,spinner3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
linearSelectLang = (LinearLayout)findViewById(R.id.LinearSelectLang);
linearSetDefault = (LinearLayout)findViewById(R.id.LinearSetDefault);
linearSelectPanch = (LinearLayout)findViewById(R.id.LinearSelectPanch);
spinner1 = (Spinner)findViewById(R.id.settingSpinner1);
spinner2 = (Spinner)findViewById(R.id.settingSpinner2);
spinner3 = (Spinner)findViewById(R.id.settingSpinner3);
txtSelectLang = (TextView)findViewById(R.id.selectLangtext);
txtSetDefault = (TextView)findViewById(R.id.setdefaulttext);
txtSelectPanch = (TextView)findViewById(R.id.selectPanchtext);
linearSelectLang.setOnClickListener(this);
linearSetDefault.setOnClickListener(this);
linearSelectPanch.setOnClickListener(this);
spinner1.setVisibility(View.GONE);
spinner2.setVisibility(View.GONE);
spinner3.setVisibility(View.GONE);
}
public void onClick(View view){
int id = view.getId();
switch (id){
case R.id.LinearSelectLang:
{
spinner1.performClick();
String text = spinner1.getSelectedItem().toString();
txtSelectLang.setText(text);
spinner1.setVisibility(View.GONE);
}
break;
case R.id.LinearSetDefault:
{
spinner2.performClick();
String text = spinner2.getSelectedItem().toString();
txtSetDefault.setText(text);
spinner2.setVisibility(View.GONE);
}
break;
case R.id.LinearSelectPanch:
{
spinner3.performClick();
String text = spinner3.getSelectedItem().toString();
txtSelectPanch.setText(text);
spinner3.setVisibility(View.GONE);
}
break;
}
}
}
I tried this but it isn't working
case R.id.LinearSelectLang:
{
spinner1.performClick();
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0)
{
txtSelectLang.setText("English");
}
else
{
txtSelectLang.setText("हिंदी");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
break;
How about you use the spinner's OnItemSelected event?
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Thing is, if you call performClick, the spinner pops out, but this call is not blocking. So you need the OnItemSelectedListener to get an async response with the input made by the user.
Calling getSelectedItem right after performClick (which opens the spinner?) will return the previously set element - which is the error you are facing.
Create an onItemSelectListener for your Spinner and change the text every time an item is selected.
spinner.setOnItemSelectedListener(new OnItemSelectListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
// DO it here
}
});
I am developing one android application.i want to display a data which is selected from database and display it in listview.first of all i had used static data for display Trainee(user) data. which is static. then after For same functionality i have use sqlite Database and register the Trainee(user) and now i want to display registered trainne's name in listview. i have just done below code. can anyone help me how to display trainee names in listview.
AddTraineeActivity.java
This file works basic function of create trainee database and insert values of trainee:
package com.example.gymapp;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTraineeActivity extends Activity implements OnClickListener
{
EditText fn;
EditText ln;
EditText un;
EditText pwd;
EditText pno;
EditText age;
Button btnAdd;
SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managetrainee);
fn = (EditText) findViewById(R.id.etfirstname);
ln = (EditText) findViewById(R.id.etlastname);
age = (EditText) findViewById(R.id.edage);
pno = (EditText) findViewById(R.id.etphoneno);
un = (EditText) findViewById(R.id.ettraineeun);
pwd = (EditText) findViewById(R.id.etpwdtrainee);
btnAdd = (Button) findViewById(R.id.btnsavedata);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("create table if not exists trainee(firstname text, lastname text,age varchar,phoneNumber varchar,userTrainee varchar,passwordTrainee varchar)");
btnAdd.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v== btnAdd)
{
String firstname = fn.getText().toString();
String lastname = ln.getText().toString();
String Age = age.getText().toString();
String phoneNumber = pno.getText().toString();
String usernameTrainee = un.getText().toString();
String passwordTrainee = pwd.getText().toString();
if(firstname==null||firstname==""||firstname.length()<3)
{
show("Please Enter Correct Name.");
}
else if(lastname==null||lastname==""||lastname.length()<2)
{
show("Please Enter Correct Name.");
}
else if(Age==null||Age==""||Age.length()>3)
{
show("Please Enter Correct Age.");
}
else if(phoneNumber==null||phoneNumber==""||phoneNumber.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(usernameTrainee==null||usernameTrainee==""||usernameTrainee.length()<4)
{
show("Please Enter valid User name.");
}
else if(passwordTrainee==null||passwordTrainee==""||passwordTrainee.length()<6)
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into trainee values('"+firstname+"','"+lastname+"','"+Age+"','"+phoneNumber+"','"+usernameTrainee+"','"+passwordTrainee+"')");
//i=new Intent(this,Welcome.class);
//startActivityForResult(i, 500);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
}
}
}`
UserListActivity.java
This file contain the code which display the trainee names in listview. but this file display static users for example,trainee1,trainee2,trainee3....trainee13.
package com.example.gymapp;
import com.tss.constant.Constant;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import com.example.gymapp.AddTraineeActivity;
import com.example.gymapp.dao.DBfitguidehelper;
public class UserListActivity extends Activity {
private ListView listViewUser;
private String loggedInType ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(DBfitguidehelper.)
listViewUser = (ListView)findViewById(R.id.listViewUser);
String[] values = new String[]{"trainee", "trainee1", "trainee2", "trainee3", "trainee4", "trainee5", "trainee6", "trainee7", "trainee8", "trainee9", "trainee10", "trainee11", "trainee12", "trainee13"};
ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listViewUser.setAdapter(userAdapter);
listViewUser.setOnItemClickListener(new ListViewListner());
if(savedInstanceState!=null){
Bundle extras = getIntent().getExtras();
loggedInType = extras.getString("loggedInType");
System.out.println("loggedInType - " + loggedInType);
}
}
private class ListViewListner implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected user is " + listViewUser.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
Constant.Selected_Trainee = ""+listViewUser.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(),TrainerActivity.class);
intent.putExtra("loggedInType", loggedInType);
Toast.makeText(getApplicationContext(), "loggedInType"+loggedInType, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
now i want to display name of trainees which is stored in database. can anyone help me??
If you want to see how a Cursor loader can work for you, you can review the following project that I have uploaded to github: GPS Distance Tracking