I need to set an image as wallpaper using RecyclerView. In my adapter i'm using this code:
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
final GridItem nature = mItems.get(i);
viewHolder.tvspecies.setText(nature.getName());
viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
viewHolder.imgThumbnail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("CLick",nature.toString());
try {
wallpaper.setResource(mItems.get(i));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
so onClick i should set the image as wallpaper but under "setResource" word i have this error:
The method setResource(int) in the type WallpaperManager is not applicable for the arguments (GridItem)
How can i set the item selected from the adapter as wallpaper?
The reason your program is not working, the method setResource(int) takes in int type as a parameter and not GridItemtype.
Reading more from the documentation
Change the current system wallpaper to the bitmap in the given
resource. The resource is opened as a raw data stream and copied into
the wallpaper; it must be a valid PNG or JPEG image.
also make sure your app have permission to set wallpaper in manifest
This method requires the caller to hold the permission SET_WALLPAPER.
Related
Clipboard data returns null when MainActivity is not active in top view activity when I click the button in Android java
I read this restriction about android10 and higher, but my activity is not a background service.
I need to get clipboard data when I click on the button located in the top view activity like the Google Translate application.
In my case, the clipboard returns null when MainActivity is not active.
https://developer.android.com/about/versions/10/privacy/changes#clipboard-data
public class MainActivity extends BridgeActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initializes the Bridge
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
// Additional plugins you've installed go here
// Ex: add(TotallyAwesomePlugin.class);
}});
startActivity(new Intent(MainActivity.this, FloatingWindow.class));
}
}
public class FloatingWindow extends Activity {
// ... additional code ....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
floatingButtonDefinedInClass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
self.getClipboardText();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void getClipboardText() throws IOException {
try {
ClipboardManager myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
ClipData clipData = myClipboard.getPrimaryClip();
if(clipData != null) {
text = (String) clipData.getItemAt(0).getText();
System.out.println(text); // returns null when mainactivity is not active
}
} catch (Exception e) {
e.printStackTrace();
}
}
// ... additional code ....
}
what does "mainactivity is not active" mean? you are getting access to ClipboardManager inside OnClickListener attached to Button, which is a View and need Context, so there must be alive Activity, which keeps this Button on the screen for clicking purpose...
btw. maybe you are you checking on Android 10 or above? it looks like according to docs
Limited access to clipboard data
Unless your app is the default input method editor (IME) or is the app
that currently has focus, your app cannot access clipboard data on
Android 10 or higher.
privacy/security reasons, thats how it will be working now
I'm using a recycler view to load a list of posts made by and organization. I've used firestore as the backend.
For loading the image I'm first getting the download Url from storage reference and then using Glide to load image in to the image view.
The issue i'm facing is that since a call to the storage reference is an asynchronous one, by the time it gets the download uri from the server the position of the adapter in OnBindviewHolder is already changed Therefore image gets mixed up.
I've provided the OnBindViewHolder code and the method where i get the download url
#Override
public void onBindViewHolder(#NonNull final studentFavouriteUniversityPosts.MyViewHolder holder, int position) {
if(postsList.get(holder.getAdapterPosition()).getImageUrl()!=null &&
!postsList.get(holder.getAdapterPosition()).getImageUrl().isEmpty()){
holder.setPostImage(holder.getAdapterPosition());
}
}
public void setPostImage(int position) {
postImage.setVisibility(View.VISIBLE);
placeholder.placeholder(R.color.white);
//Getting the download uri from the Fire store storage and displaying it using glide.
storageReference.child(postsList.get(position).getImageUrl())
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Log.d("URI",uri.toString());
Glide.with(context).applyDefaultRequestOptions(placeholder).load(uri).into(postImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("ERROR","err loading image file");
}
});
}
Can anyone of you help me out on this?
EDIT
I changed the structure a bit. So instead of running the storage reference task in adapter, i'm storing the dowload url in the object. Thus the setPostImage method only has the Glide part.
So the method looks like this
public void setPostImage(String downloadURL) {
postImage.setVisibility(View.VISIBLE);
Glide.with(context).applyDefaultRequestOptions(placeholder).load(downloadURL).into(postImage);
}
Still i'm getting this issue. I dont know how to resolve it
First get the list of urls from firestore from the activity or fragment where you are
setting the adapter
1. public void getImages() { storageReference.child("the child name")
.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Log.d("URI",uri.toString());
adapter.imagesRetrieved();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("ERROR","err loading image file");
}
});
}
2. Then inside on success listener pass the group of values to the adapter method from the success listener and define the method inside the adapter
public void imagesRetreived() {
notifyDataChanged(images);
}
private void notifyDataChanged(Images images) {
this.images = images;
notifydatasetchanged(); //this one is recycler view inbuilt method
}
Although I got my code to work, I now have no idea what it's actually doing.
My app is an RSS reader, and the main content is in a Fragment containing a ListView with NewsStory objects. When a list item is clicked, it opens an Intent with the website linked from the RSS.
Now the problem is, I don't understand the Intent here, it's not the way I've ever used Intents before.
Also, I have to make it so that when I change the orientation, the original profile Fragment takes up the left half of the screen and the linked webpage takes up the right half of the screen. I've tinkered around with it, to no avail. I did a bit of research on orientation changes, but I feel like doing things with Fragments always changes how everything works. Anyway, here's the Fragment code. Any thoughts would be greatly appreciated.
public class HeadlineFragment extends Fragment {
EditText input;
Button search;
ListView headlines;
NewsDataSource ds;
public HeadlineFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_headline,container,false);
input = (EditText)v.findViewById(R.id.txtInput);
search = (Button)v.findViewById(R.id.btnSearch);
headlines = (ListView)v.findViewById(R.id.listView);
try {
ds = new NewsDataSource();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
headlines.setAdapter(new NewsDataSourceAdapter(this.getActivity(), ds));
headlines.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent,View view, int position, long id)
{
String url = NewsDataSource.stories[position].getLink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
return v;
}
/*
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
*/
}
Firstly, regarding that Intent, its an implicit Intent. When you set the action as ACTION_VIEW and add a URI / URL as an extra, the OS gets the message that you want to open an app that can navigate to that URI / URL.
Secondly, for showing a two-pane layout in landscape mode, you'll have to show that RSS content in a Fragment instead of an Activity as you are currently doing, and you'll have to display those Fragments side-by-side in an Activity in landscape mode. See the Retrieving a List of Contacts example for a really good explanation of how to display a multi-pane master detail layout in portrait mode.
References:
1. Intents and Intent Filters.
2. Planning for Multiple Touchscreen Sizes.
I am using this code to swipe between layouts and I would like it to open audio files.
I try to work it so: I swiped from first to second layout, and when layout second came, it should open an audio file.
I tried to use "switch", but I don't know how to properly implement it.
Thanks!
I have done this!
Just add OnPageChangeListener to code.
So it will look like:
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int page) {
// TODO Auto-generated method stub
switch (mViewPager.getCurrentItem()) {
case 0: //first layout
audio1.start();
break;
case 1: //second layout
audio2.start();
break;
//other case, other layouts
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
In my opinion, you should declare a MediaPlayer object within your switch block, give it an Uri containing your audio file path and play your file.
public void moveTo(View v) {
// switch the ViewPager according to the button clicked
int page = 0;
Uri songUri = Uri.parse("musicPath");
player = MediaPlayer.create(context, songUri);
player.start();
switch (v.getId()) {
[...]
I do not know if your music file is like just a few seconds long sound or a whole music track but if it is the first case, it is the best way.
I need to stored my listview that i create dynamically by a "add" button. Of course right now if i go out of application the items disappears. I tryied in this way but something's wrong
public class MainActivity extends Activity{
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/* Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
// Eliminare un elemento al longClick con dialog di conferma
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
final int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setTitle("Are you sure");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
}
});
adb.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
adb.show();
return false;
}
});
lvItem.setClickable(true);
lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = lvItem.getItemAtPosition(position);
Intent intent2 = new Intent(getApplicationContext(), MainActivity.class); // Mettere settings.class quando creata
MainActivity.this.startActivity(intent2);
}
});
}
private void setUpView() {
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, R.layout.customlistview,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
}
protected void addItemList() {
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert value");
return false;
} else {
return true;
}
}
// Shared preferences
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "None Available");
itemAdapter.add(dataSet);
itemAdapter.notifyDataSetChanged();
}
I don't know how "call" the shared preferences and i don't know if in this way it's correct. Right now nothing happen, nothing is saving. Someone can help me please? Thanks
You should look at this API training about activity life cycle:
http://developer.android.com/training/basics/activity-lifecycle/index.html
and also this:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
As you can see, your activity can be gone because the user actively destroy it (using the back button) or the system can destroy it. If they system destroy it you can use onSaveInstanceState to save the data and onCreate to retrieve it. In that case you do not have to use SharedPreferences - just use Bundle as described in the link.
However, if you want to persist your data when the user close it, you should save your data when the call back onDestroy() is called. And retrieve the data when onCreate() is called. onDestroy() is called before the system thinks that your activity is not needed anymore, like when the user click the "back" button. In that case you do have to use one of the storage method provided by android, including Shared preferences. Like someone else said, it requires a "key, value" mechanism, so it might not match 100% with what you do. Using sqlLite is a bit heavy weight for this task, since your data is not really of a table type either (a single column table, actually, which is still not database worthy IMO). I think the best way to store your list is to use internal file. When onDestroy() is called, grab all your data and save to a file. When onCreate() is called, read the file and repopulate your list. You can read about android file system, including internal files here:
http://developer.android.com/training/basics/data-storage/files.html
As a close note, if the user press the "Home" button, your activity will not be destroyed. If he then "Force close" your app then nothing will be saved. If you still want to save it even in that case, I suggest you to save your data when "onStop()" is called and reset your list when onStart() is called.
Right now nothing happen, nothing is saving.
That's because you never call your SavePreferences() method.
If you want to continue using SharedPreferences to store the data in your list, you will need to call SavePreferences() on every item in the list.
However, SharedPreferences are used for storing data in a key-value format. This means that every item in your list will require a key, and you need to know that key to retrieve the data. If your list can contain a variable number of items, SharedPreferences is likely not what you want.
I recommend reading the Storage Options documentation, which provides a complete example using Shared Preferences correctly, and discusses other options which may better suit your needs.