How retrieve selected from preferenceActivity - preferenceactivity

(Android 2.2)
I'm trying to retrieve a value set in a PreferenceActivity. Although the value is correctly stored/recalled by the activity itself, I cannot figure out how to retrieve the set value by myself (to show it in a textView for instance). This code doesn't give an error however the value 0 is shown in textView1 in Spel.java instead of the actual / current value in PrefsManager prefs (in NumberPickerPreferenceActivity).
How to make the correct value show in textView1 there?
Also: onSharedPreferenceChanged (in NumberPickerPreferenceActivity) doesn't show a toast messsage (nothing pops up, nothing is logged). What is wrong, how to solve?
Here's class NumberPickerPreferenceActivity:
package mypackage.tabnavui;
import mypackage.R;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class NumberPickerPreferenceActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
private static final String TAG = NumberPickerPreferenceActivity.class.getSimpleName();
private SharedPreferences prefs;
public static int aantalBanen;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesMode(MODE_PRIVATE);
preferenceManager.setSharedPreferencesName("numberPicker.preferences");
addPreferencesFromResource(R.xml.preferences);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
public int prefsAantalBanen() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
return prefs.getInt( "AANTAL_BANEN", 0 );
}
public int getAantalBanen() {
aantalBanen = prefsAantalBanen();
return aantalBanen;
}
#Override
protected void onResume() {
super.onResume();
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
prefs.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
int selectedNumber = prefsAantalBanen();
Log.d(TAG, "Number selected: " + selectedNumber);
Toast t = Toast.makeText(this, "Number selected: " + selectedNumber, Toast.LENGTH_SHORT);
t.show();
}
}
Here's Spel.java where I want to show the value as selected / stored in the ReferenceActivity, see method toonClickHandler:
package mypackage.tabnavui;
import mypackage.tabnavui.R;
import mypackage.Controls2.MyGestureDetector;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.AbsListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Spel extends Activity implements NumberPickerDialog.OnNumberSetListener {
private static final String TAG = Spel.class.getSimpleName();
private GestureDetector gestureDetector;
private TextView textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gestureDetector = new GestureDetector(new MyGestureDetector());
// Use a custom layout file
setContentView(R.layout.spel);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sample_picker, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_dialog_item) {
NumberPickerDialog dialog = new NumberPickerDialog(this, -1, 2);
dialog.setTitle(getString(R.string.dialog_picker_title));
dialog.setOnNumberSetListener(this);
dialog.show();
return true;
} else if (item.getItemId() == R.id.menu_preferences_item) {
startActivity(new Intent(this, NumberPickerPreferenceActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void toonClickHandler(View v) {
textView1 = (TextView) this.findViewById(R.id.textView1);
int aantalBanen = NumberPickerPreferenceActivity.aantalBanen;
textView1.setText(String.valueOf(aantalBanen));
}
public void onNumberSet(int number) {
Log.d(TAG, "Number selected: " + number);
Toast t = Toast.makeText(this, "Number selected: " + number, Toast.LENGTH_SHORT);
t.show();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
class MyGestureDetector extends SimpleOnGestureListener {
private static final int SWIPE_MAX_OFF_PATH = 200;
private static final int SWIPE_MIN_DISTANCE = 50;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
#Override
public boolean onDown (MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// left to right swipe and right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
// left swipe
Toast t = Toast.makeText(Spel.this, "Left swipe", Toast.LENGTH_LONG);
t.show();
// startActivity(Tabs3.tab3);
startActivityForResult(Tabs3.tab3, 500);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
return true;
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
// right swipe
Toast t = Toast.makeText(Spel.this, "Right swipe", Toast.LENGTH_LONG);
t.show();
// startActivity(Tabs3.tab1);
startActivityForResult(Tabs3.tab1, 500);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
return true;
}
return false;
}
}
}
and preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:picker="http://schemas.android.com/apk/res/mypackage.tabnavui"
xmlns:android="http://schemas.android.com/apk/res/android">
<nl.computerhuys.tabnavui.NumberPickerPreference
android:key="AANTAL_BANEN"
android:title="Aantal banen"
android:summary="Number picker as a preference"
picker:defaultValue="2"
picker:startRange="0"
picker:endRange="12" />
</PreferenceScreen>

Found it here: How do I get the SharedPreferences from a PreferenceActivity in Android?
in NumberPickerReferenceActivity: replace
preferenceManager.setSharedPreferencesMode(MODE_PRIVATE);
by
preferenceManager.setSharedPreferencesMode(MODE_WORLD_READABLE);
and replace
prefs = PreferenceManager.getDefaultSharedPreferences(this);
by
prefs = getSharedPreferences("numberPicker.preferences", MODE_WORLD_READABLE);
to make the toast and log work
and in Spel:
int aantalBanen = getSharedPreferences("numberPicker.preferences", MODE_WORLD_READABLE).getInt( "AANTAL_BANEN", 0 );
textView1.setText(String.valueOf(aantalBanen));
to show stored value in textView1

Related

Showing contact from the contact loader Manager

I am showing the contact list from the contact table but not able to get the phone number using the same on RecyclerView.My code is -
package com.oodles.oodlesapprtc;
import android.annotation.SuppressLint;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by ankita on 13/4/17.
*/
public class LoginUserActivity extends AppCompatActivity {
public static final int CONTACT_LOADER_ID = 78;
RecyclerView loginUserRecycler;
ArrayList<ContactBeans> contactBeanses;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +
" COLLATE LOCALIZED ASC";
private static final String[] PROJECTION2 = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.PHOTO_URI,ContactsContract.Contacts.HAS_PHONE_NUMBER
};
private static final String[] PROJECTION3 = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.PHOTO_URI, ContactsContract.Contacts.LOOKUP_KEY
};
private static final String[] PROJECTION = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY, ContactsContract.CommonDataKinds.Phone.NUMBER
};
// private static final String[] PROJECTION1 = {
// ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
// ContactsContract.CommonDataKinds.Phone.NUMBER
// };
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user_activity);
initViews();
}
private void initViews() {
getLoaderManager().initLoader(0, null, contactLoaderManager);
initRecycler();
}
private void initRecycler() {
loginUserRecycler = (RecyclerView) findViewById(R.id.loginUserRecycler);
loginUserRecycler.setLayoutManager(new LinearLayoutManager(this));
loginUserRecycler.setItemAnimator(new DefaultItemAnimator());
}
LoaderManager.LoaderCallbacks<Cursor> contactLoaderManager = new LoaderManager.LoaderCallbacks<Cursor>() {
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// String[] projectionFields = new String[]{ContactsContract.Contacts._ID,
// ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.PhoneLookup.NORMALIZED_NUMBER,
// ContactsContract.Contacts.PHOTO_URI};
// Construct the loader
// Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
// ContactsContract.Contacts.CONTENT_URI
// Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
// Uri.encode(phoneNumber));
CursorLoader cursorLoader = new CursorLoader(LoginUserActivity.this,
ContactsContract.Contacts.CONTENT_URI, // URI
PROJECTION2, // projection fields
null, // the selection criteria
null, // the selection args
sortOrder // the sort order
);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
loginUserRecycler.setAdapter(new CursorRecyclerAdapter(LoginUserActivity.this, data));
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
};
}
My Adapter is -
package com.oodles.oodlesapprtc;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by ankita on 13/4/17.
*/
public class CursorRecyclerAdapter extends RecyclerView.Adapter<ContactViewHolder> {
private Cursor mCursor;
private final int mNameColIdx,
mIdColIdx;
int phoneNumber;
int hasPhoneNumber;
private Context mContext;
public CursorRecyclerAdapter(Context context, Cursor cursor) {
mCursor = cursor;
this.mContext = context;
mNameColIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY);
mIdColIdx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
hasPhoneNumber = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int pos) {
View listItemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.contact_row, parent, false);
return new ContactViewHolder(listItemView);
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int pos) {
mCursor.moveToPosition(pos);
String contactName = mCursor.getString(mNameColIdx);
long contactId = mCursor.getLong(mIdColIdx);
Contact c = new Contact();
Log.e("ddhdhdhhdhdhdhd",hasPhoneNumber+"");
c.name = contactName;
c.number = getPhoneNumberFromContactId(contactId);
c.profilePic = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
getPhoneNumberFromContactId(contactId);
contactViewHolder.bind(c);
}
private String getPhoneNumberFromContactId(long contactId) {
String contactNumber = "8874675724";
return contactNumber;
}
#Override
public int getItemCount() {
return mCursor.getCount();
}
}
How can I get the phone number for the same i am getting a cursorindexoutofbound exception and has phone number value as 3 but it can be only 0 or 1 why it is 3 i don't understand this.
Can Anyone please explain this to me also please explain how the contact fetch works
You have a few issues in the code:
You're querying on the Contacts table, but sorting using a CommonDataKinds.Phone table field, that's not good, you can sort using Contacts.DISPLAY_NAME_PRIMARY instead.
cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER) gives you a column index, not the value of the field, that's why you're getting 3 (it's the 4rd field defined in PROJECTION2), change hasPhoneNumber to mHasPhoneNumberIdx to avoid confusion.
add hasPhoneNumber = mCursor.getInt(mHasPhoneNumberIdx); to your onBindViewHolder method, to get the actual value.
Running a long command like a real implementation of getPhoneNumberFromContactId within onBindViewHolder is really bad... you should change your main query so you do two big queries, one for all contacts, one for all phones, and then use some HashMap to get a phone using a contact-id.

ActionBarActivity with fragment and Tab Bar how to implement it

As you see my Code, it dont have error when run debug, I put the tabhost into my fragment, but when app run. It dont show the tabhost
package com.example.phamxuanson.myapplication;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
mTitle = getTitle();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
Please see my piuctures
i.imgur.com/AuPA4GO.png
i.imgur.com/Vlrxuhz.png
i.imgur.com/or8m6Mj.png
Why wasn’t tabhost shown?

The operator - under defined for the arguement type(s) EditText, int

Im trying to create an activity which adds name, age, and maxhr to sqlite and will be displayed in a listview in Eclipse. name and age is an input text. Maxhr is age(input text) minus 220. But im getting "The operator - under defined for the arguement type(s) EditText, int" error. I can't seem to find the answer for this error. Does anyone know how to fix it?
package com.heartrate.monitoring.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.heartratemonitoringapp.R;
import com.heartrate.monitoring.dao.UserDAO;
import com.heartrate.monitoring.model.User;
public class AddUserActivity extends Activity implements OnClickListener {
public static final String TAG = "AddUserActivity";
private EditText mTxtName;
private EditText mTxtAge;
private Button mBtnAdd;
private UserDAO mUserDao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
getActionBar().setDisplayHomeAsUpEnabled(true);
initViews();
this.mUserDao = new UserDAO(this);
}
private void initViews() {
this.mTxtName = (EditText) findViewById(R.id.txt_name);
this.mTxtAge = (EditText) findViewById(R.id.txt_age);
this.mBtnAdd = (Button) findViewById(R.id.btn_add);
this.mBtnAdd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Editable name = mTxtName.getText();
Editable age = mTxtAge.getText();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(age)){
// add the user to database
double mhr;
double maxhr;
mhr = Double.parseDouble(mTxtAge.getText().toString());;
maxhr = mhr - 220;
User createdUser = mUserDao.createUser(
name.toString(), age.toString(),
maxhr.toString());
Log.d(TAG, "added user : "+ createdUser.getName());
Intent intent = new Intent();
intent.putExtra(ListUserActivity.EXTRA_ADDED_USER, createdUser);
setResult(RESULT_OK, intent);
Toast.makeText(this, R.string.user_created_successfully, Toast.LENGTH_LONG).show();
finish();
}
else {
Toast.makeText(this, R.string.empty_fields_message, Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mUserDao.close();
}
}
Remove the extra ; on this line: mhr = Double.parseDouble(mTxtAge.getText().toString());;

Preference activity seekbar

I have created a custom android seek bar from lukehorvat tutorial
and added to my preference xml file as below
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto" >
<PreferenceCategory
android:title="Color RGB channels"
android:order="100">
<com.heroku.android.SeekBarDialogPreference
android:defaultValue="20"
android:id="#+id/redchannel"
android:key="redchannel"
android:dialogMessage="Please select red channel:"
android:max="50"
android:title="Red channel"
custom:progressTextSuffix="%"
custom:min="1" />
<com.heroku.android.SeekBarDialogPreference
android:defaultValue="20"
android:dialogMessage="Please select green channel:"
android:max="50"
android:title="Select green channel"
custom:progressTextSuffix="%"
custom:min="1" />
<com.heroku.android.SeekBarDialogPreference
android:defaultValue="20"
android:dialogMessage="Please select blue channel:"
android:max="50"
android:title="Select blue channel"
custom:progressTextSuffix="%"
custom:min="1" />
</PreferenceCategory>
</PreferenceScreen>
And I have added to my preference activity these three seekbars as below
package com.heroku.android;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.widget.SeekBar;
public class Preferences extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(com.yuldashev.android.R.xml.preferences);
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(
this);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
}
}
The problem is all of them refers to the same seekbardialog custom class and I cannot get the values for these three seekbars seperately. I have tried to seperate them by entitling #+id in xml file but it does not works for me by findviewbyID because the custom SeekBardialogPreference does not support such an option. For example if you adding and single SeekBar by id you do
SeekBar seek1=(SeekBar)findviewByID(resource)
and you get the progress value from seek1 object.
Is there any suggestion how to do the same with custom seekbardialog below
package com.heroku.android;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
/**
* A {#link DialogPreference} that provides a user with the means to select an integer from a {#link SeekBar}, and persist it.
*
* #author lukehorvat
*
*/
public class SeekBarDialogPreference extends DialogPreference
{
private static final int DEFAULT_MIN_PROGRESS = 0;
private static final int DEFAULT_MAX_PROGRESS = 100;
private static final int DEFAULT_PROGRESS = 0;
private int mMinProgress;
private int mMaxProgress;
private int mProgress;
private CharSequence mProgressTextSuffix;
private TextView mProgressText;
private SeekBar mSeekBar;
public SeekBarDialogPreference(Context context)
{
this(context, null);
}
public SeekBarDialogPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
// get attributes specified in XML
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, com.yuldashev.android.R.styleable.SeekBarDialogPreference, 0, 0);
try
{
setMinProgress(a.getInteger(com.yuldashev.android.R.styleable.SeekBarDialogPreference_min, DEFAULT_MIN_PROGRESS));
setMaxProgress(a.getInteger(com.yuldashev.android.R.styleable.SeekBarDialogPreference_android_max, DEFAULT_MAX_PROGRESS));
setProgressTextSuffix(a.getString(com.yuldashev.android.R.styleable.SeekBarDialogPreference_progressTextSuffix));
}
finally
{
a.recycle();
}
// set layout
setDialogLayoutResource(com.yuldashev.android.R.layout.preference_seek_bar_dialog);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel);
setDialogIcon(null);
}
#Override
protected void onSetInitialValue(boolean restore, Object defaultValue)
{
setProgress(restore ? getPersistedInt(DEFAULT_PROGRESS) : (Integer) defaultValue);
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index)
{
return a.getInt(index, DEFAULT_PROGRESS);
}
#Override
protected void onBindDialogView(View view)
{
super.onBindDialogView(view);
TextView dialogMessageText = (TextView) view.findViewById(com.yuldashev.android.R.id.text_dialog_message);
dialogMessageText.setText(getDialogMessage());
mProgressText = (TextView) view.findViewById(com.yuldashev.android.R.id.text_progress);
mSeekBar = (SeekBar) view.findViewById(com.yuldashev.android.R.id.seek_bar);
mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
// update text that displays the current SeekBar progress value
// note: this does not persist the progress value. that is only ever done in setProgress()
String progressStr = String.valueOf(progress + mMinProgress);
mProgressText.setText(mProgressTextSuffix == null ? progressStr : progressStr.concat(mProgressTextSuffix.toString()));
}
});
mSeekBar.setMax(mMaxProgress - mMinProgress);
mSeekBar.setProgress(mProgress - mMinProgress);
}
public int getMinProgress()
{
return mMinProgress;
}
public void setMinProgress(int minProgress)
{
mMinProgress = minProgress;
setProgress(Math.max(mProgress, mMinProgress));
}
public int getMaxProgress()
{
return mMaxProgress;
}
public void setMaxProgress(int maxProgress)
{
mMaxProgress = maxProgress;
setProgress(Math.min(mProgress, mMaxProgress));
}
public int getProgress()
{
return mProgress;
}
public void setProgress(int progress)
{
progress = Math.max(Math.min(progress, mMaxProgress), mMinProgress);
if (progress != mProgress)
{
mProgress = progress;
persistInt(progress);
notifyChanged();
}
}
public CharSequence getProgressTextSuffix()
{
return mProgressTextSuffix;
}
public void setProgressTextSuffix(CharSequence progressTextSuffix)
{
mProgressTextSuffix = progressTextSuffix;
}
#Override
protected void onDialogClosed(boolean positiveResult)
{
super.onDialogClosed(positiveResult);
// when the user selects "OK", persist the new value
if (positiveResult)
{
int seekBarProgress = mSeekBar.getProgress() + mMinProgress;
if (callChangeListener(seekBarProgress))
{
setProgress(seekBarProgress);
}
}
}
#Override
protected Parcelable onSaveInstanceState()
{
// save the instance state so that it will survive screen orientation changes and other events that may temporarily destroy it
final Parcelable superState = super.onSaveInstanceState();
// set the state's value with the class member that holds current setting value
final SavedState myState = new SavedState(superState);
myState.minProgress = getMinProgress();
myState.maxProgress = getMaxProgress();
myState.progress = getProgress();
return myState;
}
#Override
protected void onRestoreInstanceState(Parcelable state)
{
// check whether we saved the state in onSaveInstanceState()
if (state == null || !state.getClass().equals(SavedState.class))
{
// didn't save the state, so call superclass
super.onRestoreInstanceState(state);
return;
}
// restore the state
SavedState myState = (SavedState) state;
setMinProgress(myState.minProgress);
setMaxProgress(myState.maxProgress);
setProgress(myState.progress);
super.onRestoreInstanceState(myState.getSuperState());
}
private static class SavedState extends BaseSavedState
{
int minProgress;
int maxProgress;
int progress;
public SavedState(Parcelable superState)
{
super(superState);
}
public SavedState(Parcel source)
{
super(source);
minProgress = source.readInt();
maxProgress = source.readInt();
progress = source.readInt();
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
super.writeToParcel(dest, flags);
dest.writeInt(minProgress);
dest.writeInt(maxProgress);
dest.writeInt(progress);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>()
{
#Override
public SavedState createFromParcel(Parcel in)
{
return new SavedState(in);
}
#Override
public SavedState[] newArray(int size)
{
return new SavedState[size];
}
};
}
}
Thank you all!

Search in ListView android

I'm using the following class to so search in listView of countries
package com.androidhive.androidlistviewwithsearch;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity {
private ListView lv;
SimpleCursorAdapter cursorAdapter;
ArrayAdapter<String> adapter;
EditText inputSearch;
private SQLiteAdapter mySQLiteAdapter;
ArrayList<HashMap<String, String>> productList;
public static final String COUNTRY_NAME = "COUNTRY_NAME";
String[] countryName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
int isEmpty = mySQLiteAdapter.isEmpty();
if (isEmpty == 0) {
mySQLiteAdapter.insert("Afghanistan", "102", "119", "119");
mySQLiteAdapter.insert("Albania", "127", "128", "129");
mySQLiteAdapter.insert("Algeria", "14", "14", "17");
mySQLiteAdapter.insert("American Samoa", "911", "911", "911");
mySQLiteAdapter.insert("Andorra", "118", "118", "110");
mySQLiteAdapter.insert("Angola", "118", "118", "110");
mySQLiteAdapter.insert("Panama", "911", "911", "911");
mySQLiteAdapter.insert("Papua New Guinea /Port Moresby", "", "110", "000");
mySQLiteAdapter.insert("Yemen", "191", "191", "194");
mySQLiteAdapter.insert("Zambia", "991/112", "993/112", "999/112");
mySQLiteAdapter.insert("Zimbabwe", "994/999", "993/999", "995/999");
}
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
List<String> list = new ArrayList<String>();
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
String countries = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.COUNTRIES_CONTENT)).toString().trim();
System.out.println("countries: " + countries);
list.add(countries);
cursor.moveToNext();
}
}
countryName = new String[list.size()];
countryName = list.toArray(countryName);
mySQLiteAdapter.close();
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, countryName);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
Intent intent ;
Bundle b = new Bundle();
b.putString(COUNTRY_NAME, countryName[position]);
intent = new Intent(getApplicationContext(), CountryNumbers.class);
intent.putExtras(b);
startActivity(intent);
finish();
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
this code works well and do a search and it also do the setOnItemClickListener that opens the Activity that contains info about the selected country.
But when I do search and I wrote "E" for example, I found the list changed and gets countries that starts with "E" but When I press for example the second country that gets from search, it opens the country with second index in "countryName" array.
How can I solve this issue and get the info of the selected country from the search?
Hope anyone got my mean.
Thanks in advance.
I solved it by replacing this line
b.putString(COUNTRY_NAME, countryName[position]);
by this line
b.putString(COUNTRY_NAME, adapter.getItem(position));