I am trying to build an android app and I need a MultiSelectListPreference option in the settings menu. I have created a PreferenceActivity to handle this and I created a preferences.xml file as well, but I need to be able to load the list elements dynamically in the program. I know that I need to use the setEntries and setEntryValues methods to do this, but when I use these methods no exceptions are thrown and the title and summary of the MultiSelectListPreferenc show up but no elements appear.
I have verified that the arrays I am using to populate entries and entryValues are not empty by printing them out, as well as by printing out the result of getEntries() and getEntryValues() after having set them and both these show the entry list to be populated; however no elements show up.
My preferences.xml code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<MultiSelectListPreference
android:key="markedApps"
android:title="Targeted Apps"
android:summary="Select apps to conditionally disable" />
</PreferenceScreen>
My AppSettings.java code:
public class AppSettings extends PreferenceActivity {
public static MultiSelectListPreference blocked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
blocked = new MultiSelectListPreference(this);
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefFrag()).commit();
}
public static class PrefFrag extends PreferenceFragment {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
MultiSelectListPreference blocked = (MultiSelectListPreference)findPreference("markedApps");
if (blocked == null)
Log.e("NullPointerException", "Blocked is null");
AppSelector.populateAppList();
CharSequence[] appNames = new CharSequence[AppSelector.Data.appNames.size()];
CharSequence[] allApps = new CharSequence[AppSelector.Data.allApps.size()];
int i = 0;
for (String appName : AppSelector.Data.appNames)
appNames[i++] = (CharSequence) appName;
i = 0;
for (String app : AppSelector.Data.allApps)
allApps[i++] = (CharSequence) app;
blocked.setEntries(appNames);
blocked.setEntryValues(allApps);
}
}
}
Thank you in advance for any help you provide.
Wow so I feel extremely stupid now. Turns out my problem was that I expected the list to show up under the title and summary whereas you actually have to click on the title and summary to make the list pop up.
Related
Im making wallpaper app which it has a setting button for users which could adjust how many circle can be drawn on the wallpaper. Here i set 5 as default value in the preferences.xml . When i install the app,the wallpaper constructor get the number of circles in preference.xml which just 0 and i have to manually press setting button and set the number. So I want the keep the number is 5 ( default) when installing the app.
Some class that use for the App:
preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference android:key="numofparticles" android:title="Number of particles" android:summary="Chose a initial particle's number" android:defaultValue="5">
</EditTextPreference>
</PreferenceScreen>
Prefernces.java
public class Preferences extends PreferenceActivity {
public static String numofparticles="numofparticles";
public static String image="getimage";
private static final int Pic_image=1;
private SharedPreferences.OnSharedPreferenceChangeListener PreferenceChangeListener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
PreferenceChangeListener=new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
if (s.equals(numofparticles) && s.getClass().getSimpleName()=="Interger")
{
Preference numofP=findPreference(s);
numofP.setSummary(sharedPreferences.getString(s,"")+ " Particles");
Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_SHORT);
}
}
};
Snippet from another class which i get this preference data.
public wallpaperengine()
{
display.getRealSize(size);
wallpaper_height=size.y;
wallpaper_width=size.x;
background=BitmapFactory.decodeResource(getResources(),R.drawable.particlebackground);
background=Bitmap.createScaledBitmap(background,wallpaper_width,wallpaper_height,true);
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(particlewallpaper.this);
sharedPreferences.registerOnSharedPreferenceChangeListener(listener);
num_particle=Integer.valueOf(sharedPreferences.getString(Preferences.numofparticles,"5"));
handler.post(drawFrames);
}
The default 5 is in the layout file (which resides in xml folder of AS) for your preferences activity.
Not in the real preferences data file which resides in /data/data/package/shared_prefs/package_preferences.xml.
The wallpaper code reads from the real data file.
Not from the layout file.
And you know that that activity and layout file are not needed 'to work with shared preferences'.
im programming an app to sort numbers and display the sorting process
after the input is sorted , a new button will be showen to display the selection sort steps in a new activity
[SelectionSort activity 1
I want the output of the function SelectionSortMethod in SelectionSortclass to be displayed in a new activity activity_Ssteps
SelectionSort.java :
public class SelectionSort extends AppCompatActivity {
EditText input;
EditText output;
Button Ssteps ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection_sort);
input=findViewById(R.id.input);
output=findViewById(R.id.output);
Ssteps = findViewById(R.id.steps);
Ssteps.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent s = new Intent(SelectionSort.this, com.example.sorted.Ssteps.class);
startActivityForResult(s, 1);
}
});}
public void sortButtonPressed(View view){
String[] numberList = input.getText().toString().split(",");
Integer[] numbers = new Integer[numberList.length];
for (int i = 0; i < numberList.length; i++) {
numbers[i] = Integer.parseInt(numberList[i]);
}
SelectionSortmethod(numbers);
output.setText(Arrays.toString(numbers));
// if button "sort " is pressed , the button "view steps "will be displayed
Ssteps.setVisibility(View.VISIBLE);
}
}
public static void SelectionSortmethod (Integer[] arr)
{
// some code for sorting and showing the steps
}
Ssteps.java :
public class Ssteps extends AppCompatActivity {
TextView steps_text ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ssteps);
setTitle("selection sort steps ");
steps_text =findViewById(R.id.Stepstextview);
}
}
You can just use intent.extras like so:
Intent s = new Intent(SelectionSort.this, com.example.sorted.Ssteps.class);
s.putExtra("AnyID",YOURDATA);
startActivity(s);
And then in your Ssteps.class you can get the data using
the id like this:
String ss = getIntent.getExtra("AnyID"); //the id is the same as the other one above
steps_text.settext(ss);
Working with Intents like Youssof described is the way to go for small applications like yours. However as you progress in Android programming, you should definitely have a look at splitting your application in Fragments rather than Activities. They can use a Viewmodel, which makes sharing lots of data between screens much easier. Also Fragments can be use in androidx Navigation component, whos changing Fragments can be beautifully arranged in a UI. Very convenient for product reviews.
First, I created a simple program that playes media when you click on a button.
In my Main Activity class I have:
MediaPlayer mySound;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySound = MediaPlayer.create(this, R.raw.sleepnk);
}
Then I created the following:
public void playMusic(View view)
{
mySound.start();
}
Then in my XML file I created a button and added:
android:onClick="playMusic"
Now I am trying to add media to an app but it doesn't have something like:
<Button
android:id="#+id/button"
.
My goal is to add a media file to this "Tap to Start" invisible button in this new app but since there are no buttons in the xml file, I don't know where to attach my playMusic method to the Tap to Start button. I am including instances of Tap to Start button so you can see how it is acting as a button-
There is a strings.xml under values folder that contains:
<?xml version="1.0" encoding="utf-8"?>
<string name="app_name">Panoramik</string>
<string name="instruction_tap_start">Tap to start</string>
Then in the MainActivity.java file we have:
private View.OnClickListener mCameraOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mIsCapturing) {
//clear the flag to prevent the screen of being on
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mDMDCapture.finishShooting()) {
mIsStitching = true;
mTextViewInstruction.setVisibility(View.INVISIBLE);
}
mIsCapturing = false;
setInstructionMessage(R.string.instruction_tap_start);
I am also including the code for "setInstructionMessage" method:
private void setInstructionMessage(int msgID)
{
if (mCurrentInstructionMessageID == msgID)
return;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mDisplayMetrics.widthPixels, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
if (msgID == R.string.instruction_empty || msgID == R.string.instruction_hold_vertically || msgID == R.string.instruction_tap_start
|| msgID == R.string.instruction_focusing) {
params.addRule(RelativeLayout.CENTER_VERTICAL);
} else {
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
}
mTextViewInstruction.setLayoutParams(params);
mTextViewInstruction.setText(msgID);
mCurrentInstructionMessageID = msgID;
}
Can anyone tell me how I can attach my media file sleepnk to the Tap to Start invisible button?
EDIT: I basically want the app to say "Tap to Start" because the app is being created for the visually impaired. So if there is any other suggestion for the app to talk back to the user, feel free to comment
You should let the OS and TalkBack read the "android:contentDescription" attribute by assigning the string "Tap to Start" to whatever it is you want the user to touch. (Remembering to use a string resource so it can be translated/localized.)
I am confused about calling the spinner widget through a custom function. I am create an app in which I use spinner 20-35 times a spinner widget in single layout or activity. So for this i want to avoid the spinner code repetition again and again. i am creating a method for this i add the items to the spinner but i want to pass item value on select to other activity which bind to that class
Here is my code
Spin_tester.class
public class Spin_tester {
public String result;
public Context ctx;
public Spin_tester(Spinner spinner, final ArrayList<String> arraylist, final Context ctx , final String value) {
this.ctx= ctx;
ArrayAdapter<String> adpts =
new ArrayAdapter<String>(ctx, android.R.layout.simple_dropdown_item_1line,arraylist);
spinner.setAdapter(adpts);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
result = arraylist.get(position);
value = result ; // This is not working
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Test_Activity.class
public class Test_Activity extends AppCompatActivity {
ArrayList<String> data_list = new ArrayList<>();
Spinner spins;
String value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
spins = (Spinner)findViewById(R.id.spinner);
data_list.add("1");
data_list.add("2");
data_list.add("3");
data_list.add("4");
Spin_tester asd = new Spin_tester(spins,data_list,this,value);
TextView txt = (TextView)findViewById(R.id.textView17);
}
}
Please help
Thanks in advance
Java is a pass-by-value language, not pass-by-reference. What this means is that setting value in setOnItemSelectedListener will only change value within that method — the result won't be passed back anywhere.
I see that you've place the result in result. That is where the calling program will find the answer.
Remove all instances of value from Spin_tester and Test_Activity and then have your main activity get the result from asd.result
I'm going to get a little meta at this point: I've only answered the question you actually asked, but this code is wrong on so many levels that you're never going to get it to work. I strongly suggest you work your way through the examples and tutorials in the documentation before you try to proceed any further.
Can someone tell me how should am i going to create my listview which look similar here.
Problem 1: The listview example i show in the link only caters to 2 file object as you can see in the link but in my own context i need a rather more "dynamic" video_list which increase/decrease with respect to time,
but how am i going to fulfill the sort of look and feel in my codes which has icons, file name, and file size yet at the same time looking clean and simple on each file object??
Problem 2: And why is my listview having error when the directory is empty despite having this to handle the "empty" in my xml
<TextView
android:id="#id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No File Directory found on SD Card"/>
Can someone guide on this matter because i'm rather new in android/java... Thanks
This is what i tried out so far...
public class ListViewActivity extends ListActivity {
private List<String> videoItems = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videolistview);
getVideoFiles(new File("/sdcard/Video_List").listFiles());
}
public void getVideoFiles(File[] videoList)
{
videoItems = new ArrayList<String>();
for (File file : videoList)
{
videoItems.add(file.getName());
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, videoItems));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
}
}
EDITED
To add your list of videos, simply use the following line:
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, Videos));