I have this code when button is clicked:
final Button btnInvia = (Button) findViewById(R.id.btnInvia);
btnInvia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
btnInvia.setEnabled(false);
mProgressBar.setVisibility(View.VISIBLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Evento evento = new Evento(PushToTalkActivity.this, Constants.TIPO_EVENTO_ID_PUSH_TO_TALK);
evento.setFile(BinaryHelper.binaryToString(mFileName));
RESTClient.pushToTalk(PushToTalkActivity.this, evento, new Callback<BaseResponse>() {
#Override
public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
if (response.code() == 200) {
Toast.makeText(PushToTalkActivity.this, getResources().getString(R.string.inizio_lavoro_inviato), Toast.LENGTH_LONG).show();
TransitionBuilder.with(PushToTalkActivity.this).clearStack().show(MainActivity.class);
}
}
#Override
public void onFailure(Call<BaseResponse> call, Throwable t) {
mProgressBar.setVisibility(View.GONE);
btnInvia.setEnabled(true);
}
});
}
});
My problem is that ProgressBar is not shown until RESTClient is enqueued, not before.
If I comment the RESTClient call the progressBar is shown correctly.
This is the xml of layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".activities.PushToTalkActivity">a
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:indeterminate="true"
android:indeterminateTintMode="src_atop" />
<TextView
android:id="#+id/recording"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/registazione_in_corso" />
<ImageButton
android:id="#+id/imgBtnAzione"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/stop_recording_icon" />
<Button
android:id="#+id/btnInvia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:visibility="gone"
android:text="#string/invia" />
</LinearLayout>
The pushToTalk function is simple:
NetworkManager.getRESTService().pushToTalk(
getAuthToken(context),
new Gson().toJson(evento)
).enqueue(new Callback<BaseResponse>() {
#Override
public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
//if (validateResponse(context, response.code(), response.message())) {
if (validateResponse(context, response)) {
callback.onResponse(call, response);
}
}
#Override
public void onFailure(Call<BaseResponse> call, Throwable t) {
showFailure(context, t.getMessage());
callback.onFailure(call, t);
}
});
I do not why my ProgressBar is not immediately shown after button is clicked.
Related
I am trying to get a list of images from a folder that I created in my FirebaseStorage bucket. There are total of 20 images and while the app gets all the images, I want to show a ProgressBar. Problem is I don't even see the progressbar before it gets dismissed. I believe this is something related to asynchronous calls that FirebaseStorage uses and I tried to solve it by using AsyncTask but no luck.
private void getBigFlagsFromFirebase() {
bigFlagsList = new ArrayList<>();
progressBar.setVisibility(View.VISIBLE);
if (Utils.isInternetConnectionAvailable(this)) {
FirebaseStorage storage = FirebaseStorage.getInstance("gs://big-quiz-adrien.appspot.com/");
StorageReference storageReference = storage.getReference().child("level1_data/big_flags");
storageReference.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(final ListResult listResult) {
final AtomicInteger filesCount = new AtomicInteger(listResult.getItems().size());
for (final StorageReference file : listResult.getItems()) {
file.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
bigFlagsList.add(uri);
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
Toast.makeText(QuestionActivity.this, "Size: " + bigFlagsList.size(), Toast.LENGTH_SHORT).show(); //this gives me 20
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
Toast.makeText(QuestionActivity.this, "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(QuestionActivity.this, "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Please check your internet connection and try again later.", Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "Size: " + bigFlagsList.size(), Toast.LENGTH_SHORT).show(); //this gives me 0
}
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f7f7f7"
tools:context=".QuestionsActivity">
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/ads">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/themeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#drawable/less_border_radius"
android:backgroundTint="#00B050"
android:gravity="center_horizontal"
android:padding="15dp"
android:text="#string/level_1"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/flagQuestionsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
tools:listitem="#layout/country_questions_item" />
</LinearLayout>
</ScrollView>
<TextView
android:id="#+id/ads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#fff"
android:gravity="center_horizontal"
android:padding="15dp"
android:text="Ads Banner"
android:textSize="18sp" />
</RelativeLayout>
So your code seems to be doing the following:
Showing the progress bar.
Adding a success and failure listener for loading your data.
Dismissing the progress bar.
Loading the data is asynchronous, so until the loading succeeds or fails, you want the progress bar to stay displayed, but you're immediately dismissing it after registering the listener. So progressBar.setVisibility(View.GONE) should be inside the onSuccessListener and onFailureListener instead.
[Edit]
The reason your progress bar is dismissed after the first image is loaded is because you aren't waiting for all the images to load. For each result, you're registering a listener, but you dismiss the progress bar right afterwards. You should wait for all the file.getDownloadUri() calls to complete (either by succeeding or failing).
// I'm not sure if these listeners run concurrently and on which threads, so to be safe I'm using an AtomicInteger, feel free to change it to an int if it's thread safe.
final AtomicInteger filesCount = new AtomicInteger(listResult.getItems().size());
for (StorageReference file : listResult.getItems()) {
file.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Do something with the Uri
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
}
}
});
}
You need to do that with FrameLayout as it help you have the progressbar behind the recyclerview so once your image got loaded, the recyclerview will hide
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/flagQuestionsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
tools:listitem="#layout/country_questions_item" />
</FrameLayout>
remove progressBar.setVisibility(View.GONE); line from bottom of funcion, and place when you got success/fail callback:
private void getFilesFromFirebase() {
progressBar.setVisibility(View.VISIBLE);
FirebaseStorage storage = FirebaseStorage.getInstance("gs://big-quiz-adrien.appspot.com/");
StorageReference storageReference = storage.getReference().child("level1_data/small_flags");
storageReference.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(final ListResult listResult) {
progressBar.setVisibility(View.GONE);
for (StorageReference file : listResult.getItems()) {
file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
smallFlagsList.add(uri);
Toast.makeText(QuestionsActivity.this, "Size: " + smallFlagsList.size(), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
}
});
}
and also you should maintain the sequence of view based on which view will render on top and which are behind.
Last view will be on top of all view, if no view contain elevation.
I have the following link
http://stage.diabetesmasterclass.org/Upload/myclinic/SAM/visit1/sam_storyline_output/story_html5.html
it contains an html5 video and I have tried to load it inside a webview in my android app
it keep loading and never run, I tried to enable javascript and to add a lot of configuration but did not work also
I even tried to use AdvancedWebView sdk to render it, and in this case it loads but did not run anything
can anyone help please ?
You can load page using below code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
protected AgentWeb mAgentWeb;
private LinearLayout mLinearLayout;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mLinearLayout = findViewById(R.id.web_content);
mAgentWeb = AgentWeb.with(this)
.setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))
.closeIndicator()
.setWebChromeClient(mWebChromeClient)
.setWebViewClient(mWebViewClient)
.setMainFrameErrorView(R.layout.agentweb_error_page, -1)
.setAgentWebWebSettings(getAgentWebSettings())
.setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
.setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
//.interceptUnkownUrl()
.createAgentWeb()
.ready()
.go("http://stage.diabetesmasterclass.org/Upload/myclinic/SAM/visit1/sam_storyline_output/story_html5.html");
}
private WebChromeClient mWebChromeClient = new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
}
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
};
private WebViewClient mWebViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i("Info", "BaseWebActivity onPageStarted");
}
};
public #Nullable
IAgentWebSettings getAgentWebSettings() {
return AgentWebSettingsImpl.getInstance();
}
#Override
protected void onPause() {
mAgentWeb.getWebLifeCycle().onPause();
super.onPause();
}
#Override
protected void onResume() {
mAgentWeb.getWebLifeCycle().onResume();
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
mAgentWeb.getWebLifeCycle().onDestroy();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == 2) {
mAgentWeb.getIEventHandler().back();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Top"
android:textSize="22dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/web_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal"></LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Bottom"
android:textSize="22dp" />
</LinearLayout>
</LinearLayout>
using this Webview
update Output look like this
I have used the Youtube API in my application along with FirebaseRecyclerAdapter and RecyclerView and for some reasons my YouTube Thumbnail is not being shown in my application although I have added it in my CardView and my FirebaseRecyclerAdapter has code to access the CardView but when I start my application and go to that activity no thumbnail is shown over there. I have implemented it as hard coded without Firebase Adapter.
Steps I have tried:
Added layout manager
Adjusting the height and width of cardView and thumbnailView
I am using Android Studio
YouTube class file:
public class YoutubeVideos extends YouTubeBaseActivity {
private RecyclerView YouRecycler;
private DatabaseReference YDatabaseReference;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.youtube_videos);
YDatabaseReference = FirebaseDatabase.getInstance().getReference().child("youtubed");
YouRecycler = (RecyclerView)findViewById(R.id.Youtube_recycler);
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder> YfirebaseRecyclerAdapter = new FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder>(
post2youtube.class,
R.layout.youtube_videos_card,
YoutubeViewHolder.class,
YDatabaseReference
) {
#Override
protected void populateViewHolder(YoutubeViewHolder viewHolder, post2youtube model, int position) {
viewHolder.setYoutube(model.getYoutube());
}
};
YouRecycler.setAdapter(YfirebaseRecyclerAdapter);
}
public static class YoutubeViewHolder extends RecyclerView.ViewHolder {
View yView;
public YoutubeViewHolder(View YitemView) {
super(YitemView);
yView = YitemView;
}
public void setYoutube(final String youtube){
final YouTubePlayerView youPlay = (YouTubePlayerView) yView.findViewById(R.id.youtuber);
youPlay.initialize("Some key",
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo(youtube);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
}
}
YouTube RecyclerView file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id ="#+id/Youtube_recycler"/>
</LinearLayout>
YouTube cardView xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/youtube_cardView"
android:layout_width="match_parent" android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtuber"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</android.support.v7.widget.CardView>
YoutubePlayer view is too large to be added to a recyclerview.So use a YouTubeThumbnailView instead to display the thumbnails. When the user clicks on one of them, you can start a YouTubePlayerFragment or an activity with a YouTubeplayerView view.
below is the reference code,
in xml :
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginBottom="#dimen/ten_dp"
android:visibility="gone"/>
in java :
// Initializing video player with developer key
youtube_view.initialize(Config.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
youTubeThumbnailLoader.setVideo(videoId);
youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
youTubeThumbnailLoader.release();
Toast.makeText(getActivity(), "It's a valid youtube url.", Toast.LENGTH_SHORT).show();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
try {
Toast.makeText(getActivity(), "Not a valid youtube url.", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
}
});
I'm following this tutorial to implement in-app purchases, however I'm doing it in a fragment. For both the public void buttonClicked and public void buyClick it says they have never been used, making the app crash when the button is press. I'm not sure whats going wrong.
Error is
java.lang.IllegalStateException: Could not find a method buyClick(View) in the activity class
public class Fragment_1 extends Fragment {
IabHelper mHelper;
private Button clickButton;
private Button buyButton;
private static final String TAG =
"com.appal.inappbilling";
static final String ITEM_SKU = "android.test.purchased";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1,
container, false);
Button buyButton = (Button) view.findViewById(R.id.buyButton);
Button clickButton = (Button) view.findViewById(R.id.clickButton);
clickButton.setEnabled(false);
String base64EncodedPublicKey =
"MYKEY";
mHelper = new IabHelper(getActivity(), base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result)
{
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " +
result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
return view;
}
public void buttonClicked (View view)
{
clickButton.setEnabled(false);
buyButton.setEnabled(true);
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(getActivity(), ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data)
{
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
buyButton.setEnabled(false);
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,
IabResult result) {
if (result.isSuccess()) {
clickButton.setEnabled(true);
} else {
// handle error
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#000000"
android:orientation="vertical"
tools:context=".Fragment_1">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Listen to"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#DEC779" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="gfhfghfg"
android:textColor="#FFFFFF"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#id/textView1"
android:layout_above="#id/textView2">
<Button
android:id="#+id/buyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableRight="#drawable/playiconw"
android:text="Best"
android:textColor="#FFFFFF"
android:layout_below="#+id/textView1"
android:layout_weight="1"
android:onClick="buyClick" />
<Button
android:id="#+id/clickButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableRight="#drawable/playiconw"
android:text="Feel"
android:textColor="#FFFFFF"
android:layout_below="#+id/button1"
android:layout_weight="1"
android:onClick="buttonClicked"/>
Problem is that hosting Activity is receiving button clicks not the fragment. You could set listeners to corresponding buttons with .setOnClickListener() or do something like this in your hosting activity:
public void buyClick(View view) {
Fragment_1_instance.buyClick(view);
}
I have made login sample app of facebook but unable to login into my own application using facebook.i am unable to fire any action on it
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textView = (TextView) view.findViewById(R.id.textView);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
use this code in onCreateViiew
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
//code for success
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException exception) {
// toast
}
});
and add code for onClick FB Login button
LoginManager.getInstance().logInWithReadPermissions(this,
Arrays.asList("email", "user_likes"));
and mention this line in onActivityResult
callbackManager.onActivityResult(requestCode, responseCode, intent);
try following example,
add FacebookSdk in your project and follow the code.
Main.java
public class LoginWithFacebook extends Activity {
// Your Facebook APP ID
private static String APP_ID = "852117698163571"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
#SuppressWarnings({ "unused", "deprecation" })
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
LoginButton btnLogin;
private UiLifecycleHelper uiHelper;
AQuery aQuery;
Button login;
String url,id,name,first_name,middle_name,last_name,location,gender,mobile_number,birthday;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_with_facebook);
login=(Button)findViewById(R.id.button1);
btnLogin=(LoginButton)findViewById(R.id.authButton);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btnLogin.performClick();
}
});
aQuery= new AQuery(getApplicationContext());
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
// When session is changed, this method is called from callback method
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i("Tag", "Logged in...");
// make request to the /me API to get Graph user
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Log.v("url aq", "http://graph.facebook.com/"+user.getId()+"/picture?type=large");
id=user.getId();
name=user.getName();
gender=user.getProperty("gender").toString();
String userName=user.getProperty("email").toString();
url="http://graph.facebook.com/"+user.getId()+"/picture?type=large";
callFacebookLogout(getApplicationContext());
Intent i=new Intent(LoginWithFacebook.this,GetDetail.class);
i.putExtra("id",id);
i.putExtra("name", name);
i.putExtra("gender", gender);
i.putExtra("url", url);
i.putExtra("username", userName);
startActivity(i);
finish();
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i("Tag", "Logged out...");
// otherView.setVisibility(View.GONE);
}
}
public static void callFacebookLogout(Context context) {
Session session = Session.getActiveSession();
if (session != null) {
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
} else {
session = new Session(context);
Session.setActiveSession(session);
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_login_with_facebook, menu);
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
Log.i("Tag", "OnActivityResult...");
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
GetDetail.java
public class GetDetail extends Activity{
Button btnBack;
TextView tvId,tvName,tvGender;
ImageView ivMypic;
AQuery aQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.get_detail);
btnBack=(Button)findViewById(R.id.btnBack);
tvId=(TextView)findViewById(R.id.tvId);
tvName=(TextView)findViewById(R.id.tvName);
tvGender=(TextView)findViewById(R.id.tvGender);
ivMypic=(ImageView)findViewById(R.id.ivMypic);
aQuery=new AQuery(GetDetail.this);
Intent i=getIntent();
tvId.setText("Id: "+i.getStringExtra("id"));
tvName.setText("Name: "+i.getStringExtra("name"));
tvGender.setText("Gender: "+i.getStringExtra("gender")+" UserName = "+i.getStringExtra("username"));
String imageUrl=i.getStringExtra("url");
aQuery.id(ivMypic).image(imageUrl,false,true);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent login= new Intent(GetDetail.this,LoginWithFacebook.class);
startActivity(login);
finish();
}
});
}
}
and main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/ivProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:id="#+id/other_views"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:gravity="left"
android:text="Name"
android:textSize="30dp" />
<TextView
android:id="#+id/gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:gravity="left"
android:text="Gender"
android:textSize="15dp" />
<TextView
android:id="#+id/location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:gravity="left"
android:text="Location"
android:textSize="15dp" />
</LinearLayout>
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login" />
</LinearLayout>
get_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
<ImageView
android:id="#+id/ivMypic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_gravity="center_vertical"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/tvId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_vertical"
android:layout_marginBottom="20dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_vertical"
android:layout_marginBottom="20dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_vertical"
android:layout_marginBottom="20dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
manifest.xml is.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.loginwithfacebook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity
android:name="com.example.loginwithfacebook.LoginWithFacebook"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.facebook.LoginActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<activity android:name=".GetDetail" />
</application>
</manifest>