Store seekbar values in array - android

I want to store seek bar values that user selects by dragging thumb, in an array

You can do something like this:
private ArrayList<Seekbar> mSeekbars = new ArrayList<Seekbar>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// Your code where you set the content view
mSeekbars.add(((Seekbar) findViewById(R.id.seekbar1));
mSeekbars.add(((Seekbar) findViewById(R.id.seekbar2));
mSeekbars.add(((Seekbar) findViewById(R.id.seekbar3));
}
// To enable seekbars
private void onRadioButtonSelected() {
for (Seekbar seekbar : mSeekbars) {
seekbar.setEnabled(true);
}
}
// To get seekbar values
private ArrayList<Integer> saveSeekbarValues() {
ArrayList<Integer> values = new ArrayList<Integer>();
for (Seekbar seekbar : mSeekbars) {
values.add(seekbar.getProgress())
}
return values;
}
}
One other solution is to have a parent layout that holds all seekbars and enable/disable that layout instead of enabling/disable the individual seekbars. However, for the values, you will have to manually retrieve each seekbar's value.

You can put all seekbars in single view and get one by one child using iteration, and setEnable() them:-
// to enable seekbars
public void enableAllSeekBars()
{
int childcount = containerView.getChildCount();
for (int i=0; i < childcount; i++){
if(containerView.getChildAt(i) instanceof SeekBar)
{
SeekBar sb = (SeekBar)containerView.getChildAt(i);
sb.setEnabled(true);
}
}
}
// to get seekbar values
public ArrayList<Integer> getSeekBarValues()
{
ArrayList<Integer> values = new ArrayList<Integer>();
int childcount = containerView.getChildCount();
for (int i=0; i < childcount; i++){
if(containerView.getChildAt(i) instanceof SeekBar)
{
SeekBar sb = (SeekBar)containerView.getChildAt(i);
values.add(sb.getProgress())
}
}
return values;
}

Related

Assign listener at onCreate time to subviews of dynamic loaded ListView items

I have a ListView managed by an ArrayList/ArrayAdapter.
The ListView item is defined in an XML layout file.
At initialisation time (onCreate) I load the ListView with a variable number of items and, at that moment, I need to assign a listener to one subview (a SeekBar) of each item.
This is the relevant part of the code:
private String TAG = "MainActivity";
private ListView lv_controlli;
private ArrayAdapter<String> adapter;
private LinkedHashMap<String, String> hmControlli;
private ArrayList<String> controlli;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
private void Init() {
lv_controlli = (ListView) findViewById(R.id.LV_Controls);
hmControlli = new LinkedHashMap<String, String>();
for (int i = 0; i < 6; i++) hmControlli.put(String.valueOf(i), "Gruppo " + i);
controlli = new ArrayList<String>(hmControlli.keySet());
adapter = new ArrayAdapter<String>(this, R.layout.control_layout, R.id.LBL_Controllo, controlli);
lv_controlli.setAdapter(adapter);
for (int i = 0; i < lv_controlli.getChildCount(); i++) {
SeekBar sb = (SeekBar) lv_controlli.getChildAt(i).findViewById(R.id.SB_Intensita);
sb.setOnSeekBarChangeListener(valueOnChange);
}
}
private SeekBar.OnSeekBarChangeListener valueOnChange = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.i(TAG,String.valueOf(seekBar.getProgress()));
}
...
};
public void click(View view) {
for (int i = 0; i < lv_controlli.getChildCount(); i++) {
SeekBar sb = (SeekBar) lv_controlli.getChildAt(i).findViewById(R.id.SB_Intensita);
sb.setOnSeekBarChangeListener(valueOnChange);
}
}
No listeners are assigned by Init() routine (called by onCreate()) because its execution happens when the ListView has not been already loaded, even though the adapter as been populated and assigned to the ListView.
The same kind of code works perfectly, instead, in the click() routine associated to a button that I press when the control is returned to the user.
So I can get the SeekBars actually usable only after my interaction and this is bad, of course.
Is there any point where the populated ListView is available before the control is returned to the user?
Thanks a lot in advance for your help.
Chances are good that the right way to solve this problem is not by trying to find a moment in time between onCreate() and when control of the app passes to the user, but by assigning your OnSeekBarChangeListener to the SeekBar inside your adapter.
You can create a subclass of ArrayAdapter that you use instead of the base ArrayAdapter implementation, then override getView() to add the listener. Something like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
SeekBar seekBar = (SeekBar) v.findViewById(R.id.SB_Intensita);
seekBar.setOnSeekBarChangeListener(valueOnChange);
return v;
}

Android: Save the activity state after a screen rotation

we are working on project in order to create an application to help autits to communicate.
In fact, after moving the ImageViews, all of them are getting back in place after my tablet's rotation.
We tried a lot of things and we finally have made this code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.repas);
area1 = (LinearLayout) findViewById(R.id.area1);
area2 = (LinearLayout) findViewById(R.id.area2);
TypedArray arrayResources = getResources().obtainTypedArray(
R.array.resicon);
if( savedInstanceState != null ) {
int count_item = savedInstanceState.getInt("number_of_item");
int tab_item[] = new int[count_item];
for (int i = 0; i < count_item; i++) {
tab_item[i]=savedInstanceState.getInt("Sauvegarde_repas" +i);
}
for (int i = 0; i < arrayResources.length(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageDrawable(arrayResources.getDrawable(i));
imageView.setOnTouchListener(myOnTouchListener);
imageView.setId(i);
if (check(tab_item,i)){
area1.addView(imageView);
}
else{
area2.addView(imageView);
}
}
}
else {
for (int i = 0; i < arrayResources.length(); i++) {
ImageView imageView = new ImageView(this);
imageView.setImageDrawable(arrayResources.getDrawable(i));
imageView.setOnTouchListener(myOnTouchListener);
imageView.setId(i);
area2.addView(imageView);
}
arrayResources.recycle();
}
area1.setOnDragListener(myOnDragListener);
area2.setOnDragListener(myOnDragListener);
}
#Override
public void onSaveInstanceState(Bundle outState)
{
int count = area1.getChildCount();
View v = null;
outState.putInt("number_of_item", count);
for(int i=0; i<count; i++) {
v = area1.getChildAt(i);
outState.putInt("Sauvegarde_repas" + i, v.getId());
}
super.onSaveInstanceState(outState);
}
Here are my interrogations:
When I set an id, it's just "i", a very simple number. It doesn't seem very unique like a string "R.id.String_here" (even if I know that is converted in Integer), so how can I be sure to do a unique ID?
Do I have to save, one by one, the child of my layout? It's not possible to save the whole layout?
Do you have any advice to improve my code? (Because it looks dirty, isn't it ?)
Thank you very much for your help !

Creating a TextView for the first 46 Fibonacci numbers on Android

I have this so far, and the result is a blank screen. What might I do to achieve the desired effect of listing the first 46 Fibonacci numbers?
TextView fibNum;
static int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static int fib(int n) {
int prev1=0, prev2=1;
for( i=0; i<n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
public void main(String[] args) {
for (int i=0; i<=46; i++)
fibNum = new TextView(this);
fibNum.setText(String.valueOf(fib(i)+", "));
}
}
First, just creating a TextView doesn't make it part of the view hierarchy being displayed. Second, Android will never call your main method. Third, I don't see how your code even compiles; the loop inside main only covers the assignment to fibNum, so at the call to setText, the variable i is not even in scope.
Putting all that aside, let's assume your activity_main.xml layout file already has a TextView in it with id #+id/text where you want to display the numbers. I suggest something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.text);
text.setText(getFib(46));
}
public static int fib(int n) {
int prev1 = 0, prev2 = 1;
for(int i = 0; i < n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
public static String getFib(int n) {
StringBuilder sb = new StringBuilder(fib(0));
for (int i = 1; i < n; ++i) {
sb.append(", ");
sb.append(fib(i));
}
return sb.toString();
}
This assumes that calculating 46 Fibonacci numbers doesn't take an inordinate amount of time. If it does, you'll have to move the calculation to a worker thread (probably easiest to do using an AsyncTask).

How to save multiple values in SQLite Database in Android?

I have a textView which is a DropDownList. Under this textview, there will be multiple options with checkboxes beside it. The User can choose one or more from the options.
I include my code for this dropdownlist and how did I populate it with my array.
MainActivity.java
private void initializeCustomerSegment()
{
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment){
//display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag==1)
tv_ConsumerSegment.setText(selected);
expandedConsumerSegment =true;
}
else{
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment){
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
I also have this line of code in order for me to save the data...
String cSegment = checkSelected.toString();
Cursor rcSegment = databaseHandler.getReport_SubBrandCode(subBrand);
String SubBrandCode = rcSegment.getString(rcSegment.getColumnIndex(Constants.CONSUMERSEGMENT_CODE));
My question is, how can I save those multiple data in a single column in SQLite?
first, you need to get the value of the selected item on your multi select spinner. Try this:
ArrayList<String> content = new ArrayList<String>();
for (int j = 0; j < checkSelected.length; j++)
{
if(checkSelected[j]==true)
{
String values = BrandListAdapter.mListItems.get(j);
content.add(values);
}
}
Toast.makeText(getApplicationContext(), content.toString(), Toast.LENGTH_SHORT).show();
I toast the arraylist content just to check if it really contains the value I select. Then when you see the right value on your toast then you could save it on your database. Hope it helps! charot :D

After filter a listview,how can I obtain the position of the first listview?

After filter a listview,how can I obtain the position of the first listview?
I use simpleadapter to fill the listview.
Each item in the datasource has its own id,and I use "case" to redirect them.
After I filter the listview ,I don't know how to associate the latter items with the first listview.The postion and id have changed.
Thank you.
I use the afterTextChanged of EditTextView to filter the listview and notify it.
#Override
public void afterTextChanged(Editable paramEditable) {
listItemsCopy.clear();
int count=simpleAdapter.getCount();
if ((count>0 )&&paramEditable.length()>0) {
for (int i = 0; i < simpleAdapter.getCount(); i++) {
Map<String,Object> tempMap=(Map<String,Object>)simpleAdapter.getItem(i);
String itemName=tempMap.get("name").toString();
HashMap<String, Object> tempHashMap=new HashMap<String, Object>();
int copyCount=0;
if(itemName.toLowerCase().contains(paramEditable.toString().toLowerCase())){
tempHashMap=(HashMap<String, Object>)simpleAdapter.getItem(i);
listItemsCopy.add(tempHashMap);
copyCount++;
}
}
if(listItemsCopy!=null){
Handler handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
simpleAdaptercopy = new SimpleAdapter(getActivity(),
listItemsCopy, R.layout.right_menu_list_view, new String[] {
"name", "id", "image" }, new int[] {
R.id.rightMenuListViewTextView1,
R.id.rightMenuListViewTextView2,
R.id.rightMenuListViewImageView1 });
simpleAdapter.setViewBinder(new ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
if ((view instanceof ImageView && data instanceof Bitmap)) {
ImageView iv = (ImageView) view;
iv.setImageBitmap((Bitmap) data);
return true;
} else {
return false;
}
}
});
listView.setAdapter(simpleAdaptercopy);
simpleAdapter.notifyDataSetChanged();
}
}, 1000);
}
}
else {
listView.setAdapter(simpleAdapter);
simpleAdapter.notifyDataSetChanged();
}
}
Then I want to use the method onItemClick of listview to redirect different Intent.As the datasource has changed,both position and id are different from which I want
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = null;
switch (position) {}`
I slove it with three arrays. Only test code:
String positionString[]=new String[22];
int latterPosition[]=new int[22];
for (int i = 0; i < latterPosition.length; i++) {
positionString[i]="";
latterPosition[i]=0;
}
int latterCount=0;
for (int i = 0; i < positions.length; i++) {
if (positions[i]==10) {
positionString[latterCount]=i+"";
latterPosition[latterCount]=10;
latterCount++;
}
}
this happens becouse Android gives you only IDs for the itmes you currently see + maybe two hidden on button and two hidden on top.
In this tutorial you can see how to create a ListView with a model, this helps me, when i got this problem before. Add this to you code and change it (I think you don't need the checkboxes).

Categories

Resources