Android Java Text to Speech Viewing Extra String Information - java

I've been running through many of the text to speech examples available for Android and I have an issue that I assume is really simple, but I cannot for the life of me work it out!
I simply want to be able to view the output of EXTRA_AVAILABLE_VOICES (for example) which according to this link is returned in an ArrayList. There are many examples of how to deal with such output programmatically, but for the benefit of my learning and understanding, I want to see the actual returned data for myself.
My project is set up exactly as the android developers example from here
// We now return the list of available and unavailable voices
// as well as the return code.
Intent returnData = new Intent();
returnData.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES, available);
returnData.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES, unavailable);
setResult(result, returnData);
finish();
}
Ideally I'd like to have the output displayed after the 'constant value' in a simple TextView from a string, but I can't achieve that, neither can I get it in a ListView despite my many efforts... Please can someone help me solve this!
Once I know how to view the returned data, I can then go on to follow the examples of how to deal with it correctly.
I've not included any the code I've already tried, as I can't find an example anywhere and it's been pure guess work (which I be embarrassed to show!)
Thanks in advance.

For anyone who is ever stuck with the same thing, I used the code below, edited from the sample found here:
ArrayList<String> available = data
.getStringArrayListExtra("availableVoices");
Log.v("languages count", String.valueOf(available.size()));
Iterator<String> iter = available.iterator();
while (iter.hasNext()) {
String lang = iter.next();
Locale locale = new Locale(lang);
Log.v(TAG, "language: " + lang);
Log.v(TAG, "language locale: " + locale.toString());
TextView LocaleResults = (TextView) getView().findViewById(
R.id.textViewConfig);
LocaleResults.append("\nAvailable Engine Language: " + lang);
}
ArrayList<String> unavailable = data
.getStringArrayListExtra("unavailableVoices");
Log.v("languages count", String.valueOf(unavailable.size()));
Iterator<String> iteru = unavailable.iterator();
while (iteru.hasNext()) {
String ulang = iteru.next();
Locale ulocale = new Locale(ulang);
Log.v(TAG, "ulanguage: " + ulang);
Log.v(TAG, "ulanguage locale: " + ulocale.toString());
TextView LocaleResults = (TextView) getView().findViewById(
R.id.textViewConfig);
LocaleResults.append("\nUnavailable Engine Language: " + ulang);
}

Related

Make link inside of string clickable: Java

I am creating a messaging system in Java using android studio.
People can send messages back and forth. But if they send a link, it just shows up as regular text. I want the part that is the link to show up as a clickable link and the rest just text.
I checked all day on this site and others but no seems to do this in the way I'm trying too. Most of the answers I see are people using a TexView to accomplish their goal. I'm using a string. Can someone please help me figure this out ?
private void showMessages(){
DatabaseReference userMessageKeyRef = RootRef.child("Messages").child(messageSenderID).child(messageReceiverID);
userMessageKeyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
Messages messages = new Messages();
String strMessage = snapshot1.child("message").getValue().toString();
String strFrom = snapshot1.child("from").getValue().toString();
String strType = snapshot1.child("type").getValue().toString();
messages.setMessage(strMessage);
messages.setFrom(strFrom);
messages.setType(strType);
messagesList.add(messages);
// Pattern for recognizing a URL, based off RFC 3986
final Pattern urlPattern = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~#!:/{};']*)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
// separate input by spaces ( URLs don't have spaces )
String [] parts = strMessage.split("\\s+");
// get every part
for( String item : parts ) {
if(urlPattern.matcher(item).matches()) {
//it's a good url
System.out.print(""+ item + " " );
} else {
// it isn't a url
System.out.print(item + " ");
}
}
}
messageAdapter = new MessageAdapter(ChatActivity.this,messagesList);
userMessagesList.setAdapter(messageAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
There are two common ways to do this. One, like you have done, is to add html to the string. The second is to use the TextView's auto link mask feature.
Using HTML
Once you have identified URLs in your incoming string and added the appropriate html tags to turn them into links, you just need to use HtmlCompat when you go to actually display it in the TextView. You also need to make sure to call setMovementMethod or you won't be able to click the link. The advantage of using HTML is that you can have the link text be a readable phrase instead of a URL.
String txt = "This is www.google.com";
TextView link = findViewById(R.id.link);
link.setMovementMethod(LinkMovementMethod.getInstance());
link.setText(HtmlCompat.fromHtml(txt,HtmlCompat.FROM_HTML_MODE_LEGACY));
If you choose to go this route, your existing code just needs to be modified a bit to save the HTML string in the messages list passed to the adapter, then add the TextView calls above inside the adapter when you set the text.
String [] parts = strMessage.split("\\s+");
// replace URL parts with html links
for( int i = 0; i < parts.length; ++i ) {
if(urlPattern.matcher(parts[i]).matches()) {
parts[i] = "" + parts[i] + "";
}
}
// re-join parts back into a single string
String htmlMessage = String.join(" ", parts);
// save a list of html strings to pass to your adapter
htmlMessageStrings.add(htmlMessage);
Using Link Mask
This method doesn't require you to edit the string at all. If you use Linkify.ALL it also recognizes things like web links, emails, phone numbers, and physical addresses - not just web links. If you only want it to recognize web links use Linkify.WEB_URLS instead. This requires a lot less code on your part - you no longer have to try to parse the string for links.
String txt = "This is www.google.com"; // no need to modify the string
TextView link = findViewById(R.id.link);
link.setAutoLinkMask(Linkify.ALL); // or Linkify.WEB_URLS
link.setText(txt);
You can also add android:autoLink="all" to the TextView XML definition instead of calling it in-code.
Both methods produce this output

Fetching a video title from a YouTube URL - Java

I was trying to learn about how to work with the YouTube API using Java libraries, and was trying to do something basic like retrieving a video title given the video ID. However, all the information on this refers to the deprecated v2 API as explained in this link (https://developers.google.com/youtube/2.0/developers_guide_protocol_video_entries?csw=1) and I have not been able to find any sources online on how to accomplish this for the v3 API. If anyone could suggest some books/references on working with the YouTube API as well, I would be extremely grateful.
What you are looking for is .getTitle()
There are a few examples at https://developers.google.com/youtube/v3/code_samples/java?hl=es
for example:
private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) {
System.out.println("\n=============================================================");
System.out.println(
" First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
System.out.println("=============================================================\n");
if (!iteratorSearchResults.hasNext()) {
System.out.println(" There aren't any results for your query.");
}
while (iteratorSearchResults.hasNext()) {
SearchResult singleVideo = iteratorSearchResults.next();
ResourceId rId = singleVideo.getId();
// Double checks the kind is video.
if (rId.getKind().equals("youtube#video")) {
Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");
System.out.println(" Video Id" + rId.getVideoId());
System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
System.out.println(" Thumbnail: " + thumbnail.getUrl());
System.out.println("\n-------------------------------------------------------------\n");
}
}
}
I am very neww to this API thing. But, isn't this part of the API that you need to achieve what you want?
snippet.title
I have never used Youtube's API.
Please correct me if I am wrong.
There is a method called getTitle() in SearchResult, please check that once.

VK SDK for android problems

I'm using Android Studio. I've downloaded VK SDK from github and added it in my project file.Also I import it
import com.perm.kate.api.Api;
I authorize, then get my friends with it
Api api = new Api(Account.access_token, Constants.API_ID);
users = api.getFriends(Account.user_id, "photo", null, null, null);
Insert them in DB
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = prefs.edit();
for(int i =0; i< users.size();++i){
editor.putString("FriendFirstName" + String.valueOf(i), users.get(i).first_name);
editor.putString("FriendLastName"+ String.valueOf(i), users.get(i).last_name);
editor.putString("FriendPhoto"+ String.valueOf(i), users.get(i).photo);
}
editor.commit();
After, I can get any of my friend's name and it's working fine:
Names.add(prefs.getString("FriendFirstName" + String.valueOf(i), null)
+" "+prefs.getString("FriendLastName" + String.valueOf(i), null) );
BUT whenever I try get the photo or photo_medium_rec or any kind of photo it gives me null
Toast.makeText(getActivity(),String.valueOf(prefs.getString("FriendPhoto0", null))
,Toast.LENGTH_LONG).show();//NULL
Why is it giving null?
Addition
I'm new in programming, so here are some of my dumb questions about VK SDK. What should I use Api or Request methods like this:
VKRequest request = VKApi.uploadWallPhotoRequest(new VKUploadImage(photo, VKImageParameters.jpgImage(0.9f)), 0, 0);
Is there any difference between them? How to use Request? And how get my personal user information? I couldn't fined any methods in Api to get it.
Try to use official VK SDK (link).
And maybe it will be helpfull (link)

Android queryIntentActivities always return empty list

I'm trying to get a list of all applications that are capable of sending text messages.
I found several solutions on that suggest to use the PackageManager.
I think that the Intent to be used is ACTION_SEND, but when i run my code i always receive an empty List.
This is my code:
Intent mainIntent = new Intent(Intent.ACTION_SEND, null);
List<ResolveInfo> pkgAppsList = getApplicationContext().getPackageManager().queryIntentActivities( mainIntent, PackageManager.GET_RESOLVED_FILTER);
int size = pkgAppsList.size();
int i = 0;
Log.i(TAG, "Size: " + size);
for(ResolveInfo infos : pkgAppsList){
String name = infos.activityInfo.applicationInfo.loadLabel(getPackageManager()).toString();
Log.i(TAG, "name: " + name);
}
Any idea?
You haven't set the MIME type for the Intent. For example:
mainIntent.setType("text/plain");
That will produce results. However, be mindful that this won't exactly return "applications capable of sending text messages", rather those that can accept a text, not necessarily for the purpose of sending a message (as an example, the Google Translate app is capable of receving text).

Compare Google Maps Marker id with id in SQLite database

I'm trying to compare the value of Markers with an id in my pre-made SQLite database. The reason being is so that I can have specific details for specific markers.
For example:
If the marker clicked has id = 1 then I wish to search the database for id '1' and then grab the details from that row. I thought it was simple enough to just loop through the database, but this doesn't seem to be working. My current code is:
final Cursor dbId = monDatabase.database.rawQuery("SELECT _id from monuments", null);
int idColumnCount = dbId.getColumnCount();
dbId.moveToFirst();
while(dbId.isAfterLast() == false) {
for(int f = 0; f < idColumnCount; f++) {
mainMarkerId = dbId.getInt(0);
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if(marker.getId().equals("m" + mainMarkerId)){
Log.v("marker.getId()", "the id is: " + marker.getId());
selectDesc = monDatabase.database.rawQuery("SELECT description from monuments WHERE _id = " + mainMarkerId, null);
selectDesc.moveToFirst();
_description = selectDesc.getString(0);
Intent descriptionIntent = new Intent(MainActivity.this, DisplayData.class);
descriptionIntent.putExtra(EXTRA_MESSAGE, _description);
startActivity(descriptionIntent);
markerId.moveToNext();
}
}
});
dbId.moveToNext();
}
}
I'm unsure if it is possible this way, or maybe I have to use a Hashmap or something.
Any help is much appreciated,
Thanks!
EDIT:
I forgot to mention that I have all the Markers already displayed on the maps, so it's more of a case of being able to get the description for that location and then passing it through to a new Intent.
SOLUTION:
Just thought I'd post the solution on here if anyone else needed it. I didn't need a Hashtable, all I used was:
selectDesc = monDatabase.database.rawQuery("SELECT description from monuments WHERE title = '" + marker.getTitle() + "'", null);
No need for all the for loops or anything. Very very simple!
your best bet is to create a HashMap of the database elements using the database id as the key and the marker as the value so then you can pull from your database and have what marker you need

Categories