Android Spinner - java

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);

Related

Android Restful API retrofit fetching data on Create method but not display

Here is complete code
(In first activity two values are taken from spinner and through a function data sent to second activity)
First Activity:
public class FindBloodActivity extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
TextView t;
Spinner spbgid;
Spinner spcityid;
ProgressBar pro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_blood);
t = (TextView) findViewById(R.id.tv);
pro=(ProgressBar) findViewById(R.id.progressBar2);
pro.setVisibility(View.INVISIBLE);
spbgid=(Spinner) findViewById(R.id.spinnerBG);
spcityid=(Spinner) findViewById(R.id.spinnerLocation);
t.setVisibility(View.INVISIBLE);
}
public void SearchOn(View v) {
String BGId = Integer.toString(spbgid.getSelectedItemPosition()+1);
String CityId =Integer.toString(spcityid.getSelectedItemPosition()+1);
Intent intent=new Intent(getApplicationContext(),SearchResult2.class);
intent.putExtra("bid",BGId);
intent.putExtra("cid",CityId);
startActivity(intent);
}
}
Second Activity: In second activity on tt.append(string.toString()); working fine, but when i add below code than application terminated if i try to debug than also application terminate.
public class SearchResult2 extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
Spinner sp;
TextView t;
TextView tt;
public int totalUsersCount = 0;
String[] allUserNames;
String[] allUserContacts;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result2);
tt=(TextView)findViewById(R.id.tvTest);
tt.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
String BGId = extras.getString("bid");
String CityId = extras.getString("cid");
tt.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git = restAdapter.create(gitapi.class);
git.SearchUsers(BGId, CityId, new Callback<String>() {
#Override
public void success(String string, Response response) {
tt.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
tt.setText("No User Found");
}
});
String bigArray = tt.getText().toString();
listView = (ListView)findViewById(R.id.lvUsers);
bigArray = bigArray.substring(0, bigArray.length() - 1);
totalUsersCount = bigArray.split(",").length;
listView.clearTextFilter();
if (totalUsersCount > 0)
{
String[] allUsers = new String[totalUsersCount];
allUsers = bigArray.split(",");
allUserNames = new String[totalUsersCount];
allUserContacts = new String[totalUsersCount];
String[] temp = new String[3];
for (int i = 0; i < totalUsersCount; i++) {
temp = allUsers[i].split("-");
allUserNames[i] = temp[1];
allUserContacts[i] = temp[2];
}
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
}
}
}
This is log
02-08 12:40:51.433 9970-10008/com.example.abdulqadir.bd I/OpenGLRenderer: Initialized EGL, version 1.4
02-08 12:40:51.457 9970-10008/com.example.abdulqadir.bd W/linker: /vendor/lib64/libhwuibp.so: unused DT entry: type 0xf arg 0xe3a
02-08 12:40:51.458 9970-9970/com.example.abdulqadir.bd W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
02-08 12:40:51.548 9970-10008/com.example.abdulqadir.bd E/hwaps: APS: SSR : The platform cannot support SSR !: 0x0,0x0,8
This code below is working fine for me but when i changed this to above than getting errors, here is code please check
public class FindBloodActivity extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
TextView t;
Spinner spbgid;
Spinner spcityid;
ProgressBar pro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_blood);
t = (TextView) findViewById(R.id.tv);
pro=(ProgressBar) findViewById(R.id.progressBar2);
pro.setVisibility(View.INVISIBLE);
spbgid=(Spinner) findViewById(R.id.spinnerBG);
spcityid=(Spinner) findViewById(R.id.spinnerLocation);
t.setVisibility(View.INVISIBLE);
}
public void SearchOn(View v) {
String BGId = Integer.toString(spbgid.getSelectedItemPosition()+1);
String CityId =Integer.toString(spcityid.getSelectedItemPosition()+1);
SearchAllUsers(BGId.toString(), CityId.toString());
}
public void SearchAllUsers(String BGId,String CityId) {
t.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git= restAdapter.create(gitapi.class);
git.SearchUsers(BGId,CityId,new Callback<String>() {
#Override
public void success(String string, Response response) {
t.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
t.setText("No User Found");
}
});
}
public void Search(View v){
try {
Thread.sleep(9000);
Intent intent=new Intent(getApplicationContext(),SearchResult.class);
intent.putExtra("users",t.getText().toString());
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Second Activity:
public class SearchResult2 extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
Spinner sp;
TextView t;
TextView tt;
public int totalUsersCount = 0;
String[] allUserNames;
String[] allUserContacts;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result2);
tt=(TextView)findViewById(R.id.tvTest);
tt.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
String BGId = extras.getString("bid");
String CityId = extras.getString("cid");
tt.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git = restAdapter.create(gitapi.class);
git.SearchUsers(BGId, CityId, new Callback<String>() {
#Override
public void success(String string, Response response) {
tt.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
tt.setText("No User Found");
}
});
String bigArray = tt.getText().toString();
listView = (ListView)findViewById(R.id.lvUsers);
bigArray = bigArray.substring(0, bigArray.length() - 1);
totalUsersCount = bigArray.split(",").length;
listView.clearTextFilter();
if (totalUsersCount > 0)
{
String[] allUsers = new String[totalUsersCount];
allUsers = bigArray.split(",");
allUserNames = new String[totalUsersCount];
allUserContacts = new String[totalUsersCount];
String[] temp = new String[3];
for (int i = 0; i < totalUsersCount; i++) {
temp = allUsers[i].split("-");
allUserNames[i] = temp[1];
allUserContacts[i] = temp[2];
}
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
}
}
Here are the things you can try, use this code in onCreate()
listView = (ListView)findViewById(R.id.lvUsers);
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
and where you were using the above code before replace it with i.e of inside of if condition
itemsAdapter.notifyDatasetChanged();
Hope this helps
Why not do your REST call from the onCreate() method?
Also component.setVisibility(View.INVISIBLE); retains space in the overall layout. You could use 'GONE' instead and see if that helps or hurts.
And try have your URL and other components in different methods or classes. This can help a WHOLE LOT to keep the code clean and easy to find errors.
With all this said, after using breakpoints and running in debug mode which line is the error?

How to correctly use the spinner

I have some items (strings) in my spinner and when I select one of these items, I want back an associated value, for example:
If I select SAE 1020, it returns me 250.0
If I select E-155, it returns me 300.0
The value is suposed to be shown in a EditText, but the only value I see is 250.0.
After all, this value should be sent to the next Activity (I also do not know if I'm doing the transfer correctly).
What is happening? What can I do?
Code:
package com.mateus.ligacoestubulares;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class Dados extends AppCompatActivity {
String [] AçoMontante = {"SAE 1020", "E-155"};
String [] AçoBanzo = {"SAE 1020", "E-155"};
String [] EspessuraT1 = {"0,75 mm", "0,90 mm", "0,95 mm"};
String [] EspessuraTo = {"0,75 mm", "0,90 mm", "0,95 mm"};
EditText campoFy1;
EditText campoFyo;
EditText campoT1;
EditText campoTo;
EditText normalM;
EditText normalB;
EditText momentoB;
EditText teta;
Button next;
Intent intentNext;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dados);
Spinner spinnerMont = (Spinner) findViewById(R.id.spinnerM);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoMontante);
spinnerMont.setAdapter(arrayAdapter1);
campoFy1 = (EditText) findViewById(R.id.fy1);
String montStr = spinnerMont.getSelectedItem().toString();
String fy1 = Double.toString(choiceM(montStr));
campoFy1.setText(fy1);
Spinner spinnerBanzo = (Spinner) findViewById(R.id.spinnerB);
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoBanzo);
spinnerBanzo.setAdapter(arrayAdapter2);
campoFyo = (EditText) findViewById(R.id.fyo);
String banzoStr = spinnerBanzo.getSelectedItem().toString();
String fyo = Double.toString(choiceB(banzoStr));
campoFyo.setText(fyo);
next = (Button) findViewById(R.id.prosseguir);
intentNext = new Intent(Dados.this, ConferenciaDosDados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resistenciaM = campoFy1.getText().toString();
String resistenciaB = campoFyo.getText().toString();
bundle.putString("fy1",resistenciaM);
bundle.putString("fyo",resistenciaB);
intentNext.putExtras(bundle);
startActivity(intentNext);
}
});
}
public double choiceM(String str) {
Double f1 = 0.0;
if (str.equals(AçoMontante[0])) {
f1 = 250.0;
} else if (str.equals(AçoMontante[1])) {
f1 = 300.0;
}
return f1;
}
public double choiceB(String str) {
Double fo = 0.0;
if (str.equals(AçoMontante[0])) {
fo = 250.0;
} else if (str.equals(AçoMontante[1])) {
fo = 300.0;
}
return fo;
}
}
Try this. This code is working as you want it to.
String [] AçoMontante = {"SAE 1020", "E-155"};
String [] AçoBanzo = {"SAE 1020", "E-155"};
String [] EspessuraT1 = {"0,75 mm", "0,90 mm", "0,95 mm"};
String [] EspessuraTo = {"0,75 mm", "0,90 mm", "0,95 mm"};
EditText campoFy1;
EditText campoFyo;
Button next;
Intent intentNext;
Bundle bundle;
String montStr,banzoStr, f1,fo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
campoFy1 = (EditText) findViewById(R.id.fy1);
campoFyo = (EditText) findViewById(R.id.fyo);
Spinner spinnerMont = (Spinner) findViewById(R.id.spinnerM);
Spinner spinnerBanzo = (Spinner) findViewById(R.id.spinnerB);
ArrayAdapter<String> arrayAdapter1 = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, AçoMontante);
ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, AçoBanzo);
spinnerMont.setAdapter(arrayAdapter1);
spinnerBanzo.setAdapter(arrayAdapter2);
spinnerMont.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
montStr = (String) parent.getItemAtPosition(i);
if(montStr == "SAE 1020"){
f1 = "250.0";
}
else if (montStr == "E-155"){
f1 = "300.0";
}
else{}
campoFy1.setText(f1);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinnerBanzo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
banzoStr = (String) parent.getItemAtPosition(i);
if(banzoStr == "SAE 1020"){
fo = "250.0";
}
else if (banzoStr == "E-155"){
fo = "300.0";
}
else{}
campoFyo.setText(fo);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
next = (Button) findViewById(R.id.prosseguir);
intentNext = new Intent(MainActivity.this, Second.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String resistenciaM = campoFy1.getText().toString();
String resistenciaB = campoFyo.getText().toString();
bundle.putString("fy1",resistenciaM);
bundle.putString("fyo",resistenciaB);
intentNext.putExtras(bundle);
startActivity(intentNext);
}
});
}
Also, instead of bundles, you can just use private static variables to pass the value.
set f1 and fo as
private static String f1,fo; instead of String f1,fo;.
And call them in another activity as Dados.f1 or Dados.fo [ Dados here is your current activity ]

Set the Data of a Spinner based on a result of previous Spinner

I'm trying to fill a spinner based on a choice in a previous spinner,and I'm trying to get the id of the selected item in the previous spinner and the with an if statement I'm trying to add data to the another spinner.The string array are define in the Strings.xml.Any Help Please and this is my code.
public class Set_Info extends AppCompatActivity {
int i;
RadioButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set__info);
final EditText CompanyName = (EditText) findViewById(R.id.companyName);
final EditText OwnerName = (EditText) findViewById(R.id.ownerName);
final Spinner CompanyType = (Spinner) findViewById(R.id.companyType);
final Spinner Mohafaza = (Spinner) findViewById(R.id.spinnerMohafaza);
final Spinner Kadaa = (Spinner) findViewById(R.id.spinnerKadaa);
final EditText Village = (EditText) findViewById(R.id.village);
final EditText Street = (EditText) findViewById(R.id.street);
final EditText PhoneNumber = (EditText) findViewById(R.id.phoneNumber);
final EditText PolicyNumber = (EditText) findViewById(R.id.policyNumber);
final DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
final TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker);
final EditText AuditName = (EditText) findViewById(R.id.auditName);
final EditText AuditNumber = (EditText) findViewById(R.id.auditNumber);
final RadioGroup RadioGroup = (RadioGroup) findViewById(R.id.radio);
if(RadioGroup.getCheckedRadioButtonId()!=-1){
int id= RadioGroup.getCheckedRadioButtonId();
View Rd = RadioGroup.findViewById(id);
int radioId = RadioGroup.indexOfChild(Rd);
RadioButton btn = (RadioButton) RadioGroup.getChildAt(radioId);
}
final List<String> Facilities = Arrays.asList(getResources().getStringArray(R.array.Facilities));
ArrayAdapter<String> FaciltiesAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style, Facilities);
final List<String> Mohafazat = Arrays.asList(getResources().getStringArray(R.array.Mohafazat));
ArrayAdapter<String> MohazatAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style, Mohafazat);
CompanyType.setAdapter(FaciltiesAdapter);
Mohafaza.setAdapter(MohazatAdapter);
final List<String> KadaaBeirut = Arrays.asList(getResources().getStringArray(R.array.KadaaBeirut));
final List<String> KadaaJabal = Arrays.asList(getResources().getStringArray(R.array.KadaaJabal));
final List<String> KadaaNorth = Arrays.asList(getResources().getStringArray(R.array.KadaaNorth));
final List<String> KadaaSouth = Arrays.asList(getResources().getStringArray(R.array.KadaaSouth));
final List<String> KadaaNabatieh = Arrays.asList(getResources().getStringArray(R.array.KadaaNabatieh));
final List<String> KadaaBekaa = Arrays.asList(getResources().getStringArray(R.array.KadaaBekaa));
;
final ArrayAdapter<String> BeirutAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaBeirut);
final ArrayAdapter<String> JabalAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaJabal);
final ArrayAdapter<String> NorthAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaNorth);
final ArrayAdapter<String> SouthAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaSouth);
final ArrayAdapter<String> NabatiehAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaNabatieh);
final ArrayAdapter<String> BekaaAdapter = new ArrayAdapter<String>(this, R.layout.spinner_style,KadaaBekaa);
Mohafaza.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
i = parent.getSelectedItemPosition();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
if(i==0){
Kadaa.setAdapter(BeirutAdapter);
}else if(i==1){
Kadaa.setAdapter(JabalAdapter);
}else if(i==2){
Kadaa.setAdapter(NorthAdapter);
}else if(i==3){
Kadaa.setAdapter(SouthAdapter);
}else if(i==4){
Kadaa.setAdapter(NabatiehAdapter);
}else if(i==5){
Kadaa.setAdapter(BekaaAdapter);
}
Button Submit = (Button) findViewById(R.id.submit);
final ParseObject data = new ParseObject("General_Data");
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.put("CompanyName", CompanyName.getText().toString().trim());
data.put("OwnerName", OwnerName.getText().toString().trim());
data.put("CompanyType", CompanyType.getSelectedItem().toString().trim());
data.put("Mohafaza", Mohafaza.getSelectedItem().toString().trim());
data.put("Kadaa", Kadaa.getSelectedItem().toString().trim());
data.put("Village", Village.getText().toString().trim());
data.put("Street", Street.getText().toString().trim());
data.put("PhoneNumber", PhoneNumber.getText().toString().trim());
data.put("PolicyNumber", PolicyNumber.getText().toString().trim());
data.put("AuditName", AuditName.getText().toString().trim());
data.put("AuditNumber", AuditNumber.getText().toString().trim());
data.put("Inspect_Type",btn.getText().toString());
data.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Intent i = new Intent(Set_Info.this, MainActivity.class);
startActivity(i);
}
});
}
});
}
}

Android when spinner selected one of the item, it will show the information in listview according to their data name from database

public class AddMark extends AppCompatActivity {
SQLControlerSubject dbconnection;
Spinner spinnerM;
TextView tv_markId, tv_markSub,tv_markType;
TextView tv_listmarkId,tv_listmarkName,tv_listmarkMark,tv_listmarkType,tv_listmarkDescription;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_mark);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.buttonAddMark);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (spinnerM.getSelectedItem() != null) {
tv_markId = (TextView) findViewById(R.id.mark_id);
tv_markSub = (TextView) findViewById(R.id.markSub);
tv_markType = (TextView) findViewById(R.id.mark_tutorlec);
String markId = tv_markId.getText().toString();
String markSub = tv_markSub.getText().toString();
String markType = tv_markType.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), AddMarkInside.class);
modify_intent.putExtra("markId", markId);
modify_intent.putExtra("markSub", markSub);
modify_intent.putExtra("markType", markType);
startActivity(modify_intent);
}
else {Toast.makeText(getApplicationContext(), "Please select a subject", Toast.LENGTH_LONG).show();
}
}
});
// **************************Spinner view******************************
dbconnection = new SQLControlerSubject(this);
dbconnection.openDatabase();
spinnerM = (Spinner)findViewById(R.id.spinnerMark);
Cursor cursor = dbconnection.readSubjectMark();
String[] from = new String[] {
DBhelperSubject.SUBJECT_ID,
DBhelperSubject.SUBJECT_NAME,
DBhelperSubject.SUBJECT_TYPE
};
int[] to = new int[] {
R.id.mark_id,
R.id.markSub,
R.id.mark_tutorlec
};
SimpleCursorAdapter adapterMark = new SimpleCursorAdapter
(AddMark.this, R.layout.row_format_mark, cursor, from, to);
adapterMark.notifyDataSetChanged();
spinnerM.setAdapter(new NothingSelectedSpinnerAdapter(adapterMark, R.layout.spinner_show_nothing, this));
// **************************List View******************************
list = (ListView) findViewById(R.id.listViewMark);
Cursor cursorM = dbconnection.readMark();
String[] a = new String[]{
DBhelperSubject.MARK_ID,
DBhelperSubject.SUBJECT_NAME,
DBhelperSubject.SUBJECT_TYPE,
DBhelperSubject.MARK_MARKS,
DBhelperSubject.MARK_DESCRIPTION
};
int[] b = new int[]{
R.id.list_mark_id,
R.id.list_mark_name,
R.id.list_mark_type,
R.id.list_mark_mark,
R.id.list_mark_description
};
SimpleCursorAdapter adapterM = new SimpleCursorAdapter(
AddMark.this, R.layout.row_format_list_mark, cursorM, a, b);
adapterM.notifyDataSetChanged();
list.setAdapter(adapterM);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
tv_listmarkId = (TextView) view.findViewById(R.id.list_mark_id);
tv_listmarkName = (TextView) view.findViewById(R.id.list_mark_name);
tv_listmarkType = (TextView) view.findViewById(R.id.list_mark_type);
tv_listmarkMark = (TextView) view.findViewById(R.id.list_mark_mark);
tv_listmarkDescription = (TextView) view.findViewById(R.id.list_mark_description);
String listmarkId = tv_listmarkId.getText().toString();
String listmarkName = tv_listmarkName.getText().toString();
String listmarkType = tv_listmarkType.getText().toString();
String listmarkMark = tv_listmarkMark.getText().toString();
String listmarkDescription = tv_listmarkDescription.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), UpdateMark.class);
modify_intent.putExtra("listmarkId", listmarkId);
modify_intent.putExtra("listmarkName", listmarkName);
modify_intent.putExtra("listmarkType", listmarkType);
modify_intent.putExtra("listmarkMark", listmarkMark);
modify_intent.putExtra("listmarkDescription", listmarkDescription);
startActivity(modify_intent);
}
});
}
}
Desired outcome: when a user selects a subject called "Math", it should show all the math marks in list view according to the mark_name.
When the user chooses nothing, it should leave it blank.
Begin by creating an inner class that implements AdapterView.OnItemSelectedListener. Override it's two methods:
onItemSelected( )
Callback method to be invoked when an item in this
view has been selected.
onNothingSelected( )
Callback method to be invoked when the selection disappears from this view.
Now, set an object of this class as the listener on your spinner. Something like:
spinner.setOnItemSelectedListener( new MyItemSelectedListener() );
Now go back and provide a proper definition to those two methods.

fetching value from database and setting it in android spinner

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);
}

Categories