Convert an int-value to a resource uri - java

i have implemented an android-project which plays a random song. So i have an int-array like this:
int [] playlist_stadt = {R.raw.black_a, R.raw.black_b, R.raw.black_c};
for the random play i wrote:
Random r = new Random();
int i = playlist_stadt[r.nextInt(playlist_stadt.length)];
PlayMusic(i);
what i dont understand is following:
textView.setText(i);
textview shows: res/raw/black_c.mp3
Log.e("Output: ", "" + i);
String uriPath = "android.resource://" + getPackageName() + i;
in the log is i an number and not the same string how in the textview:
Output: 2130968577
203-06 13:09:23.680: E/Output:(31456): android.resource://com.example.testproject2130968577
can s.o. explain me this and how to convert the int-value, that i use it as an resource uri path?
thanks in advance and sry for my english

getResources().getResourceEntryName(i) should get you the mp3 name you are looking for.
i is the resource ID generated by aapt in gen/R.java
Android Accessing Resources Doc
The reason textView.setText(i) returns the mp3 resource name is because you are actually calling setText(int resId)
setText(int resId) JavaDoc
You are passing an int parameter which Android interprets as a resource ID and does the getResourceEntryName conversion for you.

Try using "valueOf(i)", otherwise it will try to look up the location of i and not use the value of i.

Related

How to fetch a R id in Java using a variable name

ImageView test = (ImageView) findViewById(R.id.A1);
gets me an ImageView
instead of A1 I would like to use a string variable to fetch a series of IDs
I have tried
Method Pmethod = Class.getDeclaredMethod("(ImageView) findViewById(Id.R." + dest.toString());
as suggusted in this question : how to call a java method using a variable name?
However I get the error
non-static method getDeclaredMethod cannot be referenced from a static context
Any way to fix this?
My latest attempt :
String ps = "P"+ dest.toString();
String ss = "S"+ dest.toString();
int piecelayertier = getResources().getIdentifier(ps,"id","com.donthaveawebsite.mhy.ocfix");
int selectorlayertier = getResources().getIdentifier(ss,"id","com.donthaveawebsite.mhy.ocfix");
ImageView test =(ImageView)findViewById(piecelayertier);
spot.TieAppearance((ImageView)findViewById(piecelayertier));
spot.TieSelector((ImageView)findViewById(selectorlayertier));
I think this is not a correct way to get id.
You can try following to get id using a string variable :
int id = getResources().getIdentifier("<String id>","id","<package name>");
ImageView test =(ImageView)findViewById(id);
You might also need to use a this reference like so :
int id = this.getResources().getIdentifier("<String id>","id", getPackageName());

How can I like a Video using the YouTube Data API v3

I am using the YouTube Data API V3 in Java and I am trying to "like" a video. I am using the following method:
private static String insertPlaylistItem(String playlistId, String videoId) throws IOException {
// Define a resourceId that identifies the video being added to the
// playlist.
ResourceId resourceId = new ResourceId();
resourceId.setKind("youtube#video");
resourceId.setVideoId(videoId);
// Set fields included in the playlistItem resource's "snippet" part.
PlaylistItemSnippet playlistItemSnippet = new PlaylistItemSnippet();
playlistItemSnippet.setTitle("First video in the test playlist");
playlistItemSnippet.setPlaylistId(playlistId);
playlistItemSnippet.setResourceId(resourceId);
// Create the playlistItem resource and set its snippet to the
// object created above.
PlaylistItem playlistItem = new PlaylistItem();
playlistItem.setSnippet(playlistItemSnippet);
// Call the API to add the playlist item to the specified playlist.
// In the API call, the first argument identifies the resource parts
// that the API response should contain, and the second argument is
// the playlist item being inserted.
YouTube.PlaylistItems.Insert playlistItemsInsertCommand =
youtube.playlistItems().insert("snippet,contentDetails", playlistItem);
PlaylistItem returnedPlaylistItem = playlistItemsInsertCommand.execute();
System.out.println("New PlaylistItem name: " + returnedPlaylistItem.getSnippet().getTitle());
System.out.println(" - Video id: " + returnedPlaylistItem.getSnippet().getResourceId().getVideoId());
System.out.println(" - Posted: " + returnedPlaylistItem.getSnippet().getPublishedAt());
System.out.println(" - Channel: " + returnedPlaylistItem.getSnippet().getChannelId());
return returnedPlaylistItem.getId();
}
The Method above came from the official YouTube Example located here:
https://developers.google.com/youtube/v3/docs/playlists/insert?hl=de#examples
I go the hint that I have to add the video to the "liked" playlist, which automatically adds a like to that video.
Here is how I get the Playlist for Likes
....
String likesPlaylistId = channelsList.get(0).getContentDetails().getRelatedPlaylists().getLikes();
insertPlaylistItem(likesPlaylistId, "pwi9TAKUMYI" );
If I like a video that I uploaded myself, it works. But If I try to like a video that another youtuber uploaded, the following error appears:
http://pokit.org/get/?d25a148b2a20d169488cf167d22ad7b0.jpg
I see the video as "liked" but the like counter isn't increasing. Noone else can see that like. Can anyone tell me what I am doing wrong? Is that a restriction? Or is it a prevention against Bots?
Have you tried actually getting the rating of a video? (https://developers.google.com/youtube/v3/docs/videos/getRating).
Get the rating of the video before and after liking the video and then you can verify if the rating count increased. There might be a graphical delay.
raw api call is :
GET https://www.googleapis.com/youtube/v3/videos/getRating?id=pwi9TAKUMYI&key={YOUR_API_KEY}

Can I use a string as an Id?

Still a Noob at Android Development..
So here's My Code
for(int i=1;i<=6;i++){
for(int j=startat;j<=7;j++){
String constring = "r" + i + "c" + j;
//TextView dtv = (TextView) findViewById(R.id.constring); #commented this out
}
}
Is there a way I could use the string variable constring as an Id?
Is there a way I could use the string variable constring as an Id?
I'm little confused what are trying to make?!
This: TextView dtv = (TextView) findViewById(R.id.constring);
especially R.id.constring you shouldn't, musn't do it in the way you do. Every id is automatic generated from XML resources and you should respect it!
Also R.id.costring is int auto-generated in R.java not String so your approach won't work.
From your code is feel "spaghetti code".
<TextView
android:id=#+id/constring"
... next attributes
/>
If you'll write this, id named as constring will be automatic generated and then you just call R.id so constring is automatic filled.
It a case if you don't want to create XML so you just do it like that:
TextView t = new TextView();
t.setText("Hello World");
setContentView(t);
I recommend to you read some Android tutorials for beginners. Here you can start:
Android - A beginner's
guide
You can use getIdentifier method to obtain resource id from name.

url harvester string manipulation

I'm doing a recursive url harvest.. when I find an link in the source that doesn't start with "http" then I append it to the current url. Problem is when I run into a dynamic site the link without an http is usually a new parameter for the current url. For example if the current url is something like http://www.somewebapp.com/default.aspx?pageid=4088 and in the source for that page there is a link which is default.aspx?pageid=2111. In this case I need do some string manipulation; this is where I need help.
pseudocode:
if part of the link found is a contains a substring of the current url
save the substring
save the unique part of the link found
replace whatever is after the substring in the current url with the unique saved part
What would this look like in java? Any ideas for doing this differently? Thanks.
As per comment, here's what I've tried:
if (!matched.startsWith("http")) {
String[] splitted = url.toString().split("/");
java.lang.String endOfURL = splitted[splitted.length-1];
boolean b = false;
while (!b && endOfURL.length() > 5) { // f.bar shortest val
endOfURL = endOfURL.substring(0, endOfURL.length()-2);
if (matched.contains(endOfURL)) {
matched = matched.substring(endOfURL.length()-1);
matched = url.toString().substring(url.toString().length() - matched.length()) + matched;
b = true;
}
}
it's not working well..
I think you are doing this the wrong way. Java has two classes URL and URI which are capable of parsing URL/URL strings much more accurately than a "string bashing" solution. For example the URL constructor URL(URL, String) will create a new URL object in the context of an existing one, without you needing to worry whether the String is an absolute URL or a relative one. You would use it something like this:
URL currentPageUrl = ...
String linkUrlString = ...
// (Exception handling not included ...)
URL linkUrl = new URL(currentPageUrl, linkUrlString);

Loading pre-set script in with a String

Ok I have not done a very good job explaining my problem so here goes revised a few times.
I have a Survey, The Survey Produces an Integer Number. I Convert this Number into a String File name Which relates to a Preset String stored in my resources. Based on the choices made on the questions a different string is required at the end.
This code generates the desired command line; R.string.c####
int Q1 = question1.getmCounter();
int Q2 = question2.getmCounter();
int Q3 = question3.getmCounter();
int Q4 = question4.getmCounter();
int qTotal = Q1 + Q2 + Q3 + Q4;
String Test5 = "R.string.c" + qTotal;
And This code is inside onCreate to generate the content for the TextView.
textOut = (TextView) findViewById(R.id.ChmpNametxt);
textOut.setText(Test5);
Now my concept was that it would read Test5 as "R.string.c####" and load the desired string. It does not do this and i would like to know how i can get the contents of Test5 into a commandline.
Hope someon can help me im malting..
Thanks in Advance
-Chris
You got the correct answer here already: Creating Strings than can be used as Filepath - Eclipse / Android
In your case:
String stringId = "c" + qTotal; //note: not the same as what you did with your Test5
int resId = getResources().getIdentifier(stringId, "string", getPackageName());
textOut.setText(resId);
Or are we misunderstandig your use of the word "commandline"?
You need to get the reosurce id for your text, this code gets the resource id for you:
ContextWrapper cw = this.getContext();// how you get this can be different, but you need a ContextWrapper from somewhere to use.
int resId = cw.getResources().getIdentifier("c" + qTotal, "string", cw.getPackageName());
Then you can use textOut.setText with the resId variable as the parameter.

Categories

Resources