After days of research and numerous compiler errors... i think i need some assitance from the community.
I have a simple app that retrieves a url through a shared intent from another app.
I want to extract a value from the intent's stringextra (which is a url) add it to the end of my script's url and send that final string as a URL to an URLconnection httpget request.
I've defined my script's url as a variable.
I've gotten the intent and its extras and put it in a variable.
I've tried to just concat my url variable and the stringextra variable to no avail,
URLconnectio gave me back a MalformedURLException. I've logged the concat'd variable
and it looked exactly like what i wanted but for some reason it wouldn't go through.
So now, I'm attempting to just cut the piece I need off of the stringextra and put it on my script's url and then make the http get request off that newly formed string.
SO....
how do I extract 11 characters after "v=", which is in the stringextra, which is
a variable called sharedText?
String goLoQooUrl = "http://my.domain.my/script.php?link=";
private static final String TAG = "LTV";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent rIntent = getIntent();
String rAction = rIntent.getAction();
String rType = rIntent.getType();
if (Intent.ACTION_SEND.equals(rAction) && "text/plain".equals(rType))
displaySentText(rIntent);
}
private void displaySentText (Intent rIntent) {
String sharedText = rIntent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText == null) return;
if (sharedText.startsWith("http://")) {
TextView url = (TextView) findViewById(R.id.URL);
url.setText(String.valueOf(sharedText));
****String w = goLoQooUrl+SUBSTRING***** this is what I want
Log.d("TAG", w);
};
playOnLoqooTv(w);
}
private void playOnLoqooTv (String w) {
try {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(w);
I've tried numerous things to no avail
namely tried using the substring method and it gave me an error about that method
wasn't available I probably wasn't calling it correct.
Can any Masters of the Universes', shed some light?
Try this out:-
int indexOfv = sharedText.indexOf("="); // Get the index of =
indexOfv++; // To get the substring after this element.
String subString = sharedText.substring(indexOfv, indexOfv+11); //Get the 11 characters after the = sign.
Related
I am using YouTubeAndroidPlayerApi - 1.2.1, to show Youtube videos in my application. I get the url's from backend and they come in different formats. For example,
public static final String DOMAIN_1 = "https://www.youtube.com/watch?v=";
public static final String DOMAIN_2 = "http://www.youtube.com/watch?v=";
public static final String DOMAIN_3 = "https://youtu.be/";
public static final String DOMAIN_4 = "http://www.youtube.com/embed/";
public static final String DOMAIN_5 = "https://www.youtube.com/embed/";
All the above urls have VideoID at the end, and I am able to get VideoID and use,
Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) activity,
Const.YouTube.API_KEY, videoId, 0,
true, true);
to play them. But my problem is, there are also urls such as,
https://www.youtube.com/watch?t=15&v=video_id
https://www.youtube.com/watch?v=video_id&list=PL1RpYLGwB6WM409EJBVM1MS9bs3httFse&index=1
and since there are other characters in it, I couldn't extract the videoID.
Is there a way I can use URL with createVideoIntent() or is there any other way i can use URLs to work with YouTubeAndroidPlayerApi.
[EDIT]
If i can't use URL, can someone help me with getting a regex, for extracting videoID from the above Urls?
Use regular expression to cut off the rest of the url
I have an image url I parse form json that I want to load into an android widget onto the homescreen. Right now I am trying to do it this way but its wrong:
ImageDownloadTask imageD = new ImageDownloadTask(image);
views.setImageViewBitmap(R.id.image, imageD.execute(image));
image is a string holding a url to an image that needs to be downloaded and I am trying to set it to R.id.image
I found another stack question and tried this as a result:
views.setBitmap(R.id.image, "setImageBitmap",BitmapFactory.decodeStream(new URL(image).openStream()));
And when I use that nothing in the app loads at all, none of the text views get set.
My third try was this:
//get beer data
JSONObject o = new JSONObject(result);
String name = getName(o);
String image = getImage(o);
String abv = getABV(o);
String ibu = getIBU(o);
String glass = getGlass(o);
String beerBreweryName = getBreweryName(o);
String beerBreweryStyle = getBreweryStyle(o);
String beerDescription = getDescription(o);
InputStream in = new java.net.URL(image).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
views.setTextViewText(R.id.beerTitle, name);
views.setTextViewText(R.id.beerBreweryName, beerBreweryName);
views.setTextViewText(R.id.beerStyleName, beerBreweryStyle);
views.setImageViewBitmap(R.id.image, bitmap);
This gave the same result as the last attempt, it would not even set any text views....
Just tried another attempt after one of the answers posted below:
RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget_test);
//get beer data
JSONObject o = new JSONObject(result);
String name = getName(o);
String imageURL = getImage(o);
String abv = getABV(o);
String ibu = getIBU(o);
String glass = getGlass(o);
String beerBreweryName = getBreweryName(o);
String beerBreweryStyle = getBreweryStyle(o);
String beerDescription = getDescription(o);
Log.d("widgetImage" , imageURL);
views.setImageViewUri(R.id.image, Uri.parse(imageURL));
views.setTextViewText(R.id.beerTitle, name);
views.setTextViewText(R.id.beerBreweryName, beerBreweryName);
views.setTextViewText(R.id.beerStyleName, beerBreweryStyle);
mgr.updateAppWidget(appWidgetIds, views);
This attempt lets all the text views load, but no image ever shows up.
The way to do this reliably is to use setImageViewURI on the remote ImageView. The trick is that the URI you give it is a content:// URI which then points back to a content provider that you export from your application. In your content provider you can do anything you need to do to supply the image bytes.
For example, in your manifest:
<provider android:name=".ImageContentProvider" android:authorities="com.example.test" android:exported="true" />
And your provider:
public class ImageContentProvider extends ContentProvider {
// (Removed overrides that do nothing)
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
List<String> segs = uri.getPathSegments();
// Download the image content here, get the info you need from segs
return ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY);
}
}
And then your URL is something like:
content://com.example.test/something-you-can-define/here
This is necessary because your remote image view is not running in your process. You are much more limited in what you can do because everything must be serialized across the process boundary. The URI can serialize just fine but if you try to send a megabyte of image data with setImageViewBitmap, it's probably going to fail (depending on available device memory).
Got a lot of help from multiple sources for this question. The big problem for me why a bunch of the attempts I tried listed above seemed to lock the widget app and not load anything is because I can not download the image and set it in a UI thread.
To accomplish this I had to move everything to the do in background of my async task and not in the onPostExecute.
I am trying to communicate with Facebook doing simple things. At the moment I can log a user in and post to their wall as them. But for whatever reason, I can't seem to access public information such as their name. I consistently get this error:
{"error":{"message":"Syntax error \"Expected end of string instead of \"?\".\" at character 4: name?access_token=MYACCESSTOKEN","type":"OAuthException","code":2500}}
Here is the call:
SampleRequestListener srl = new SampleRequestListener();
AsyncFacebookRunner afr = new AsyncFacebookRunner(facebook);
afr.request("http://graph.facebook.com/me?fields=name", (RequestListener)srl);
That call is made within a validated session (in the onComplete portion of the DialogListener for .Authorize). Using my access_token and the exact same string as above I can get the request to work just fine at http://developers.facebook.com/tools/explorer/
The error occurs whilst parsing the response in the RequestListener.onComplete
JSONObject json = Util.parseJson(response);
final String name = json.getString("name");
System.out.println("Hi, my name is " + name);
Thank you for your time. All input is welcomed.
UPDATE *
There are two things going on. In the facebook API, Util.openUrl was appending a "?" between the field name and the access_token (as the answer below pointed out). This seems odd. I wonder if I pulled an old version of the API or something. You would think that would be set up correctly.
Also, I called the method incorrectly:
This:
afr.request("http://graph.facebook.com/me?fields=name", (RequestListener)srl);
Should be:
afr.request("me?fields=name", (RequestListener)srl);
If you are using com.facebook.Request class then just use the following form of constructor: Request(Session session, String graphPath, Bundle parameters, HttpMethod httpMethod, Callback callback) and pass your parameters in "parameters" parameter.
Just like:
if (GlobalApplication.accessToken != null && !GlobalApplication.accessToken.isExpired()) {
/* make the API call */
Bundle b = new Bundle();
b.putString("fields", "id,created_time,description,embed_html,name,source,picture");
new GraphRequest(GlobalApplication.accessToken, "/me/videos",
b, HttpMethod.GET, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
/* handle the result */
Log.i("", "");
String string = response.toString();
JSONObject object = response.getJSONObject();
JSONArray array = response.getJSONArray();
Log.i("", "");
}
}).executeAsync();
Looks like the actual request being sent is something like
/me?fields=name?access_token=MYACCESSTOKEN
and that of course is wrong; it should be an ampersand before the second parameter and not a question mark.
You’d have to look for the location in the code where the access token is added as parameter. At that point there should be a check for whether this URL already contains a question mark or not before appending the access_token parameter.
I am obtaining HTML coded content from an SQlite database that I would like to display in a WebView . I am currently using:
public class ShowAbstracts extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String body = extras.getString(DatabaseHelper.KEY_BODY);
WebView webview = new WebView(this);
setContentView(webview);
String summary = "<html><body> "+body+" </body></html>";
webview.loadData(summary, "text/html", "iso-8859-1");
}
}
}
It works in that it opens a WebView and displays the contents but I get strange characters and for some content it just crashes. The Database is ISO-8859-1 encoded.
Is there any way to take care of the special characters in my database content and display them properly?
Thanks very much in advance!
Rik
Success!
Solving this was a combination of 3 things:
uri encoding the string
pasting a head in the HTML string identifying utf-8 encoding
installing LibreOffice which allowed the xls file used for generating the SQLite database to be saved as a csv file with utf-8 encoding (as far as I can tell not possible from MS Office Excel).
.
public class ShowAbstracts extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String body = extras.getString(DatabaseHelper.KEY_BODY);
WebView webview = new WebView(this);
setContentView(webview);
String summary = "<?xml version='1.0' encoding='utf-8'?><html><body>"+body+" </body></html>";
String uri = Uri.encode(summary);
webview.loadData(uri, "text/html", "utf-8");
}
}
}
The api for WebView (http://developer.android.com/reference/android/webkit/WebView.html) says that the the data argument must be URI-escaped (http://developer.android.com/reference/java/net/URLEncoder.html).
Also, when you have a string, the encoding has already been done. You have to see to that the string is created using the correct encoding (for Android the default is UTF-8).
i'm working on a API, and i want to take the json data that is display in an adress like this : https://api.empireavenue.com/profile/info/?apikey=YOURAPIKEY&username=TICKER&password=PASSWORD
and take this data to display it on my app .
Thanks.
The input to the parseJson method should be whatever you get back from the HTTP request. This also assumes the format is something like:
{"rootKey":{"intVal":1}}
You will have to modify the order in which you query objects depending on the structure.
private static final ROOT_JSON_KEY = "rootKey";
private static final INT_VALUE_NAME = "intVal";
public void parseJson(String webServiceResponse) {
JSONObject json = new JSONObject(webServiceResponse);
JSONObject rootObject = json.getJSONObject(ROOT_KEY);
int intValues = rootObject.getInt(INT_VALUE_NAME);
}
EDIT: Sorry, stupid coding error.