hi how is fetching data from database and setting it in spinner on android app.how can i develop dis.the below code is update data from spinner to android mysql database.but i wish to need fetch the data from database and that fetched value is display on my spinner value on android app.how can i develop this..
this is my android code:
public class InsertionExample extends Activity {
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://192.168.1.168:8089/XcartLogin/services/update?wsdl";
private final String SOAP_ACTION = "http://xcart.com/insertData";
private final String METHOD_NAME = "insertData";
Button btninsert;
String selectedItem;
static final String KEY_NAME = "orderid";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_status);
/* Intent in = getIntent();
// Get XML values from previous intent
String orderid = in.getStringExtra(KEY_NAME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.textView1);
lblName.setText(orderid); */
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
btninsert = (Button)findViewById(R.id.btn_insert1);
btninsert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent in = getIntent();
String orderid = in.getStringExtra(KEY_NAME);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("Status");//Define the variable name in the web service method
unameProp.setValue(selectedItem);//Define value for fname variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);
PropertyInfo idProp =new PropertyInfo();
idProp.setName("Orderid");//Define the variable name in the web service method
idProp.setValue(orderid);//Define value for fname variable
idProp.setType(String.class);//Define the type of the variable
request.addProperty(idProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
TextView result = (TextView) findViewById(R.id.textView2);
result.setText(response.toString());
}
catch(Exception e){
}
}
});
//attach the listener to the spinner
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
//Dynamically generate a spinner data
createSpinnerDropDown();
}
//Add animals into spinner dynamically
private void createSpinnerDropDown() {
//get reference to the spinner from the XML layout
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//Array list of animals to display in the spinner
List<String> list = new ArrayList<String>();
list.add("Q");
list.add("P");
list.add("F");
list.add("I");
list.add("C");
//create an ArrayAdaptar from the String Array
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
//set the view for the Drop down list
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//set the ArrayAdapter to the spinner
spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
//attach the listener to the spinner
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selectedItem = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
please help me..how can i develop this.
Have you tried using ArrayAdapter<?> on your spinner? I used this once.
private class ColorSpinner extends ArrayAdapter<Integer> {
public ColorSpinner(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return this.getView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Here can I set a custom layout or view of each item in the spinner.
TextView textView = new TextView(PincodeTextView.this.context);
String message = Integer.toHexString(this.getItem(position)).toUpperCase();
textView.setBackgroundColor(this.getItem(position));
textView.setText("0x" + message);
return textView;
}
}
Then I used this to load the spinner with my ColorSpinner:
final View colorbox = this.findViewById(R.id.edit_cell_dialog_color);
if (colorbox instanceof Spinner) {
ColorSpinner list = new ColorSpinner(context, android.R.layout.simple_spinner_item);
// Load from my database the need items in my case a list of color codes.
int[] colors = PincodeTextView.this.pincodeDB.getColors();
int indexOfColor = 0;
// Add each item into the Spinner.
for (int i = 0; i < colors.length; i++) {
list.add(colors[i]);
}
((Spinner) colorbox).setAdapter(list);
}
Related
I want to add two buttons to each row of a list view. And I want to add them in the custom adapter. The two buttons are for edit and delete. The following is my adapter code.
public class RoleList extends ArrayAdapter<String>
{
private String[] name;
private String[] username;
private String[] password;
private String[] role;
private Activity context;
public RoleList(Activity context, String[] name, String[] username, String[] password, String[] role)
{
super(context, R.layout.role_list,name);
this.context = context;
this.name = name;
this.username =username;
this.password = password;
this.role = role;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.role_list, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.tv_empname);
TextView textViewusername = (TextView) listViewItem.findViewById(R.id.tv_empusername);
TextView textViewPass = (TextView) listViewItem.findViewById(R.id.tv_emppassword);
TextView textViewRole = (TextView) listViewItem.findViewById(R.id.tv_emprole);
textViewName.setText(name[position]);
textViewusername.setText(username[position]);
textViewPass.setText(password[position]);
textViewRole.setText(role[position]);
return listViewItem;
}
}
Handler for the list:-
public void userRolehandler()
{
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run()
{
RoleList roleList = new RoleList(UserRegistration.this,employee_name,emp_username,emp_password,employee_role);
userList.setAdapter(roleList);
roleList.notifyDataSetChanged();
}
});
}
//User Role array
public void userRoleArray() throws JSONException {
name = editTextName.getText().toString();
username = editTextUsername.getText().toString();
password = editTextPassword.getText().toString();
emp_role = textRole.getText().toString();
JSONObject jsonobj = new JSONObject();
jsonobj.put("name",name);
jsonobj.put("username",username);
jsonobj.put("password",password);
jsonobj.put("emp_role",emp_role);
rolejson.put(counter,jsonobj);
counter++;
}
//travRoleArray
public void travRoleArray() throws JSONException {
response = "{\"result\":" + rolejson.toString() + "}";
Log.d("RESPONSE",response);
JSONObject jsonOb = new JSONObject(response);
JSONArray result = jsonOb.getJSONArray(JSON_ARRAY);
try
{
for (int i=0; i< result.length();i++)
{
JSONObject jObj = result.getJSONObject(i);
employee_name[i] = jObj.getString(KEY_NAME);
emp_username[i] = jObj.getString(KEY_UNAME);
emp_password[i] = jObj.getString(KEY_PASS);
employee_role[i] = jObj.getString(KEY_ROLE);
}
}catch (ArrayIndexOutOfBoundsException e)
{
Toast.makeText(UserRegistration.this, "Contact customer care for assigning more roles", Toast.LENGTH_LONG).show();
}
}
Scenario:
User clicks on add user button a dialog box opens
user enters the required fields and clicks on register
a row gets added to the list view.
Screen shots:
Dialog box:
Final screen:
Now I want to add two buttons edit and delete. To allow the
user to edit and delete the row added to the list view.
The simplest solution is you should change your String[] name to ArrayList<String> name
public class RoleList extends ArrayAdapter<String>{
//private String[] name;
private ArrayList<String> name;
// it show how many items are in the data set represented by this Adapter.
#Override
public int getCount(){
return name.size();
}
}
Current you use String[], and the size of it is fix
String[] toppings = new String[10];
System.out.println("Hello World"+toppings.length); // will print 10
therefore your ListView always display 10 items (even some is empty)
But if you use ArrayList<String>, the size of list auto change when you add or remove item then your ListView will have total row = list size
OR if you still want to use String[]
You can create a new int variable like realTotalFriends (it start from 0) and every time you add new user (just increase it by 1)
Then inside getCount() you return realTotalFriends
int realTotalFriends;
#Override
public int getCount(){
return realTotalFriends;
}
Hope this help
First you need to re-edit your R.layout.role_list to add your button. I assume you know how to add button to layout. After that on your getView() method you need to define your buttons and set click listeners for them.
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.role_list, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.tv_empname);
TextView textViewusername = (TextView) listViewItem.findViewById(R.id.tv_empusername);
TextView textViewPass = (TextView) listViewItem.findViewById(R.id.tv_emppassword);
TextView textViewRole = (TextView) listViewItem.findViewById(R.id.tv_emprole);
Button edit = (Button ) listViewItem.findViewById(R.id.edit_button);
Button delete = (Button ) listViewItem.findViewById(R.id.delete_button);
textViewName.setText(name[position]);
textViewusername.setText(username[position]);
textViewPass.setText(password[position]);
textViewRole.setText(role[position]);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourList.remove(position);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// May be you can show a popup here
}
});
return listViewItem;
}
Hope it works for your needs
sorry for my english.
simply you should add buttons in your "role_list.xml" as you added TextView. then you can add onClickListner on button in your adapter class.
I hope it will help you.
This is what i have tried, but my ListView doesn't get filled. I use a custom adapter because i wan't to change the background color of the items that't got a boolean value = true. I am using Android Studio.
Hope someone can help.
i'm new to android.
public class ShoppingListActivity extends ActionBarActivity {
private TextView header;
private ListView listView;
private CustomArrayAdapter arrayAdapter;
private ShoppingList shoppingList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
header = (TextView)findViewById(R.id.textView2);
//get reference to ListView
listView = (ListView)findViewById(R.id.shoppingListItemsView);
shoppingList = (ShoppingList) getIntent().getSerializableExtra(Globals.CHOSENLISTKEY);
arrayAdapter = new CustomArrayAdapter(this, R.layout.custom_list_view, shoppingList.getItemList());
listView.setAdapter(arrayAdapter);
header.setText(shoppingList.toString());
Button btnShop = (Button) findViewById(R.id.btnShop);
btnShop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ShoppingListActivity.this, SelectStoreActivity.class);
startActivity(intent);
}
});
}
public void setData() {
for(int i = 0; i < shoppingList.getItemList().size(); i++) {
arrayAdapter.add(shoppingList.getItemList().get(i));
}
}
}
public class CustomArrayAdapter extends ArrayAdapter<Entry> {
private int resource;
private ArrayList<Entry> list;
public CustomArrayAdapter(Context context, int resource, ArrayList<Entry> list) {
super(context, resource);
this.resource = resource;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parentGroup) {
View view = convertView;
Entry entry = list.get((position));
if(view == null) {
LayoutInflater layoutInflater = ((Activity) getContext()).getLayoutInflater();
view = layoutInflater.inflate(resource, parentGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.customName);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
return view;
}
}
To show data in ListView rows call setText method of TextView which is return from getView method:
TextView textView = (TextView) view.findViewById(R.id.customName);
// get Text from entry and pass it to setText method
String strTextViewData=entry.getItem()...;
textView.setText(strTextViewData);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
I have two spinners on my layout as below:
public class DemoActivity extends Activity {
private static final String STATE_SCALE = "state-scale";
private static final String STATE_CENTER_X = "state-center-x";
private static final String STATE_CENTER_Y = "state-center-y";
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
String text1 = spinner1.getSelectedItem().toString();
Spinner spinner3 = (Spinner) findViewById(R.id.spinner3);
String text3 = spinner3.getSelectedItem().toString();
if (text1.equals("Harris Academy"))
Harris(spinner1);
if (text1.equals("Harris Academy") && text3.equals("Ground Floor")) {
Toast.makeText(getBaseContext(), text3, Toast.LENGTH_LONG).show();
try {
SubsamplingScaleImageView imageView =
(SubsamplingScaleImageView) findViewById(id.imageView);
imageView.setImageAsset("DSC00277.png");
if (savedInstanceState != null &&
savedInstanceState.containsKey(STATE_SCALE) &&
savedInstanceState.containsKey(STATE_CENTER_X) &&
savedInstanceState.containsKey(STATE_CENTER_Y)) {
imageView.setScaleAndCenter(savedInstanceState.getFloat(STATE_SCALE),
new PointF(savedInstanceState.getFloat(STATE_CENTER_X),
savedInstanceState.getFloat(STATE_CENTER_Y)));
}
} catch (IOException e) {
Log.e(DemoActivity.class.getSimpleName(), "Could not load asset", e);
}
}
}
}
This works fine when the app starts it gets the value of spinner 1 and spinner 3 and then does something depending on the values.
How do I extend it so that when I select an item on either spinner it does something based on the new values?
To get updated value as user select item from spinner,
You have to implement spinner's onItemSelectedListner
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// Do your stuff here for spinner1
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// Do your stuff here for spinner3
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
If you want to manipulate views or data on the selection of item in Spinner you need to implement
ItemSelectedListener to the particular Spinner.
Sample Code:
// in onCreate() or where you want to bind this Views with XML views
{
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner3 = (Spinner) findViewById(R.id.spinner3);
// mItemSelectedListener Object of OnItemSelectedListener to handle Item Selection to Spinners.
spinner1.setOnItemSelectedListener(mItemSelectedListener);
spinner3.setOnItemSelectedListener(mItemSelectedListener);
}
// Creating an Object of Anonymous Class so no need to create another instance for same class
// OutSide of onCreate() method.
OnItemSelectedListener mItemSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (view.getId()) {
case R.id.spinner1:
// Manipulates Views at selection of item in Spinner1
break;
case R.id.spinner3:
// Manipulates Views at selection of item in Spinner3
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
So I am trying to pass some info with serialization, but for some reason it is not working, I wrote a couple of Log.e() for testing, and according to the LogCat it says it is not getting passed the startactivity(intent).
Here is my code
public class MainActivity extends Activity {
FileManager file = new FileManager();
FileInputStream fileInput;
FileOutputStream fileOutput;
SortedArrayList<Contact> contactList = new SortedArrayList<Contact>();
ArrayList<Contact> theList =new ArrayList<Contact>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
fileInput = openFileInput("contacts.txt");
Log.e("FILE INPUT","FOUND!!");
contactList = file.read(fileInput,getApplicationContext());
Log.e("_____",contactList.toString());
}
catch (Exception e) {
Log.e("Error","ERROR CREATING FILE");
}
if(contactList.size() != 0){
ListView lv =(ListView)findViewById(R.id.contactList);
for(int i=0;i<contactList.size();i++){
theList.add(contactList.get(i));
}
ArrayAdapter<Contact> adapter = new MyListAdapter();
lv.setAdapter(adapter);
clickOnContact();
}
// Create The Adapter with passing ArrayList as 3rd parameter
//OrderAdapter arrayAdapter = new OrderAdapter(this, R.layout.list_view, contactListNameView, contactListLastNameView, contactListCellphoneView);
//Set The Adapter
//lv.setAdapter(arrayAdapter);
}
private void clickOnContact() {
ListView list = (ListView) findViewById(R.id.contactList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int pos,
long id) {
Contact Contact = theList.get(pos);
Log.e("contact: ",Contact.getFirstName());
try{
Intent intent = new Intent(MainActivity.this, ShowContactActivity.class);
Log.e("pass ","1");
intent.putExtra("Contact",Contact);
Log.e("pass ","2");
startActivity(intent);
}
catch (Exception e){
Log.e("didnt","pass catch");
}
}
});
}
private class MyListAdapter extends ArrayAdapter<Contact> {
public MyListAdapter() {
super(MainActivity.this, R.layout.list_view, theList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.list_view, parent, false);
}
Contact contact = theList.get(position);
//Fill First Name
TextView name = (TextView) itemView.findViewById(R.id.contactName);
name.setText(contact.getFirstName());
//Fill Last Name
TextView lastname = (TextView) itemView.findViewById(R.id.contactLastName);
lastname.setText(contact.getLastName());
return itemView;
}
}
This is the Activity is trying to contact:
public class ShowContactActivity extends Activity {
TextView name;
TextView lastname;
TextView email;
TextView cell;
TextView homenumber;
Contact contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_contact_info);
// Show the Up button in the action bar.
setupActionBar();
name = (TextView) findViewById(R.id.nametextview);
lastname = (TextView) findViewById(R.id.lastnametextview);
email = (TextView) findViewById(R.id.emailtextview);
cell = (TextView) findViewById(R.id.celltextview);
homenumber = (TextView) findViewById(R.id.homenumbertextview);
Contact contact = new Contact();
try{
Intent i = getIntent();
contact = (Contact) i.getSerializableExtra("Contact");
}
catch (Exception e){
Log.e("problema","con serializacion");
}
name.setText(contact.getFirstName());
lastname.setText(contact.getLastName());
cell.setText(contact.getCell());
homenumber.setText(contact.getHomeNumber());
email.setText(contact.getEmail());
}
}
use like
Contact contact = theList.get(pos); //contact is the object of the class (small c)
I am working in Spinner.. I am having three spinners and i am going to display days (i,e) 1,2,3,4,5...30,31 in 1st spinner and months in 2nd spinner (i,e)1,2,3,...11,12 and Year in 3rd spinner 2010,.... What i want is that that i wanna to display current date,month,year in 1st,2nd,3rd spinner resp when the page loads..from that it is possible to select any day,month,Year
Here is my code::
public class NoteEdit extends Activity implements OnItemSelectedListener {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private NotesDbAdapter mDbHelper;
private String array_spinner[];
private int currentDayOfMonth=0;
private int currentDayOfDays=0;
private final String[] months = {"1","2","3","4","5","6","7","8","9","10","11","12"};
Spinner s1,s,s2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH,month);//month starts from 0
cal.set(Calendar.YEAR,year);
int noOfDayInMonthyear = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
Log.v("noOfDayInMonthyear",""+noOfDayInMonthyear);
ArrayList<Integer> obj=new ArrayList();
ArrayList<Integer> obj1=new ArrayList();
for(int i=1;i<=noOfDayInMonthyear;i++){
obj.add(i);
}
Log.v("Size",""+obj.size());
for(int i=2010;i<=2020;i++){
obj1.add(i);
}
Log.v("Size1",""+obj1.size());
s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,obj);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(NoteEdit.this);
s1 = (Spinner) findViewById(R.id.Spinner02);
ArrayAdapter adapter1 = new ArrayAdapter(this,android.R.layout.simple_spinner_item,months);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter1);
s1.setOnItemSelectedListener(NoteEdit.this);
s2 = (Spinner) findViewById(R.id.Spinner03);
ArrayAdapter adapter2 = new ArrayAdapter(this,android.R.layout.simple_spinner_item,obj1);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(adapter2);
s2.setOnItemSelectedListener(NoteEdit.this);
s2.setAdapter(adapter2);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(NotesDbAdapter.KEY_ROWID)
: null;
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
finish();
}
});
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
public void onNothingSelected(AdapterView<?> arg0) {
}
if i understand your question right, i think you're asking how to set the value for each spinner?
figure out what value you want to select for each spinner and do something like this for each
http://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int, boolean)
int dateId = <date id in the spinner>;
s2.setSelection(dateId);