I've been struggling with this for some time now and could not find a solution. Currently I'm population my RecyclerView with all the installed apps on the device using PackageManager. This works perfectly, here is the result I get:
The issue I'm having is that I can't figure out how to store/retrieve the selected checkbox, let me elaborate.
When I select a Checkbox I do the following inside onBindViewHolder:
holder.mAppSelect.setOnCheckedChangeListener(null);
holder.mAppSelect.setChecked(mDataSet.get(position).isSelected());
holder.mAppSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).setSelected(isChecked);
if (holder.mAppSelect.isChecked()){
//Ok great, I can use this to get the position, package name and app name that was selected/checked
}else{
//and it was un-sellected
}
So, I can used the above to store the package name of the selected checkbox and also store a boolean of the state of the checkbox in SQLite, like this:
holder.mAppSelect.setOnCheckedChangeListener(null);
holder.mAppSelect.setChecked(mDataSet.get(position).isSelected());
holder.mAppSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).setSelected(isChecked);
if (holder.mAppSelect.isChecked()){
dbManager.insert(holder.mTextViewPackage.getText().toString(), true);
}else{
dbManager.insert(holder.mTextViewPackage.getText().toString(), false);
}
This is where I have difficulty.. Lets say I close the Activity and open it again, I would like to get the packages/checkboxes that was selected from SQLite and set it again.
So, I'm looking for a way to "cycle" though each holder, get the package name from the holder so that I can check in SQLite if the checkbox was selected previously and set it accordingly.
I think it's also worth mentioning that applications may have been uninstalled or installed since the last time the application was launched. So that would mean that the getAdapterPosition will not remain the same.
EDIT 1:
This is how I populate the Array called mDataSet:
public class AppManager {
private Context mContext;
private AppInfo appInfo;
private ArrayList<AppInfo> myApps;
public AppManager(Context c) {
mContext = c;
myApps = new ArrayList<AppInfo>();
}
public ArrayList<AppInfo> getApps() {
loadApps();
return myApps;
}
private void loadApps() {
List<ApplicationInfo> packages = mContext.getPackageManager().getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
AppInfo newApp = new AppInfo();
newApp.setAppName(getApplicationLabelByPackageName(packageInfo.packageName));
newApp.setAppPackage(packageInfo.packageName);
newApp.setAppIcon(getAppIconByPackageName(packageInfo.packageName));
myApps.add(newApp);
}
Collections.sort(myApps, new Comparator<AppInfo>() {
#Override
public int compare(AppInfo s1, AppInfo s2) {
return s1.getAppName().compareToIgnoreCase(s2.getAppName());
}
});
}
// Custom method to get application icon by package name
private Drawable getAppIconByPackageName(String packageName) {
Drawable icon;
try {
icon = mContext.getPackageManager().getApplicationIcon(packageName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
// Get a default icon
icon = ContextCompat.getDrawable(mContext, R.drawable.ic_launcher_background);
}
return icon;
}
// Custom method to get application label by package name
private String getApplicationLabelByPackageName(String packageName) {
PackageManager packageManager = mContext.getPackageManager();
ApplicationInfo applicationInfo;
String label = "Unknown";
try {
applicationInfo = packageManager.getApplicationInfo(packageName, 0);
if (applicationInfo != null) {
label = (String) packageManager.getApplicationLabel(applicationInfo);
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return label;
}
}
what you can do is use shared preferences
when you start activity retrive state from shared preference like this
SharedPreferences sharedPreference PreferenceManager.getDefaultSharedPreferences(getAppContext());
for(i=0;i<mDataSet.size();i++)
{
mDataSet.get(i).setSelected(sharedPreference.getBoolean(mDataSet.get(i).getAppPackage(),false));
}
and in your adapter save state like this.
holder.mAppSelect.setOnCheckedChangeListener(null);
holder.mAppSelect.setChecked(mDataSet.get(position).isSelected());
holder.mAppSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mDataSet.get(position).setSelected(isChecked);
sharedPreference.edit().putBoolean(mDataSet.get(position).getAppPackage(), isChecked).commit();
});
As I can see, you are following the right steps to show the checkbox selected, if isSelected() returns true, and to save the state(checked/unckecked) of the checkbox in SQLite.
TO display the saved state of the checkboxes from SQLite when you close and open the Activity again, you just need to do is:
First, you need to get the latest list of installed packages.
Select data/checkbox values from SQLite where package name matches with the
latest list of packages.
Now, as you have the saved checkbox values from SQLite, create data set
using the latest installed app list and the checkbox values which you
got from SQLite.
Pass it to your RecyclerViewAdeptor.
It should work fine.
You can try OnClickListener instead of OnCheckedChangeListener
Try this method,
1.Use a list which will have selected items. //selectedlist
If you want to store it permanantly, then use SharedPref.
2.Choose item's data which will be unique //appname as string
3.Set checked state based on the selected list item.
if(selectedlist.get(appname)!=null
&& (selectedlist.get(appname).equals("selected"))) {
holder.checkBox.setChecked(true);
}
else {
holder.checkBox.setChecked(false);
}
4. Add listener to your checkbox,
View.OnClickListener listener=new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedlist.get(appname)==null) {
selectedlist.put(appname, "selected");
else if (selectedlist.get(appname).equals("selected"))
selectedlist.put(appname, "not selected");
else
selectedlist.put(appname, "selected");
notifyDataSetChanged();
}
};
holder.checkBox.setOnClickListener(listener);
Related
I realized that, even though the Sharedprefs, saves the checkbox state, it doesn't keep the drawable resource background thingy that way...... any way to save that too? I was hoping it stays like the picture below. EDIT : So my objective would be that, On checkbox being checked, background changes, because of sharedprefs, the checked state is saved and on exiting the app, the checkbox remains checked but the background of the checkbox returns to its "un-highlighted" state without the drawable background
CheckBox C1,C2,C3;
//Creating keys for sharedpreference
private static final String C1key = "C1_key";
private static final String C2key = "C2_key";
private static final String C3key = "C3_key";
SharedPreferences shp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anime);
//sharedpreference created with the name as anime
shp = getSharedPreferences("Anime",MODE_PRIVATE);
//This is just background gradient animation
ConstraintLayout constraintLayout = findViewById(R.id.layout_anime);
AnimationDrawable animationDrawable = (AnimationDrawable) constraintLayout.getBackground();
animationDrawable.setEnterFadeDuration(2000);
animationDrawable.setExitFadeDuration(4000);
animationDrawable.start();
//Initializing checkboxes
C1 = findViewById(R.id.C1);
C2 = findViewById(R.id.C2);
C3 = findViewById(R.id.C3);
//mapping checkbox and string for ease of use during sharedprefs
Map<String, CheckBox> checkBoxMap = new HashMap();
checkBoxMap.put(C1key,C1);
checkBoxMap.put(C2key,C2);
checkBoxMap.put(C3key,C3);
//loading initial values from sharedprefs, and also creating onCheckedChangeListeners from the map
loadInitialValues(checkBoxMap);
setupCheckedChangeListener(checkBoxMap);
}
public void loadInitialValues(Map<String, CheckBox> checkboxMap) {
for (Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
boolean checked = shp.getBoolean(checkboxEntry.getKey(), false);
checkboxEntry.getValue().setChecked(checked);
}
}
public void setupCheckedChangeListener(Map<String, CheckBox> checkboxMap) { //for loop to cover all the checkboxes and keys in the map
for (final Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
checkboxEntry.getValue().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences.Editor editor = shp.edit();
editor.putBoolean(checkboxEntry.getKey(), isChecked);
editor.apply();
// this part is to turn the background of the checkbox to a specified drawable when its checked and when it isn't
if(checkboxEntry.getValue().isChecked()) //checkboxentry.getvalue().ischecked is to check whether specific checkboxes are in the checked state or not, Ex C1.ischecked() C2.ischecked() and so on
{
checkboxEntry.getValue().setBackgroundResource(R.drawable.cb_background);
}
else
{
checkboxEntry.getValue().setBackgroundResource(R.drawable.cb_background_default);
}
}
});
}
Than i believe should be something like this:
//If is selected set the background
if (C1.isChecked()) {
C1.setSelected(true);
C1.setBackgroundResource(R.drawable.[name of the background]);
}else{
//If is not selected
C1.setBackgroundResource(0);
}
Thanks to Suehtam for helping me out with this really appreciate it!!! this the solution
private void loadInitialValues(Map<String, CheckBox> checkboxMap) {
for (Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
boolean checked = shp.getBoolean(checkboxEntry.getKey(), false);
checkboxEntry.getValue().setChecked(checked);
if (checkboxEntry.getValue().isChecked()) {
checkboxEntry.getValue().setSelected(true);
checkboxEntry.getValue().setBackgroundResource(R.drawable.cb_background);
}else{
//If is not selected
checkboxEntry.getValue().setBackgroundResource(0);
}
}
}
private void setupCheckedChangeListener(Map<String, CheckBox> checkboxMap) {
for (final Map.Entry<String, CheckBox> checkboxEntry: checkboxMap.entrySet()) {
checkboxEntry.getValue().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final SharedPreferences.Editor editor = shp.edit();
editor.putBoolean(checkboxEntry.getKey(), isChecked);
if (checkboxEntry.getValue().isChecked()) {
checkboxEntry.getValue().setSelected(true);
checkboxEntry.getValue().setBackgroundResource(R.drawable.cb_background);
}else{
//If is not selected
checkboxEntry.getValue().setBackgroundResource(0);
}
editor.apply();
}
});
}
}
Humm, if i understood what you want to do is not to save the value but instead to set the box selected.
something like this:
if(C1.isChecked()){
//In this way the box would be with the selected view.
C1.setSelected(true)
}
if is not the state selected and is just the drawable you could do the same:
It's just an example since i don't know which drawable function you are going to use.
Ex:
if(C1.isChecked()){
C1.setCheckMarkDrawable([drawable location]);
}
I am working on a Quiz app. First when a user opens the app they go to the MainActivity, from there when they press start they go to the Categories Activity , from there after selecting a category they go to the Sets Activity, from there after selecting a set the go to the Questions Activity and finally after completing all the questions they reach the Score Activity. Here in the score activity when the click on Done button they are redirected to the MainActivity. In the Score Activity i want to change the color of the Set that they completed to green instead of the default color. How can i do this? I created a sets item layout xml file and used an adapter to fill the gridview in the Sets Activity with views from the adapter. Currently i am getting a null object reference after clicking the Done button in the ScoreActivity.
Here is the code :
SetsAdapter.java
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return numOfSets;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view;
if(convertView == null){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
}
else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent questionIntent = new Intent(parent.getContext(), QuestionActivity.class);
questionIntent.putExtra("SETNUM", position +1);
parent.getContext().startActivity(questionIntent);
}
});
((TextView) view.findViewById(R.id.setNumber)).setText(String.valueOf(position+1));
return view;
}
}
SetsActivity.java
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
private FirebaseFirestore firestore;
public static int categoryID;
private Dialog loadingDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
Toolbar toolbar = (Toolbar)findViewById(R.id.set_toolbar);
setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
categoryID = getIntent().getIntExtra("CATEGORY_ID",1);
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridView);
loadingDialog = new Dialog(SetsActivity.this);
loadingDialog.setContentView(R.layout.loading_progressbar);
loadingDialog.setCancelable(false);
loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.progress_background);
loadingDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
loadingDialog.show();
firestore = FirebaseFirestore.getInstance();
loadSets();
}
private void loadSets() {
firestore.collection("Quiz").document("CAT" + String.valueOf(categoryID))
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
long sets = (long) doc.get("SETS");
SetsAdapter adapter = new SetsAdapter(Integer.valueOf((int)sets));
sets_grid.setAdapter(adapter);
} else {
Toast.makeText(SetsActivity.this, "No Sets Exists!", Toast.LENGTH_SHORT).show();
finish();
}
} else {
Toast.makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
ScoreActivity.java
public class ScoreActivity extends AppCompatActivity {
private TextView score;
private Button done;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
score = findViewById(R.id.score_tv);
done = findViewById(R.id.score_activity_done);
String score_str = getIntent().getStringExtra("SCORE");
final int setNum = getIntent().getIntExtra("SetNum", 1);
score.setText(score_str);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
View view = findViewById(R.id.setNumber);
view.setBackgroundColor(Color.GREEN);
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
}
}
As your activity Sequence is MainActivity -> Categories -> Sets -> Scores.
You've two options to change the color with two different life cycle of the change.
To change the color on a temporary basis, this will reset itself after closing the app or resrtating the 'Sets' activity. It can be done in two ways: Using Public Static Variable and using a public function.
To change the color on a permanent basis until the app is uninstalled/reinstalled. You should use SharedPreferences. SharedPreferences acts like a private data stored in device's memory for further use and it stays there unchanged until and unless the app is removed/data is cleared. Although, apps with root permission can access any app's SharedPreferences data and can modify it as well.You can use SharedPreferences as explained here. Or, you can use some library to access it an easy way. The way I use it in all my apps is TinyDB(it's just a java/kotlin file). This works as:
//store the value from ScoreActivity after completion as
TinyDB tinyDB = TinyDB(this);
tinyDB.putBoolean("isSet1Completed",true);
//access the boolean variable in SetsActivity to change the color of any set that
//is completed and if it's true, just change the color.
TinyDB tinyDB = TinyDB(this);
Boolean bool1 = tinyDB.getBoolean("isSet1Completed");
But, it's your choice what way you want to prefer.
Now, this was about the lifecycle of the change you'll do: Temp or Permanent. Now, we'll talk about how you change the color.
Using public static variable in Sets activity. What you can do is you can set the imageView/textview whose background you want to change as public static variable. Remember, this idea is not preferred as it causes memory leak but it's just easy.
Declare it as public static ImageView imageview;(or TextView) intialize it in the
onCreated() as imageView = finViewById(R.id.viewId); in Sets activity. Call
it as new SetsActivity().imageView.setBackgroundColor(yourColor); in ScoreActivity.
Second way is to create a public function in SetsAcitvity, putting the color change code in it, and then calling it from the ScoreActivity. Just declare it as public void changeColor(){ //your work} and call it from ScoreActivity as new SetsActivity().changeCOlor(). You can also pass some arguments to the function like setId.
I've provided you every thing you need. Rest you should figure out yourself to actually learn it and not copy it.
I think simply you add flag in MainActivity.
for example, add flag in MainActivity.
boolean isFromDone = false;
and when done clicked,
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
mainIntent.putExtra("FromDone", true);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
and in MainActivity, add this.
#Override
protected void onResume() {
super.onResume();
isFromDone = getIntent().getBooleanExtra("FromDone", false);
if(isFromDone) {
(TextView) view.findViewById(R.id.setNumber)).setBackgroundColor(Color.GREEN);
}
}
Suppose you have a Linear Layout in Activity A and you want to change it's background color from a button click which is present in Activity B.
Step 1 Create a class and declare a static variable.
class Util { private static LinearLayout mylayout ; }
Step 2
In the activity which is holding this layout, initialize it.
Util.mylayout = findviewbyid(R.id.linear);
Step 3Change the background color on button click from Activity B
onClick{
Util.mylayout.setBackgroundColor(Color.RED);
}
In my activity I have 4 items in a list view with checkboxes in each row. After I leave activity I want all the checked item position numbers in an arraylist. This code works fine when user clicks all the checkboxes ones and leave the activity. But when user clicks a checkbox and then unchecks it, item position is arraylist doesnt able to clear. This methood is in my CustomAdapter class.
class GameAdapter extends BaseAdapter{
private ArrayList<Integer> positions = new ArrayList<Integer>();
public ArrayList<Integer> getPositions() {
return positions;
}
getView(....){
final ViewHolder holder;
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(holder.checkBox.isChecked()) {
positions.add(position);
}
}
});
}
}
I am handling this adapter class in the activity where my listview resides. There I am taking this arraylist values like this
ArrayList<Integer> gamePositions = mGameAdapter.getPositions();
String itemNumbers = gamePositions.toString();
in itemNumber string I want all the checked item number values.
Thank you in advance for guidance....
Replace this
if(holder.checkBox.isChecked()) {
positions.add(position);
}
with this
if(holder.checkBox.isChecked()) {
if(!positions.contains(position))
positions.add(position);
} else {
if(positions.contains(position))
positions.remove(position);
}
Follow below approach.
Use HashMap instead of Arraylist, like below
HashMap<Integer,Boolean> mapOfSelection = new HashMap<>();
before onClick method, assign position to the checkbox, like below.
holder.checkbox.setTag(position);
In onClick, do the following.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mapOfSelection.put((Integer)buttonView.getTag(),isChecked); // True if this position/value is checked, false otherwise.
}
Now when you need the selected items, just loop through the hashmap and check the positions/Key which have True value.
I have to check whether the button is clicked or not.if clicked application has to do one task and if not, application has to do another task. I tried to do this, but I am getting no connection error which I have put at the end of the code in catch block.
protected void onCreate(Bundle savedInstanceState) {
PracticeVO practiceObj;
try {
setTitle("Klarity");
setPrefBtn = (Button) findViewById(R.id.setPrefBtn);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klarity_home);
/*
* asynchronous calls
*/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
final ConnectionHelper con = new ConnectionHelper();
/*
* It will connect to DB and fetches the Practice Information
*/
if (Btnclicked == false) {
String allPracticesStr = null;
here I have set the boolean variable 'Btnclicked' true.
setPrefBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Btnclicked=true;
Intent setPrefIntent = new Intent(KlarityHome.this,
SetPreferences.class);
startActivity(setPrefIntent);
}
});
But After executing this The cursor is directly goin here and displaying 'no connection'.
catch (Exception ex) {
Context context = getApplicationContext();
CharSequence text = "There is some error in application";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
System.out.println("no connection");
}
}
Anyone has solution on this.
as you said
"the button is clicked or not.if clicked application has to do one task and if noapplication has to do another task"
so, if i were you, i'll put 2 radio buttons, every one with the text of the task you want to do, and add a listener for them, like this:
radiobutton1.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
radiobutton2.setChecked(false);
}
});
radiobutton2.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
radiobutton1.setChecked(false);
}
});
and last, in the button do the task you want to do:
Button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
if(radiobutton1.isChecked){
//do task 1
}else{
//do task2}
}
});
You are getting an NPE(NullPointerException) since you havent initialised Btnclicked in your code at the time of usage.ie you are checking whether Btnclicked is false like
if (Btnclicked == false) {
But at the time of this checking, the value of Btnclicked is null and hence an NPE.
So to get rid of this, you just add either
Btnclicked=true;
or
Btnclicked=false;
before the if loop according to your logic.
OR
or just replace the declaration from Boolean Btnclicked; to Boolean Btnclicked=false;
Hope this helps.
Remove Btnclicked you don't need that. OnClickListner is meant for what you're trying to do. The code which you want to run when button is not pressed put it before
//When button is not pressed
setPrefBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//When button is pressed
}
});
And the code which you want to run when the button is clicked place it inside the onClick(){}
I'm writing an app for the Sony Smartwatch, using their SDK. Here's part of the main activity:
class SmartTickerActivity extends ControlExtension {
private Handler mHandler;
SmartTickerActivity(final String hostAppPackageName, final Context context, Handler handler) {
super(context, hostAppPackageName);
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
}
#Override
public void onStart() {
//do some stuff
PreferenceManager.setDefaultValues(mContext, R.xml.preference, false);
}
The problem is that the saved preferences aren't being applied on the Smartwatch when the application launches. Nor are the default preference values from XML. However, if I click on any of the app's preferences on the phone, the saved preference values are immediately applied to the Smartwatch.
Note that the main class has no onCreate() method, and that's throwing me for a loop.
Here's part of the Preference activity:
public class MyPreferenceActivity extends PreferenceActivity {
private OnSharedPreferenceChangeListener mListener = new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry().toString());
}
if (pref instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) pref;
pref.setSummary(editTextPref.getText().toString());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preference);
setSummaries();
setTypeface(SmartTickerActivity.mainLayout);
if (previewLayout != null) setTypeface(previewLayout);
// Handle read me
Preference readMe = findPreference(getText(R.string.preference_key_read_me));
readMe.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference readMe) {
showDialog(DIALOG_READ_ME);
return true;
}
});
// Handle about
Preference about = findPreference(getText(R.string.preference_key_about));
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference about) {
showDialog(DIALOG_ABOUT);
return true;
}
});
// Handle preview
Preference preview = findPreference(getText(R.string.preference_key_preview_dialog));
preview.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preview) {
showDialog(DIALOG_PREVIEW);
return true;
}
});
}
I'm rather inexperienced at Android development, so the problem might very well have nothing to do whatsoever with the Sony SDK. Can anyone help?
You are correct, the preferences of the official sample extensions are not loaded until the PreferenceActivity is shown for the first time. If you use correct default values when accessing the preferences, this should not be a problem.
If you would like for the preferences to be loaded when the extension is initiated the first time, you could extend the android.app.Application class, and the onCreate method.
For example:
public class MySmartWatchApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
PreferenceManager.setDefaultValues(this, R.xml.app_preferences, false);
}
}