Android Foursquare accessToken: How to get accessToken from inner class? - java

How can I get the accessToken from the anonymous inner class below? when I try to use the accessToken outside the class it shows up as null. I tried to display a toast with the accessToken right after I closed the inner class and it just shows up as null. I want to be able to use the accessToken in an asynctask to fetch some data. How can I go about doing this?
public class main extends Activity {
public static final String CALLBACK_URL = "url";
public static final String CLIENT_ID = "id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url =
"https://foursquare.com/oauth2/authenticate" +
"?client_id=" + CLIENT_ID +
"&response_type=token" +
"&redirect_uri=" + CALLBACK_URL;
// If authentication works, we'll get redirected to a url with a pattern like:
//
// http://YOUR_REGISTERED_REDIRECT_URI/#access_token=ACCESS_TOKEN
//
// We can override onPageStarted() in the web client and grab the token out.
WebView webview = (WebView)findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient( new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
String fragment = "#access_token=";
int start = url.indexOf(fragment);
if (start > -1) {
// You can use the accessToken for api calls now.
String accessToken = url.substring(start + fragment.length(), url.length());
Toast.makeText(main.this, "Token: " + accessToken, Toast.LENGTH_SHORT).show();
}
}
});
webview.loadUrl(url);
}
}

String accessToken =
url.substring(start + fragment.length(), url.length());
There is your access token.
You can pass it to somewhere else in your program. You need to modify the inner class given in the example to fit your needs. As of now, it just displays the token in a dialog box.

Related

How can I use MVVM with the UI components of the App/activity and AsyncTask

As I know that the ViewModel should be secluded from the UI/View and contains only the logic that observes the data that's coming from the server or database
In my App, I used REST API "retrofit" and blogger API and I tried to migrate/upgrade the current code to MVVM but there are a few problems, let's go to the code
BloggerAPI Class
public class BloggerAPI {
private static final String BASE_URL =
"https://www.googleapis.com/blogger/v3/blogs/4294497614198718393/posts/";
private static final String KEY = "the Key";
private PostInterFace postInterFace;
private static BloggerAPI INSTANCE;
public BloggerAPI() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
postInterFace = retrofit.create(PostInterFace.class);
}
public static String getBaseUrl() {
return BASE_URL;
}
public static String getKEY() {
return KEY;
}
public static BloggerAPI getINSTANCE() {
if(INSTANCE == null){
INSTANCE = new BloggerAPI();
}
return INSTANCE;
}
public interface PostInterFace {
#GET
Call<PostList> getPostList(#Url String url);
}
public Call<PostList>getPosts(String url){
return postInterFace.getPostList(url);
}
}
this getData method I used in the Mainctivity to retrieve blog posts
public void getData() {
if (getItemsByLabelCalled) return;
progressBar.setVisibility(View.VISIBLE);
String url = BloggerAPI.getBaseUrl() + "?key=" + BloggerAPI.getKEY();
if (token != "") {
url = url + "&pageToken=" + token;
}
if (token == null) {
return;
}
final Call<PostList> postList = BloggerAPI.getINSTANCE().getPosts(url);
postList.enqueue(new Callback<PostList>() {
#Override
public void onResponse(#NonNull Call<PostList> call, #NonNull Response<PostList> response) {
if (response.isSuccessful()) {
progressBar.setVisibility(View.GONE);
PostList list = response.body();
Log.d(TAG, "onResponse: " + response.body());
if (list != null) {
token = list.getNextPageToken();
items.addAll(list.getItems());
adapter.notifyDataSetChanged();
for (int i = 0; i < items.size(); i++) {
items.get(i).setReDefinedID(i);
}
if (sqLiteItemsDBHelper == null || sqLiteItemsDBHelper.getAllItems().isEmpty()) {
SaveInDatabase task = new SaveInDatabase();
Item[] listArr = items.toArray(new Item[0]);
task.execute(listArr);
}
}
} else {
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
}
#Override
public void onFailure(#NonNull Call<PostList> call, #NonNull Throwable t) {
Toast.makeText(MainActivity.this, "getData error occured", Toast.LENGTH_LONG).show();
Log.e(TAG, "onFailure: " + t.toString());
Log.e(TAG, "onFailure: " + t.getCause());
progressBar.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}
});
}
I created the PostsViewModel to trying to think practically how to migrate the current code to use MVVM
public class PostsViewModel extends ViewModel {
public MutableLiveData<PostList> postListMutableLiveData = new MutableLiveData<>();
public void getData() {
String token = "";
// if (getItemsByLabelCalled) return;
// progressBar.setVisibility(View.VISIBLE);
String url = BloggerAPI.getBaseUrl() + "?key=" + BloggerAPI.getKEY();
if (token != "") {
url = url + "&pageToken=" + token;
}
if (token == null) {
return;
}
BloggerAPI.getINSTANCE().getPosts(url).enqueue(new Callback<PostList>() {
#Override
public void onResponse(Call<PostList> call, Response<PostList> response) {
postListMutableLiveData.setValue(response.body());
}
#Override
public void onFailure(Call<PostList> call, Throwable t) {
}
});
}
}
and it's used thus in MainActivity
postsViewModel = ViewModelProviders.of(this).get(PostsViewModel.class);
postsViewModel.postListMutableLiveData.observe(this, postList -> {
items.addAll(postList.getItems());
adapter.notifyDataSetChanged();
});
now there are two problems using this way of MVVM "ViewModel"
first in the current getData method in the MainActivity it's contains some components that should work only in the View layer like the items list, the recyclerView needs to set View.GONE in case of response unsuccessful, progressBar, emptyView TextView, the adapter that needs to notify if there are changes in the list, and finally I need the context to used the create the Toast messages.
To solve this issue I think to add the UI components and other things into the ViewModel Class and create a constructor like this
public class PostsViewModel extends ViewModel {
Context context;
List<Item> itemList;
PostAdapter postAdapter;
ProgressBar progressBar;
TextView textView;
public PostsViewModel(Context context, List<Item> itemList, PostAdapter postAdapter, ProgressBar progressBar, TextView textView) {
this.context = context;
this.itemList = itemList;
this.postAdapter = postAdapter;
this.progressBar = progressBar;
this.textView = textView;
}
but this is not logically with MVVM arch and for sure cause memory leaking also I will not be able to create the instance of ViewModel with regular way like this
postsViewModel = ViewModelProviders.of(this).get(PostsViewModel.class);
postsViewModel.postListMutableLiveData.observe(this, postList -> {
items.addAll(postList.getItems());
adapter.notifyDataSetChanged();
});
and must be used like this
postsViewModel = new PostsViewModel(this,items,adapter,progressBar,emptyView);
so the first question is How to bind these UI components with the ViewModel?
second in the current getata I used the SaveInDatabase class use the AsyncTask way to save all items in the SQLite database the second question is How to move this class to work with ViewModel? but it also needs to work in the View layer to avoid leaking
the SaveInDatabase Class
static class SaveInDatabase extends AsyncTask<Item, Void, Void> {
#Override
protected Void doInBackground(Item... items) {
List<Item> itemsList = Arrays.asList(items);
// runtimeExceptionDaoItems.create(itemsList);
for (int i = 0 ; i< itemsList.size();i++) {
sqLiteItemsDBHelper.addItem(itemsList.get(i));
Log.e(TAG, "Size :" + sqLiteItemsDBHelper.getAllItems().size());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
Actually the question is too broad to answer because there are many ways to implement for this case. First of all, never pass view objects to viewModel. ViewModel is used to notify changes to ui layer with LiveData or rxJava without retaining the view instance. You may try this way.
class PostViewModel extends ViewModel {
private final MutableLiveData<PostList> postListLiveData = new MutableLiveData<PostList>();
private final MutableLiveData<Boolean> loadingStateLiveData = new MutableLiveData<Boolean>();
private String token = "";
public void getData() {
loadingStateLiveData.postValue(true);
// if (getItemsByLabelCalled) return;
// progressBar.setVisibility(View.VISIBLE);
String url = BloggerAPI.getBaseUrl() + "?key=" + BloggerAPI.getKEY();
if (token != "") {
url = url + "&pageToken=" + token;
}
if (token == null) {
return;
}
BloggerAPI.getINSTANCE().getPosts(url).enqueue(new Callback<PostList>() {
#Override
public void onResponse(Call<PostList> call, Response<PostList> response) {
loadingStateLiveData.postValue(false);
postListLiveData.setValue(response.body());
token = response.body().getNextPageToken(); //===> the token
}
#Override
public void onFailure(Call<PostList> call, Throwable t) {
loadingStateLiveData.postValue(false);
}
});
}
public LiveData<PostList> getPostListLiveData(){
return postListLiveData;
}
public LiveData<Boolean> getLoadingStateLiveData(){
return loadingStateLiveData;
}
}
and you may observe the changes from your activity like this.
postsViewModel = ViewModelProviders.of(this).get(PostsViewModel.class);
postsViewModel.getPostListLiveData().observe(this,postList->{
if(isYourPostListEmpty(postlist)) {
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
items.addAll(postList.getItems());
adapter.notifyDataSetChanged();
}else {
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
}
});
postsViewModel.getLoadingStateLiveData().observe(this,isLoading->{
if(isLoading) {
progressBar.setVisibility(View.VISIBLE);
}else {
progressBar.setVisibility(View.GONE);
}
});
For my personal prefer, I like using Enum for error handling, but I can't post here as it will make the answer very long. For your second question, use Room from google. It will make you life a lot easier. It work very well with mvvm and it natively support liveData. You can try CodeLab from google to practise using room.
Bonus: You don't need to edit the url like this:
String url = BloggerAPI.getBaseUrl() + "?key=" + BloggerAPI.getKEY();
if (token != "") {
url = url + "&pageToken=" + token;
}
You can use #Path or #query based on your requirements.
As your question is bit broad , I am not giving any source code for the same, Rather mentioning samples which clearly resolves issues mentioned with MVVM.
Clean Code Architecture can be followed which will clearly separate the responsibilities of each layer.
First of all application architecture needs to be restructured so that each layer has designated role in MVVM. You can follow the following pattern for the same.
Only View Model will have access to UI layer
View model will connect with Use Case layer
Use case layer will connect with Data Layer
No layer will have cyclic reference to other components.
So now for Database, Repository will decide, from which section the data needs to be fetched
This can be either from Network or from DataBase.
All these points (except Database part) are covered over Medium Article, were each step is covered with actual API's .
Along with that unit test is also covered.
Libraries used are in this project are
Coroutines
Retrofit
Koin (Dependency Injection) Can be replaced with dagger2 is required
MockWebServer (Testing)
Language: Kotlin
Full Source code can be found over Github
Edit
Kotlin is the official supported language for Android Development now. I suggest you should lean and migrate your java android projects to Kotlin.
Still for converting Kotlin to Java, Go to Menu > Tools > Kotlin > Decompile Kotlin to Java Option

passing values between classes by sharedPreferences in Android

I want to save a value in login page that I can use afterwards in other fragments. For doing this I used sharedPreferences and could store the "username", and here is the code:
Login.java
btnl.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String userName=un.getText().toString();
String password=pa.getText().toString();
String PATIENTID="";
// fetch the Password form database for respective user name
String storedPassword=demoCRUD.getSingleEntry_Username(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword)) {
show("Welcome!");
SharedPreferences userDetails = getContext().getSharedPreferences("userdetails", Context.MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString("_user", userName.trim());
edit.apply();
Intent intentLogin=new Intent(getActivity(),Welcome.class);
startActivity(intentLogin);
}
else {
show("User Name or Password does not match");
}
}
});
In addition I could fetch the value again using sharedPreferences in other fragment using the following code:
EditPersonal.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ep_demoCRUD = new DemographicsCRUD(getActivity());
SharedPreferences userDetails = getContext().getSharedPreferences("userdetails", Context.MODE_PRIVATE);
String puser = userDetails.getString("_user", "");
show("puser = " + puser); *SHOWS ME IT HAS A STRING INSIDE
}
Also in "EditPersonal.java" I have this piece of code that call a method from different class:
protected Long doInBackground(Void... arg0) {
return ep_demoCRUD.UpdateDemographics(ep_demoId,puser);
}
The problem is that when onCreate method of "EditPersonal.java" run, "puser" has a value equal to the username from Login.java, but once "doInBachground" call the method "ep_demoCRUD.UpdateDemographics(ep_demoId,puser);" it pass null!
I printed the Log and I understood puser=null.
I can't understand what is the problem? why "null" is passed while it has already had the value ?
p.s the method UpdateDemographics is defined as following:
public long UpdateDemographics(Demographics_to demoId,String us) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DataBaseHelper.lastName, demoId.getD_lastName());
values.put(DataBaseHelper.firstName, demoId.getD_firstName());
values.put(DataBaseHelper.dateOfBirth, demoId.getD_dateOfBirth());
Log.d("puser","=" +us); * NULL IS PRINTED IN LOG*
long result = database.update(dbHelper.Demographics_Table,values,"username = ?" , new String[]{us});
Log.d("Update Result:", "=" + result);
db.close();
return result;
}
Thank you in advance!
i think you are using two variable with same name puser ,, one of them global and the other is Local ,, Just make sure if thats true or not ,, if not then show me the full code of class EditPersonal.java
doInBackground(Void... arg0){}
You do not give the puser variable in the AsyncTask. Why not? is puser a global var?
try giving the puser var with the AsyncTask.
doInBackground(String... puser) {
return ep_demoCRUD.UpdateDemographics(ep_demoId,puser);
}
can you post the whole AsyncTask and where puser is defined?
Why are you using editor.clear()? If you want to store, replace editor.clear() with editor.commit();

Using the userID to get a large profile picture Facebook

I'm a little unsure how to retrieve a large profile picture from facebook current when I use the picture ID. I am loading this URL into my imageview.
http://graph.facebook.com/1454465268197338/picture?type=large
But it doesn't load, when I enter this though it works.
https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xft1/v/t1.0-1/p200x200/11014854_1403982213245644_5725357301610737602_n.jpg?oh=9d95140ca58c8e13a950e14f63018ff4&oe=55F8A88F&gda=1442905098_49d2c7ec583d417722e02a10206c0fb6
What I put above is the REDIRECTED URL after I put in the first. The problem is I cannot produce that with the userID I am given because I am using this.
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
Event ci = contactList.get(i);
contactViewHolder.vName.setText(ci.name);
TinyDB userinfo =new TinyDB(context);
String user_id = userinfo.getString("id");
profile_pic_url ="http://graph.facebook.com/"+user_id+"/picture?type=large";
Picasso.with(context)
.load(profile_pic_url)
.resize(225, 225)
.centerCrop()
.into(contactViewHolder.vProfilePic);
}
Pay attention to the profile_pic_url.
So ultimately, how can I get the redirected url (because I know that works)?
OR
how can I get a LARGE facebook profile picture url from the user because keep in mind the facebook android id because what I get from this:
parameters.putString("fields", "id,name,link,picture,friends");
IS REALLY SMALL.
I tried using
Java - How to find the redirected url of a url?
https://developers.facebook.com/docs/graph-api/reference/user/picture/
No luck unfortunately,
help is appreciated.
TYTY
Try
parameters.putString("fields", "id,name,link,picture.type(large),friends");
– that should get you the large version of the profile picture.
(This makes use of Field Expansion syntax to specify which data you want more precisely.)
You can get good large photo with minimym width of 1000 pic, for example, and height given from aspect ratio, using next code:
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
String profileImg = "https://graph.facebook.com/" + loginResult.getAccessToken().getUserId() + "/picture?type=large&width=1000";
}
});
Bundle parameters = new Bundle();
parameters.putString(AuthConstants.FIELDS,
AuthConstants.ID + "," +
AuthConstants.BIRTHDAY + "," +
AuthConstants.FIRST_NAME + "," +
AuthConstants.LAST_NAME + "," +
AuthConstants.GENDER);
request.setParameters(parameters);
request.executeAsync();
}
Where
public static final String FIELDS = "fields";
public static final String ID = "id";
public static final String BIRTHDAY = "birthday";
public static final String FIRST_NAME = "first_name";
public static final String GENDER = "gender";
public static final String LAST_NAME = "last_name";

Trying to pass information from 4 fields in an Android app to a String in java for testing connection prior to saving the information

I'm programing an android app that connects to a MySQL server, so far I have it so the user can enter the server ip, database name, user name and password and store it to the phone. I am trying to build a string off the info the user just entered to test the connection prior to saving to the .txt files. I know it's probably right in front of my face but after a day of this I'm stuck, please help!! The problem is located in the 'TestButtonListener'
public class AppInfo extends Activity {
public static final String DEBUGTAG = "It's Broke";
public static final String DATABASEPASSWORD = "pinfo.txt";
public static final String SERVERIP = "sinfo.txt";
public static final String DATABASEUSER = "ninfo.txt";
public static final String DATABASE = "dinfo.txt";
public static final String FILESAVED = "filesaved";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_info);
addTestButtonListener();
///Test connection
private void addTestButtonListener() {
Button test = (Button) findViewById(R.id.testcon);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
///need information from the R.id.server, R.id.database, R.id.name, R.id.pword
/// and insert it into the string as serverIp, dataBase, name, pword.
///
try {
/// everything I've tried in here spits out the name of the text file,
/// or the memory address, but not the value just typed in.
}
String serverConnect = new String("jdbc:mysql://" + serverIp
+ "/" + dataBase + ", " + name + ", " + pword);
Toast.makeText(AppInfo.this, serverConnect, Toast.LENGTH_LONG)
.show();
}
});
}
Don't bother, I figured out how to fix it with .getText().toString() and after all that come to find out Android DOES NOT WORK with jdbc connector.

How can my facebook application post message to a wall?

i already found out how to post something to a wall with the graph api on behalf of the facebook user. But now i want to post something in the name of my application.
Here is how i'm trying to do this:
protected void btn_submit_Click(object sender, EventArgs e)
{
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("message", "Testing");
// i'll add more data later here (picture, link, ...)
data.Add("access_token", FbGraphApi.getAppToken());
FbGraphApi.postOnWall(ConfigSettings.getFbPageId(), data);
}
FbGraphApi.getAppToken()
// ...
private static string graphUrl = "https://graph.facebook.com";
//...
public static string getAppToken() {
MyWebRequest req = new MyWebRequest(graphUrl + "/" + "oauth/access_token?type=client_cred&client_id=" + ConfigSettings.getAppID() + "&client_secret=" + ConfigSettings.getAppSecret(), "GET");
return req.GetResponse().Split('=')[1];
}
FbGraphApi.postOnWall()
public static void postOnWall(string id, Dictionary<string,string> args)
{
call(id, "feed", args);
}
FbGraphApi.call()
private static void call(string id, string method, Dictionary<string,string> args )
{
string data = "";
foreach (KeyValuePair<string, string> arg in args)
{
data += arg.Key + "=" + arg.Value + "&";
}
MyWebRequest req = new MyWebRequest(graphUrl +"/" + id + "/" + method, "POST", data.Substring(0, data.Length - 1));
req.GetResponse(); // here i get: "The remote server returned an error: (403) Forbidden."
}
Does anyone see where this i going wrong? I'm really stuck on this.
Thanks!
You need to obtain the Auth Token for your application to post as that application.
The Auth_Token defines the security context you are posting as.
You would need to request the following Graph API URL, for the current user, to find the access token for your application.
https://graph.facebook.com/me/accounts?access_token=XXXXXXXX
This should give you an output similar to the following:
{
"data": [
{
"name": "My App",
"category": "Application",
"id": "10258853",
"access_token": "xxxxxxxxxxxxxxxx"
}
]
}
Be sure you have the manage_pages permission before calling that API or your will not get the access token back.
Once you have the Access Token you publish to the wall like you would any other user. Note that the ID used in the URL matches the ID of the application. This will post to the Application's wall as the Application.
https://graph.facebook.com/10258853/feed?access_token=XXXXXXX
Be sure you have the publish_stream permission as well before posting to the wall.
Recently I had worked With FB api's.
I had Done every thing in javascript.
Here is what i used to post to a users wall.
I hope this helps you.
Include the javascript library provided by FB and add your app id to it.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
For login , i used a button with "fb_login" as id and then i used jquery as follows:
$("#fb_login").click(function(){
FB.login(function(response) {
if (response.session)
{
if (response.perms)
{
// alert("Logged in and permission granted for posting");
}
else
{
// alert("Logged in but permission not granted for posting");
}
}
else
{
//alert("Not Logged In");
}
}, {perms:'publish_stream'});
Note that You have to add {perms:'publish_stream'} as done above which will obtain you the rights to post to the users wall.
A button with id="stream_publish" and then the following jquery:
$("#stream_publish").click(function(){
FB.getLoginStatus(function(response){
if(response.session)
{
publishPost(response.session);
}
});
});
function publishPost(session)
{
var publish = {
method: 'stream.publish',
message: 'Your Message',
picture : 'Image to be displayed',
link : 'The link that will be the part of the post, which can point to either your app page or your personal page or any other page',
name: 'Name or title of the post',
caption: 'Caption of the Post',
description: 'It is fun to write Facebook App!',
actions : { name : 'Start Learning', link : 'link to the app'}
};
FB.api('/me/feed', 'POST', publish, function(response) {
document.getElementById('confirmMsg').innerHTML =
'A post had just been published into the stream on your wall.';
});
};
private class FbWebViewClient extends WebViewClient {
boolean started=false;
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("Facebook-WebView", "Redirect URL: " + url);
if (url.startsWith(Facebook.REDIRECT_URI)) {
Bundle values = Util.parseUrl(url);
String error = values.getString("error");
if (error == null) {
error = values.getString("error_type");
}
if (error == null) {
mListener.onComplete(values);
} else if (error.equals("access_denied")
|| error.equals("OAuthAccessDeniedException")) {
mListener.onCancel();
} else {
mListener.onFacebookError(new FacebookError(error));
}
FbDialog.this.dismiss();
return true;
} else if (url.startsWith(Facebook.CANCEL_URI)) {
mListener.onCancel();
FbDialog.this.dismiss();
return true;
} else if (url.contains(DISPLAY_STRING)) {
return false;
}
// launch non-dialog URLs in a full browser
getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(new DialogError(description, errorCode,
failingUrl));
FbDialog.this.dismiss();
}
public Map<String, String> getUrlParameters(String url)
throws UnsupportedEncodingException {
Map<String, String> params = new HashMap<String, String>();
String[] urlParts = url.split("\\?");
if (urlParts.length > 1) {
String query = urlParts[1];
for (String param : query.split("&")) {
String pair[] = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], "UTF-8");
}
params.put(key, value);
}
}
return params;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d("Facebook-WebView", "Webview loading URL: " + url);
String newUrl="http://www.facebook.com/dialog/feed?_path=feed&app_id=";
if (url.contains("touch") && started==false) {
started=true;
ChildTabBibleLessonActivity.fbMaterial=ChildTabBibleLessonActivity.fbMaterial.replace(" ", "+");
url=url+"&picture=http://www.minibiblecollege.org/mbclandingpage/images/icmlogo-small.jpg&description="+ChildTabBibleLessonActivity.fbMaterial;
/* Map<String,String> param;
try {
param = getUrlParameters(url);
newUrl=newUrl+param.get("app_id")+"&redirect_uri="+"https://deep-rain-6015.herokuapp.com"+"&display=page&picture=http://www.minibiblecollege.org/mbclandingpage/images/icmlogo-small.jpg"+"&name=MiniBible&description=heregoesMyMessage";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
view.loadUrl(url);
//super.onPageStarted(view, url, favicon);
}
else
{
super.onPageStarted(view, url, favicon);
}
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mSpinner.dismiss();
/*
* Once webview is fully loaded, set the mContent background to be
* transparent and make visible the 'x' image.
*/
mContent.setBackgroundColor(Color.TRANSPARENT);
mWebView.setVisibility(View.VISIBLE);
mCrossImage.setVisibility(View.VISIBLE);
}
}

Categories