I need to set the open_time string value to spinner.In previous
activity I'm getting the response as string.
then I passed that string value to bundle from FirstActivity to
SecondActivity.
Coding :
SecondActivity.java:
String open_time;
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
open_time = bundle.getString("open_time");
}
My only problem is ,While entering into SecondActivity the open_time
String value have to set into Spinner.Anyone help me with this.
Edit: I have tried fromSpinner.setPrompt(open_time); .But that doesn't worked for me.
Android Spinners need adapters. So you should prepare a simple adapter for them.
String[] list = new String[] {open_time};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
staticSpinner.setAdapter(adapter);
I solved it by using this below code:
int s3;
s3 = fromSpinnerAdapter.getPosition(open_time);
fromSpinner.setSelection(s3);
Try this code
private ArrayList<String> list;
private int selectedItem = -1;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
staticSpinner.setAdapter(adapter);
staticSpinner.setOnItemSelectedListener(this);
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Spinner selectedSpinner = (Spinner) adapterView;
switch (selectedSpinner.getId()) {
case R.id.sp_actions:
String row_data = sp_actions.getSelectedItem();
Log.d(TAG, "" + row_data);
// pass these variable to new activity and call setSelected method
selectedItem = list.indexOf(row_data);
break;
}
}
Related
I want to get information using putExtra() on another page and I can do it, but my only problem is always the default value the first value sample_array but i want to by default classDayIntent value is displayed in spinner
tip: The putExtra() received in Spinner is there
First Activity:
Intent intent = new Intent();
intent.putExtra("className" , className);
intent.putExtra("uniName" , uniName);
intent.putExtra("classDay" , classDay);
intent.setClass(context , AddNewClass.class);
context.startActivity(intent);
Second Activity:
Spinner spinner = (Spinner)findViewById(R.id.spinnerDay);
String className = getIntent().getStringExtra("className");
String uniName = getIntent().getStringExtra("uniName");
String classDayInent = getIntent().getStringExtra("classDay"); // How To Display classDayInent In Spinner....
className_EditeText.setText(className);
uniName_EditeText.setText(uniName);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this , R.array.sample_array , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String classDay = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Strings:
<resources>
<string name="app_name">ClassManager</string>
<string-array name="sample_array">
<item>شنبه</item>
<item>یکشنبه</item>
<item>دوشنبه</item>
<item>سه شنبه</item>
<item>چهارشنبه</item>
<item>پنجشنبه</item>
<item>جمعه</item>
</string-array>
you can use add function of adapter.
since CharSequence is an interface, and the String class implements CharSequence so you can directly add string to adapter
adapter.add(classDayInent);
spinner.setAdapter(adapter);
Another issue is , createFromResources creates a immutable list mean it cannot add more items.
Solution : create your own adapter with mutable list
List<String> list = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this , android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
list.add(0,classDayIntent);// to add received element at first position to display
spinner.setAdapter(adapter);
You can get your xml arraylist and then add to that:
List<String> ar = new LinkedList<String>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ar.add("test");
i found correct answer :
String classDayInent = getIntent().getStringExtra("classDay");
List<String> list = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this , android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
//find classDayIntent from List For get Position To Display
for (int i = 0; i < list.size(); i++)
{
if (classDayIntent.equals(list.get(i)))
{
spinner.setSelection(i);
}
}
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
classDay = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method
I am working on EditText and Spinner . When I set text for EditText it were fine but when I try to set text for Spinner it give error.
this is code for set text EditText
New_Name.setText(NewName);
here New_Name is EditText
this is code for set text Spinner
New_Quantity.setText(NewQuantity);
here New_Quantity is Spinner
this is the full code.
public class UpdateFoodActivity extends Activity {
EditText Name_Search,New_Name,New_Calorie,New_Fat,New_Protein,New_Sugar,New_carbohydrates;
Spinner New_Quantity;
TextView title_text;
String SearchName,NewName,NewQuantity,NewCalorie,NewFat,NewProtein,NewSugar,Newcarbohydrates;
FoodDbHelper foodDbHelper;
SQLiteDatabase sqLiteDatabase;
Button UpdateButton;
ArrayAdapter<CharSequence> adapter;
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.update_food_activity);
Name_Search = (EditText)findViewById(R.id.name_search);
New_Name = (EditText)findViewById(R.id.new_name);
New_Quantity = (Spinner)findViewById(R.id.new_quantity);
adapter = ArrayAdapter.createFromResource(this, R.array.quant, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
New_Quantity.setAdapter(adapter);
New_Quantity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
New_Calorie = (EditText)findViewById(R.id.new_calorie);
New_Fat = (EditText)findViewById(R.id.new_fat);
New_Protein = (EditText)findViewById(R.id.new_protein);
New_Sugar = (EditText)findViewById(R.id.new_sugar);
New_carbohydrates = (EditText)findViewById(R.id.new_vitamins);
UpdateButton = (Button)findViewById(R.id.update_button);
title_text = (TextView)findViewById(R.id.title_text);
New_Name.setVisibility(View.GONE);
New_Quantity.setVisibility(View.GONE);
New_Calorie.setVisibility(View.GONE);
New_Fat.setVisibility(View.GONE);
New_Protein.setVisibility(View.GONE);
New_Sugar.setVisibility(View.GONE);
New_carbohydrates.setVisibility(View.GONE);
UpdateButton.setVisibility(View.GONE);
title_text.setVisibility(View.GONE);
}
public void searchFood(View view){
SearchName = Name_Search.getText().toString();
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
Cursor cursor = foodDbHelper.getFood(SearchName,sqLiteDatabase);
if (cursor.moveToFirst()) {
NewQuantity = cursor.getString(0);
NewCalorie = cursor.getString(1);
NewFat = cursor.getString(2);
NewProtein = cursor.getString(3);
NewSugar = cursor.getString(4);
Newcarbohydrates = cursor.getString(5);
NewName = SearchName;
New_Name.setText(NewName);
New_Quantity.setText(NewQuantity);
New_Calorie.setText(NewCalorie);
New_Fat.setText(NewFat);
New_Protein.setText(NewProtein);
New_Sugar.setText(NewSugar);
New_carbohydrates.setText(Newcarbohydrates);
New_Name.setVisibility(View.VISIBLE);
New_Quantity.setVisibility(View.VISIBLE);
New_Calorie.setVisibility(View.VISIBLE);
New_Fat.setVisibility(View.VISIBLE);
New_Protein.setVisibility(View.VISIBLE);
New_Sugar.setVisibility(View.VISIBLE);
New_carbohydrates.setVisibility(View.VISIBLE);
UpdateButton.setVisibility(View.VISIBLE);
title_text.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),
"No Dish Found " ,
Toast.LENGTH_SHORT).show();
}
}
public void updatebutton(View view)
{
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getWritableDatabase();
String name,quantity,calorie,fat,protein,sugar,carbohydrates;
name = New_Name.getText().toString();
quantity = New_Quantity.getSelectedItem().toString();
calorie = New_Calorie.getText().toString();
fat = New_Fat.getText().toString();
protein = New_Protein.getText().toString();
sugar = New_Sugar.getText().toString();
carbohydrates = New_carbohydrates.getText().toString();
int count = foodDbHelper.updateInformation(SearchName,name,quantity,calorie,fat,protein,sugar,carbohydrates,sqLiteDatabase);
Toast.makeText(getApplicationContext(),count+" dish updated",Toast.LENGTH_LONG).show();
Intent intent = new Intent(this,UpdateFoodActivity.class);
startActivity(intent);
}
}
In order to add entries to the spinner you need to define an Adapter i give you an example:
spinner = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.spinner_item, list);
spinner.setAdapter(dataAdapter);
Spinner likes ListView, need an adapter for rendering data. Adapter, in simple term, is a collection of items. (As you see ListView always contains list of item and also Spinner). Nevertheless, Adapter of spinner often a list of string. (because spinner just represents user choice)
In your example, You can simply create ArrayAdapter and assign again to Spinner.
private void setTextForSpinner(Spinner spinner) {
String[] items = {"Stack", "Over", "Flow"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
}
If apply above code to your example, you can change again to:
private void setTextForSpinner(Spinner spinner, String NewName) {
String[] items = {NewName};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
}
Hope this help :)
i have on my Activity1 a ListView with 10 items. Based on which item i click, i want to pass just a part of a StringArray to my next Activity. I want to bind passed StringArray over an ArrayAdapter to a GridView.
First Problem:
I don´t understand how can i pass something in the next Activity, DEPENDING on the clicked item in the ListView of my Activity1
Second Problem:
How can i get just parts of my StringArray. My String Array has 200 items. Now i want to pass (depending on itemclick in Activity1) just the items i really need.
Here is my code
public class MainActivity extends Activity {
// ListView items
String[] provinces = new String[]{
"Prozentrechnung, Terme und Brüche",
"Gleichungen",
"Ungleichungen und Beträge",
"Geraden, Parabeln und Kreise",
"Trigonometrie",
"Potenzen, Wurzeln und Polynome",
"Exponentialfunktionen und Logarithmen",
"Trigonometrische Funktionen",
"Differenzialrechnung",
"Integralrechnung"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView provincelist = (ListView)findViewById(R.id.lvProvinceNames);
//add header to listview
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.listheader, provincelist, false);
provincelist.addHeaderView(header, null, false);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, provinces);
provincelist.setAdapter(adapter);
provincelist.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
//we use the items of the listview as title of the next activity
String province = provinces[position-1];
//we retrieve the description of the juices from an array defined in arrays.xml
String[] provincedescription = getResources().getStringArray(R.array.provincedescription);
//List<String> aufgabenListe = new ArrayList<String>(Arrays.asList(provincedescription));
//final String provincedesclabel = provincedescription[position-1];
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("position",position);
intent.putExtra("province", province); //aktualisieren der Titel in der DetailActivity
intent.putExtra("provincedescription", provincedescription); //befüllen der GridView
startActivity(intent);
}
});
}
}
Here is the Activity2 where i have to bind my items to a GridView.
public class DetailActivity extends Activity {
String title;
String[] array;
int position;
//int image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detailactivity);
TextView tvTitleLabel = (TextView)findViewById(R.id.tvTitleLabel);
GridView gridView = (GridView) findViewById(R.id.gridView);
ArrayAdapter<String> adapter;
Bundle extras = getIntent().getExtras();
position = extras.getInt("position");
if (extras != null) {
title = extras.getString("province");
tvTitleLabel.setText(title);
/////Fehlermeldung: array = null --> NullPointerException
array = extras.getStringArray("provincedescription");
gridView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
}
});
//adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);
//gridView.setAdapter(adapter);
}
}
}
UPDATE: Here is my string array
<string-array name="provincedescription">
<item>A1.1</item>
<item>A1.2</item>
<item>A1.3</item>
<item>A1.4</item>
<item>A1.5</item>
<item>A1.6</item>
<item>A1.7</item>
<item>A1.8</item>
<item>A1.9</item>
<item>A1.10</item>
<item>A1.11</item>
<item>A1.12</item>
<item>A1.13</item>
<item>A1.13</item>
<item>A1.14</item>
<item>A2.1</item>
<item>A2.2</item>
<item>A2.3</item>
<item>A2.4</item>
<item>A2.5</item>
<item>A2.6</item>
<item>A2.7</item>
<item>A2.8</item>
<item>A2.9</item>
<item>A2.10</item>
<item>A2.11</item>
<item>A2.12</item>
<item>A3.1</item>
<item>A3.2</item>
<item>A3.3</item>
<item>A3.4</item>
<item>A3.5</item>
<item>A3.6</item>
<item>A3.7</item>
<item>A3.8</item>
<item>A3.9</item>
<item>A3.10</item>
<item>A3.11</item>
<item>A3.12</item>
</string-array>
if I understand what you want maybe you should take a look at Singleton, I use and works great for now
https://gist.github.com/Akayh/5566992
Credits: https://stackoverflow.com/a/16518088/3714926
For resources like yours that are fixed its better to use string-array in your xml file. From Java I prefer to use static array in your case. Heres a sample:
public class Constants {
public static final String[] provinces = new String[] {
"Prozentrechnung, Terme und Brüche", "Gleichungen",
"Ungleichungen und Beträge", "Geraden, Parabeln und Kreise",
"Trigonometrie", "Potenzen, Wurzeln und Polynome",
"Exponentialfunktionen und Logarithmen",
"Trigonometrische Funktionen", "Differenzialrechnung",
"Integralrechnung" };
}
Then I can access the provinces from anywhere from my class like this:
String iWant = Constants.provinces[0];
Very Important Note
Static objects are dangerous in a number of scenarios and they are usually present in memory so use them sparingly.
As for the string array you cannot get a single element directly from the string-array defined in xml. For that you need to first get all the elements from the array:
Resources res = getResources();
String[] planets = res.getStringArray(R.array.provincedescription);
I want to show the value of spinner in string instead of integer. Right now it is showing integer like '0','1'.
Setting activity:
public class Setting extends Activity {
bloodtype = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,getResources().getStringArray(R.array.blood_groups_arrays));
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bloodtype.setAdapter(adapter2);
bloodtype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item is selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
sharedpreferences.edit().putString(BloodType, parent.getItemAtPosition(position).toString()).commit();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
if(sharedpreferences.contains(BloodType)) {
bloodtype.setSelection(sharedpreferences.getString(BloodType, "DEFAULT"));
}
}
Calling its value in main activity:
if(sharedpreferences.contains(Setting.BloodType)) {
show.setText(""+sharedpreferences.getString(Setting.BloodType, "DEFAULT"));
}
In order to store a value of array you populated your spinner with in SharedPreferences use the following line in onItemSelected() method:
sharedpreferences.edit().putString(BloodType, parent.getItemAtPosition(position).toString()).commit();
Note: BloodType has to be of String type, because it plays a role of a key in key-value pair of SharedPreferences.
Taken from my working project it should work:
adapterSpinner = new ArrayAdapter<String>(yourContenxt,
android.R.layout.simple_list_item_1, yourDataSource);
spinnerProfileType.setAdapter(adapterSpinner);
As you are using a string array you can set the spinner items in xml too by using:
android:entries = "#array/your_string_entry"