Android project wont pull facebook events - android

Hi I am trying to make a app that will pull a list the logged in users friends from facebook into my application I am using the facebook SDK the code compiles and seems to work but hangs on the spinner animation when I select the get friends option from the menu! here is the code I am using bellow
public static final String APP_ID = "IDHERE";
private static final String[] PERMISSIONS =
new String[]{ "offline_access", "read_stream",
"publish_stream","create_event","user_events","friends_events",
"publish_checkins", "friends_checkins" };
private TextView mText;
private Handler mHandler = new Handler();
private ProgressDialog mSpinner;
private final ArrayList<Friend> friends = new ArrayList<Friend>();
private FriendsArrayAdapter friendsArrayAdapter;
private ListView listView;
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure the app client_app has been set
if (APP_ID == null) {
Util.showAlert(this,
"Warning", "Facebook Applicaton ID must be set...");
}
// Initialize the content view
setContentView(R.layout.main);
// Get the status text line resource
mText = (TextView) workdammit.this.findViewById(R.id.txt);
// Setup the ListView Adapter that is loaded when selecting "get friends"
listView = (ListView) findViewById(R.id.friendsview);
friendsArrayAdapter = new FriendsArrayAdapter(this, R.layout.rowlayout, friends);
listView.setAdapter(friendsArrayAdapter);
// Define a spinner used when loading the friends over the network
mSpinner = new ProgressDialog(listView.getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
// Initialize the Facebook session
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
//////////////////////////////////////////////////////////////////////
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FB Sample App", "onActivityResult(): " + requestCode);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
//////////////////////////////////////////////////////////////////////
// Get Friends request listener
//////////////////////////////////////////////////////////////////////
/**
* FriendsRequestListener implements a request lister/callback
* for "get friends" requests
*/
public class FriendsRequestListener implements
com.facebook.android.AsyncFacebookRunner.RequestListener {
/**
* Called when the request to get friends has been completed.
* Retrieve and parse and display the JSON stream.
*/
public void onComplete(final String response) {
mSpinner.dismiss();
try {
// process the response here: executed in background thread
Log.d("Facebook-Example-Friends Request", "response.length(): " + response.length());
Log.d("Facebook-Example-Friends Request", "Response: " + response);
final JSONObject json = new JSONObject(response);
JSONArray d = json.getJSONArray("data");
int l = (d != null ? d.length() : 0);
Log.d("Facebook-Example-Friends Request", "d.length(): " + l);
for (int i=0; i<l; i++) {
JSONObject o = d.getJSONObject(i);
String n = o.getString("name");
String id = o.getString("id");
Friend f = new Friend();
f.id = id;
f.name = n;
friends.add(f);
}
// Only the original owner thread can touch its views
workdammit.this.runOnUiThread(new Runnable() {
public void run() {
friendsArrayAdapter = new FriendsArrayAdapter(
workdammit.this, R.layout.rowlayout, friends);
listView.setAdapter(friendsArrayAdapter);
friendsArrayAdapter.notifyDataSetChanged();
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
}
}
#Override
public void onComplete(String response, Object state) {
mSpinner.dismiss();
}
#Override
public void onIOException(IOException e, Object state) {
mSpinner.dismiss();
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
mSpinner.dismiss();
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
mSpinner.dismiss();
}
#Override
public void onFacebookError(FacebookError e, Object state) {
mSpinner.dismiss();
}
}
//////////////////////////////////////////////////////////////////////
// Wall Post request listener
//////////////////////////////////////////////////////////////////////
/**
* WallPostRequestListener implements a request lister/callback
* for "wall post requests"
*/
public class WallPostRequestListener implements
com.facebook.android.AsyncFacebookRunner.RequestListener {
/**
* Called when the wall post request has completed
*/
public void onComplete(final String response) {
Log.d("Facebook-Example", "Got response: " + response);
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
//////////////////////////////////////////////////////////////////////
// Wall post dialog completion listener
//////////////////////////////////////////////////////////////////////
/**
* WallPostDialogListener implements a dialog lister/callback
*/
public class WallPostDialogListener implements
com.facebook.android.Facebook.DialogListener {
/**
* Called when the dialog has completed successfully
*/
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("FB Sample App", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId, new WallPostRequestListener());
} else {
Log.d("FB Sample App", "No wall post made");
}
}
#Override
public void onCancel() {
// No special processing if dialog has been canceled
}
#Override
public void onError(DialogError e) {
// No special processing if dialog has been canceled
}
#Override
public void onFacebookError(FacebookError e) {
// No special processing if dialog has been canceled
}
}
/////////////////////////////////////////////////////////
// Login / Logout Listeners
/////////////////////////////////////////////////////////
/**
* Listener for login dialog completion status
*/
private final class LoginDialogListener implements
com.facebook.android.Facebook.DialogListener {
/**
* Called when the dialog has completed successfully
*/
public void onComplete(Bundle values) {
// Process onComplete
Log.d("FB Sample App", "LoginDialogListener.onComplete()");
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
mText.setText("Facebook login successful. Press Menu...");
}
});
}
/**
*
*/
public void onFacebookError(FacebookError error) {
// Process error
Log.d("FB Sample App", "LoginDialogListener.onFacebookError()");
}
/**
*
*/
public void onError(DialogError error) {
// Process error message
Log.d("FB Sample App", "LoginDialogListener.onError()");
}
/**
*
*/
public void onCancel() {
// Process cancel message
Log.d("FB Sample App", "LoginDialogListener.onCancel()");
}
}
/**
* Listener for logout status message
*/
private class LogoutRequestListener implements RequestListener {
/** Called when the request completes w/o error */
public void onComplete(String response) {
// Only the original owner thread can touch its views
workdammit.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Thanks for using FB Sample App. Bye bye...");
friends.clear();
friendsArrayAdapter.notifyDataSetChanged();
}
});
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
}
});
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
///////////////////////////////////////////////////////////////////
// Menu handlers
///////////////////////////////////////////////////////////////////
/**
* Invoked at the time to create the menu
* #param menu is the menu to create
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
/**
* Invoked when preparing to display the menu
* #param menu is the menu to prepare
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem loginItem = menu.findItem(R.id.login);
MenuItem postItem = menu.findItem(R.id.wallpost);
MenuItem getfriendsItem = menu.findItem(R.id.getfriends);
if (mFacebook.isSessionValid()) {
loginItem.setTitle("Logout");
postItem.setEnabled(true);
getfriendsItem.setEnabled(true);
} else {
loginItem.setTitle("Login");
postItem.setEnabled(false);
getfriendsItem.setEnabled(false);
}
loginItem.setEnabled(true);
return super.onPrepareOptionsMenu(menu);
}
/**
* Invoked when a menu item has been selected
* #param item is the selected menu items
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Login/logout toggle
case R.id.login:
// Toggle the button state.
// If coming from login transition to logout.
if (mFacebook.isSessionValid()) {
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
asyncRunner.logout(this.getBaseContext(), new LogoutRequestListener());
} else {
// Toggle the button state.
// If coming from logout transition to login (authorize).
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
}
break;
// Wall Post
case R.id.wallpost: // Wall Post
mFacebook.dialog(workdammit.this, "stream.publish", new WallPostDialogListener());
break;
// Get Friend's List
case R.id.getfriends: // Wall Post
// Get the authenticated user's friends
mSpinner.show();
mAsyncRunner.request("me/friends", new FriendsRequestListener());
break;
default:
return false;
}
return true;
}
}
there are also two other classes that work with the application the code for these are bellow also
/**
* ListView Friends ArrayAdapter
*/
public class FriendsArrayAdapter extends ArrayAdapter {
private final Activity context;
private final ArrayList friends;
private int resourceId;
/**
* Constructor
* #param context the application content
* #param resourceId the ID of the resource/view
* #param friends the bound ArrayList
*/
public FriendsArrayAdapter(
Activity context,
int resourceId,
ArrayList<Friend> friends) {
super(context, resourceId, friends);
this.context = context;
this.friends = friends;
this.resourceId = resourceId;
}
/**
* Updates the view
* #param position the ArrayList position to update
* #param convertView the view to update/inflate if needed
* #param parent the groups parent view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(resourceId, null);
}
Friend f = friends.get(position);
TextView rowTxt = (TextView) rowView.findViewById(R.id.rowtext_top);
rowTxt.setText(f.name);
return rowView;
}
}
public class Friend {
public String id;
public String name;
public byte[] picture;
public Bitmap pictureBitmap;;
}
any help would be great :D

Code looks good!
Here is one thing to try... check to see if your "#Override" onComplete() method is being called and do something there.
Eg.
public class FriendsRequestListener implements
com.facebook.android.AsyncFacebookRunner.RequestListener {
...
...
#Override
public void onComplete(String response, Object state) {
mSpinner.dismiss();
// Got a response... now process it
onComplete(response);
}

Related

YouTube Player API throwing exception

I looked into other threads, but found no solution for this, except it was originally detected for API 21, i.e. Lollipop. While, I am facing this issue in Lollipop as well as post-Lollipop versions.
I am using YouTube Data API, to display the content of the particular channel in my app. And I am successful in getting the response from the API and displaying content in the RecyclerView.
But when I try to load the video in the YouTubeSupportFragment, the app crashes while invoking the cueVideo() of YouTubeSupportFragment with the following exception.
Note: I am using the latest version (1.2.2) of the YouTube API.
Here's the exception thrown by the YouTube Player:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.acme.youtubeplayer, PID: 16757
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.google.android.youtube.api.service.START }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:2101)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:2225)
at android.app.ContextImpl.bindService(ContextImpl.java:2203)
at android.content.ContextWrapper.bindService(ContextWrapper.java:560)
at com.google.android.youtube.player.internal.r.e(Unknown Source)
at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
at com.google.android.youtube.player.YouTubePlayerSupportFragment.a(Unknown Source)
at com.google.android.youtube.player.YouTubePlayerSupportFragment.onCreateView(Unknown Source)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:7007)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Here's my ListFragment.java, where the app crashes:
public class ListFragment extends android.support.v4.app.Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String KEY_TRANSITION_EFFECT = "transition_effect";
private static final int RECOVERY_REQUEST = 1;
private int mCurrentTransitionEffect = JazzyHelper.HELIX;
private JazzyRecyclerViewScrollListener jazzyScrollListener;
YouTubePlayerView youtube_player;
MyPlayerStateChangeListener playerStateChangeListener;
MyPlaybackEventListener playbackEventListener;
YouTubePlayer playerFragment;
JSONObject jObjectAPI;
JSONArray jArrayResponse;
int listSize;
JSONObject jObjectResponse, jObject;
public static final String YOUTUBE_API = "https://www.googleapis.com/youtube/v3/search?key=" + Config.YOUTUBE_API_KEY + "&channelId=" + Config.YOUTUBE_CHANNEL_ID + "&part=snippet,id&order=date&maxResults=20";
//Local Variables
RecyclerView recyclerView;
Button seekToButton;
YouTubePlayerSupportFragment youTubePlayerFragment;
String[] thumbnailVideo;
String[] titleVideo;
String[] descriptionVideo;
String[] idVideo;
int itemLayoutRes = R.layout.item;
boolean isStaggered = false;
private OnFragmentInteractionListener mListener;
private ProgressDialog pDialog;
public ListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ListFragment.
*/
// TODO: Rename and change types and number of parameters
public static ListFragment newInstance(String param1, String param2) {
ListFragment fragment = new ListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
// Inflate the layout for this fragment
recyclerView = (RecyclerView) view.findViewById(R.id.rv_video_list);
recyclerView.setLayoutManager(createLayoutManager(itemLayoutRes, isStaggered));
recyclerView.setHasFixedSize(false);
new GetList().execute();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private RecyclerView.LayoutManager createLayoutManager(int itemLayoutRes, boolean isStaggered) {
if (itemLayoutRes == R.layout.item) {
return new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
} else {
if (isStaggered) {
return new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
} else {
return new GridLayoutManager(getActivity(), 1);
}
}
}
private void setupJazziness(int effect) {
mCurrentTransitionEffect = effect;
jazzyScrollListener.setTransitionEffect(mCurrentTransitionEffect);
}
private void showMessage(String message) {
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
public final class MyPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {
#Override
public void onPlaying() {
// Called when playback starts, either due to user action or call to play().
showMessage("Playing");
}
#Override
public void onPaused() {
// Called when playback is paused, either due to user action or call to pause().
showMessage("Paused");
}
#Override
public void onStopped() {
// Called when playback stops for a reason other than being paused.
showMessage("Stopped");
}
#Override
public void onBuffering(boolean b) {
// Called when buffering starts or ends.
}
#Override
public void onSeekTo(int i) {
// Called when a jump in playback position occurs, either
// due to user scrubbing or call to seekRelativeMillis() or seekToMillis()
}
}
public final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onLoading() {
// Called when the youtube_player is loading a video
// At this point, it's not ready to accept commands affecting playback such as play() or pause()
playerFragment.loadVideo(idVideo.toString());
}
#Override
public void onLoaded(String s) {
// Called when a video is done loading.
// Playback methods such as play(), pause() or seekToMillis(int) may be called after this callback.
playerFragment.play();
}
#Override
public void onAdStarted() {
// Called when playback of an advertisement starts.
playerFragment.pause();
}
#Override
public void onVideoStarted() {
// Called when playback of the video starts.
}
#Override
public void onVideoEnded() {
// Called when the video reaches its end.
if (playerFragment.hasNext()) {
playerFragment.next();
}
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
// Called when an error occurs.
Toast.makeText(getActivity(), "Please check your Internet Connection", Toast.LENGTH_LONG).show();
}
}
public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String jsonString;
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
return new JSONObject(jsonString);
}
private class GetList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
jObjectAPI = getJSONObjectFromURL(YOUTUBE_API);
Log.e("response", String.valueOf(jObjectAPI));
jArrayResponse = jObjectAPI.getJSONArray("items");
Log.e("array", String.valueOf(jArrayResponse));
listSize = jArrayResponse.length();
thumbnailVideo = new String[listSize];
titleVideo = new String[listSize];
descriptionVideo = new String[listSize];
idVideo = new String[listSize];
for (int i = 0; i < listSize; i++) {
jObjectResponse = jArrayResponse.getJSONObject(i);
thumbnailVideo[i] = jObjectResponse.getJSONObject("snippet").getJSONObject("thumbnails")
.getJSONObject("default")
.optString("url");
titleVideo[i] = jObjectResponse.getJSONObject("snippet").optString("title");
if (!(jObjectResponse.getJSONObject("snippet").optString("description").equals(""))
&& !(jObjectResponse.getJSONObject("snippet").optString("description").equals(null))
&& (jObjectResponse.getJSONObject("snippet").optString("description").length() > 0)) {
descriptionVideo[i] = jObjectResponse.getJSONObject("snippet").optString("description");
} else {
descriptionVideo[i] = "No Description Found";
}
idVideo[i] = jObjectResponse.getJSONObject("id").optString("videoId");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Exception", e.toString());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
**/
recyclerView.setAdapter(new VideoListAdapter(thumbnailVideo, titleVideo, descriptionVideo, idVideo, itemLayoutRes, getActivity()));
jazzyScrollListener = new JazzyRecyclerViewScrollListener();
recyclerView.setOnScrollListener(jazzyScrollListener);
setupJazziness(R.anim.slide_left_in);
playerStateChangeListener = new MyPlayerStateChangeListener();
playbackEventListener = new MyPlaybackEventListener();
youTubePlayerFragment = new YouTubePlayerSupportFragment();
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
playerFragment = player;
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
if (!wasRestored) {
player.cueVideos(Arrays.asList(idVideo));
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult errorReason) {
// TODO Auto-generated method stub
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(getActivity(), RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
}
}
});
android.support.v4.app.FragmentManager fmPlayer = getFragmentManager();
FragmentTransaction transaction = fmPlayer.beginTransaction();
transaction.replace(R.id.youtube_player_view, youTubePlayerFragment);
transaction.commit();
}
}
}
Here's my Adapter class:
public class VideoListAdapter extends Adapter<VideoListAdapter.VideoListViewHolder> {
private List<String> thumbnail;
private List<String> title;
private List<String> desc;
private List<String> id;
private int itemLayoutRes;
private static Activity mContext;
public VideoListAdapter(String[] videoThumbnail, String[] videoTitle, String[] videoDesc, String[] videoId, int itemLayoutRes, Activity context) {
this.thumbnail = Arrays.asList(videoThumbnail);
this.title = Arrays.asList(videoTitle);
this.desc = Arrays.asList(videoDesc);
this.id = Arrays.asList(videoId);
this.itemLayoutRes = itemLayoutRes;
this.mContext = context;
}
#Override
public VideoListAdapter.VideoListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view;
view = inflater.inflate(itemLayoutRes, parent, false);
return new VideoListViewHolder(view);
}
#Override
public void onBindViewHolder(final VideoListViewHolder holder, final int position) {
Picasso.with(mContext).load(thumbnail.get(position)).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// loaded bitmap is here (bitmap)
holder.thumbnailVideo.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Toast.makeText(mContext, "Image load failed", Toast.LENGTH_LONG).show();
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
Log.e("thumbnail Adapter", String.valueOf(thumbnail.get(position)));
holder.titleVideo.setText(title.get(position));
holder.descVideo.setText(desc.get(position));
holder.idVideo = id.get(position);
}
#Override
public int getItemCount() {
return title.size();
}
#Override
public int getItemViewType(int position) {
// return isStaggered ? position % 2 : 0;
return position;
}
public static class VideoListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView titleVideo, descVideo;
final YouTubeThumbnailView thumbnailVideo;
String idVideo;
public VideoListViewHolder(View view) {
super(view);
thumbnailVideo = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail_video);
titleVideo = (TextView) view.findViewById(R.id.title_video);
descVideo = (TextView) view.findViewById(R.id.desc_video);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, YouTubeBaseActivity.class);
//Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) v.getContext(), Config.YOUTUBE_API_KEY, idVideo);
v.getContext().startActivity(intent);
}
}
}
Finally I got rid of this issue. I replaced the YouTubeSupportFragment with YouTubeBaseActivity and used YouTubePlayerView to play the video.
In other words, I used an Activity extending YouTubeBaseActivity to play the video instead of a Fragment.
Hope it helps someone getting the issue.

async task does not work properly

Hi i have a function to get users from website database
my function
private void get_users() {
try {
url = "my address";
dbGetData3 = new DbGetData();
new Thread(new Runnable() {
public void run() {
data = dbGetData3.getDataFromDB(url);
runOnUiThread(new Runnable() {
#Override
public void run() {
userha = parseJSON3(data);
}
});
}
}).start();
Toast.makeText(context, "please wait ", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
toast(9);
}
Now i want add a loading progress bar while fetch data finished.
I use AsyncTask like this:
private class LongOperation extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
progressDialog = new ProgressDialog(Login.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected String doInBackground(String... params) {
try {
get_users();
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
}
}
and i use this code for excute
mytask = new LongOperation();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
mytask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
mytask.execute();
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
onCreate(savedInstanceState);
}
});
but progress dialog dose not show for me (get user worked)
i change my code like this:
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
mytask.onPreExecute();
mytask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else
{
mytask.onPreExecute();
mytask.execute();
}
then my progress dialog allways show
i test other code in stackoverflow like
AsyncTask doInBackground does not run
AsyncTask called from Handler will not execute doInBackground
Android SDK AsyncTask doInBackground not running (subclass)
but that not work for me
please help me tankyou
Consdier using a LoaderManager and an AsyncTaskLoader for this sort of stuff.
AsyncTasks are a pain in the ass as because you have to manage their lifecycle with screen-rotations etc. With a LoaderManager all of that is in the past.
Below is an example of a loader which loads a list of "items".
public class ItemsLoader extends AsyncTaskLoader<List<Item>> {
private static final String TAG = "ItemsLoader";
private List<Item> mItems;
private ItemUpdatedReceiver mObserver;
private int mSomeParam;
public static class ItemUpdatedReceiver extends BroadcastReceiver {
private static final String TAG = "ItemLoader";
final ItemsLoader mLoader;
public ItemUpdatedReceiver(ItemsLoader mLoader) {
this.mLoader = mLoader;
// listen for changes to the account we're using
IntentFilter filter = new IntentFilter(GlobalConstants.ACTION_ITEMS_UPDATED);
LocalBroadcastManager.getInstance(mLoader.getContext()).registerReceiver(this, filter);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (GlobalConstants.ACTION_ITEMS_UPDATED.equals(action)) {
mLoader.onContentChanged();
}
}
}
public void setSomeParam(int someParam){
mSomeParam = someParam;
onContentChanged();
}
public ItemsLoader(Context context, int someParam) {
super(context);
mSomeParam = someParam;
onContentChanged();
}
#Override
public List<Item> loadInBackground() {
// do whatever you need to do here
ArrayList<Item> Items = new ArrayList<>();
return Items;
}
/**
* Called when there is new data to deliever to the client.
*
* #param data
*/
#Override
public void deliverResult(List<Item> data) {
if (isReset()) {
// an async query came in while the loader is stopped, we don't need the result
//release resources if needed
onReleaseResources(data);
}
List<Item> oldItems = mItems;
mItems = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(mItems);
}
// At this point we can release the resources associated with
// 'oldApps' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldItems != null) {
onReleaseResources(oldItems);
}
}
#Override
protected void onStartLoading() {
super.onStartLoading();
if (mItems != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(mItems);
}
// start listening for changes
if (mObserver == null) {
mObserver = new ItemUpdatedReceiver(this);
}
if (takeContentChanged() || mItems == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Handles a request to cancel a load.
*/
#Override
public void onCanceled(List<Item> items) {
super.onCanceled(items);
// At this point we can release the resources associated with 'profile'
// if needed.
onReleaseResources(items);
}
#Override
protected void onReset() {
super.onReset();
// Ensure the laoder is stopped
onStopLoading();
// At this point we can release the resources if needed.
if (mItems != null) {
onReleaseResources(mItems);
mItems = null;
}
// Stop monitoring for changes.
if (mObserver != null) {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mObserver);
mObserver = null;
}
}
/**
* Helper function to take care of releasing resources associated
* with an actively loaded data set.
*/
private void onReleaseResources(List<Item> data) {
// For a simple List<> there is nothing to do. For something
// like a Cursor, we would close it here.
}
}
To use this class, in your activity you must extend LoaderManager.LoaderCallbacks> and override the methods:
public Loader<List<Item>> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// start the loading dialog here
return new ItemsLoader(context);
}
public void onLoadFinished(Loader<List<Item>> loader, List<Item>data) {
// do something with your data, hide the progress dialog
}
public void onLoaderReset(Loader<Cursor> loader) {
// set the old data to null
}
To actually start loading:
getLoaderManager().initLoader(LOADER_ID, null, this);

Android Testing startActivityForResult for Contact

I have one Activity that uses startActivityForResult for Contact by ACTION_PICK. In first, my test is choice the contact and after check the contact selected.
public class ListaMensagemActivity extends ListActivity implements Transacao{
private List<Mensagem> mensagens;
private static final int CONTATO_SELECIONADO=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TransacaoTask task = new TransacaoTask(this, this, R.string.aguarde);
task.execute();
}
#Override
public void executar() throws Exception {
// Busca as mensagens em uma thread
this.mensagens = new MensagemService(this).getMensagem();
}
#Override
public void atualizarView() {
// Atualiza as mensagens na thread principal
if (this.mensagens != null) {
this.setListAdapter(new MensagemAdapter(this, mensagens));
}
}
#Override
public void onListItemClick(ListView parent, View view, int posicao,
long id) {
super.onListItemClick(parent, view, posicao, id);
Intent contactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contactIntent,CONTATO_SELECIONADO);
}
}
atleast send the code that you wanted to test. this is the structure of unit testing in robotium.
your question is also not clear
public class SimpleActivityTest extends
ActivityInstrumentationTestCase2<SimpleActivity> {
private Solo solo;
public SimpleActivityTest() {
super(SimpleActivity.class);
}
public void setUp() throws Exception {
solo = new Solo(getInstrumentation(), getActivity());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
}
public void testListItemClickShouldDisplayToast() throws Exception {
// check that we have the right activity
solo.assertCurrentActivity("wrong activity", SimpleActivity.class);
// Click a button which will start a new Activity
// Here we use the ID of the string to find the right button
solo.clickOnButton(solo
.getString(de.vogella.android.test.target.R.string.button1));
// assert that the current activity is the SimpleListActivity.class
solo.assertCurrentActivity("wrong activity", SimpleListActivity.class);
solo.clickInList(1);
// searchForText has a timeout of 5 seconds
assertTrue(solo.waitForText("Android")); // Assertion
solo.clickInList(2);
assertTrue(solo.waitForText("iPhone")); // Assertion
solo.clickInList(3);
assertTrue(solo.waitForText("Blackberry")); // Assertion
solo.goBack();
solo.clickOnButton("Button2");
solo.clickOnButton("Button3");
}
public void testListItemClickShouldDisplayToast() throws Exception {
// open the menu
solo.sendKey(Solo.MENU);
solo.clickOnText("Preferences");
solo.clickOnText("User");
solo.clearEditText(0);
Assert.assertTrue(solo.searchText(""));
solo.enterText(0, "http//:www.vogella.com");
Assert.assertTrue(solo.searchText("http//:www.vogella.com"));
solo.goBack();
}
}
The my question is a test to Intent.ACTION_PICK. In case, I have an action pick to choose a contact's number in view of android and get the contact's number.

No list returned while retrieving scores from Scoreloop server

I am trying to retrieve score of the device user from the Scoreloop server. It's an AndEngine game. I tried the following:
observer = new RequestControllerObserver() {
#Override
public void requestControllerDidFail(RequestController arg0,
Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void requestControllerDidReceiveResponse(
RequestController requestController) {
// TODO Auto-generated method stub
myScoresController = (ScoresController) requestController;
myScoresController.setSearchList(SearchList
.getGlobalScoreSearchList());
myScoresController.setMode(mode);
myScoresController.setRangeLength(20);
myScoresController.loadRangeForUser(Session.getCurrentSession()
.getUser());
Log.i("score", "" + myScoresController.getScores().get(0).getResult());
// List<Score> retrievedScores = myScoresController.getScores();
}
The Log.i() is not even showed up. I also tried this:
observer = new RequestControllerObserver() {
#Override
public void requestControllerDidFail(RequestController arg0,
Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void requestControllerDidReceiveResponse(
RequestController requestController) {
// TODO Auto-generated method stub
}
myScoresController = new ScoresController(observer);
myScoresController.setSearchList(SearchList
.getGlobalScoreSearchList());
myScoresController.setMode(mode);
myScoresController.setRangeLength(20);
myScoresController.loadRangeForUser(Session.getCurrentSession()
.getUser());
Log.i("score", "" + myScoresController.getScores().get(0).getResult());
// List<Score> retrievedScores = myScoresController.getScores();
I am trying to get the first element of the list and then the score result. But there is no list coming up. The error shown as:
java.lang.IndexOutOfBoundsException
java.util.Collections$EmptyList.get(Collections.java:102)
But I didn't try both of the above together. There certainly is a mistake But I don't see it.
Edit:
The whole class where I am using it is as follows:
public class ScoreLoopUpdater implements Runnable {
private double score;
private int mode;
private RequestControllerObserver observer;
private ScoresController myScoresController = null;
public ScoreLoopUpdater(double _score, int _mode) {
this.score = _score;
this.mode = _mode;
}
public void run() {
getGlobalHighscore();
ScoreloopManagerSingleton.get().onGamePlayEnded(
score, mode);
}
private void getGlobalHighscore() {
//the above codes including observer go inside here.
}
I am calling from a scene using this:
ScoreLoopUpdater scoreLoopUpdater = new ScoreLoopUpdater(theScore, theMode);
activity.runOnUiThread(scoreLoopUpdater);
After gesturing with some examples I've finally come up with the proper way:
private void getGlobalHighscore() {
observer = new RequestControllerObserver() {
#Override
public void requestControllerDidFail(RequestController arg0,
Exception arg1) {
// TODO Auto-generated method stub
}
#Override
public void requestControllerDidReceiveResponse(
RequestController requestController) {
// TODO Auto-generated method stub
final ScoresController myScoresController = (ScoresController) requestController;
Log.i("score", "" + myScoresController.getScores().get(0).getResult());
// List<Score> retrievedScores = myScoresController.getScores();
}
};
ScoresController myScoresController = new ScoresController(observer);
myScoresController.setSearchList(SearchList
.getGlobalScoreSearchList());
myScoresController.setMode(mode);
myScoresController.setRangeLength(20);
myScoresController.loadRangeForUser(Session.getCurrentSession()
.getUser());
}
Only getScores() should be called inside requestControllerDidReceiveResponse function, which means getting the scores after receiving the response.

android spinner action bar (easy answer for someone)

Im having trouble adding a spinner in place of the application name in my action bar.
im sure this question has been asked before but all the answers are pretty much the same either a simple one line correction and then a reference to thiers a lovely example at the google dev site here: http://developer.android.com/guide/topics/ui/actionbar.html#Dropdown
the android docs but for a beginner I find it ashumes to much and leaves out tiny peices of key information.
public class MainProgram extends Activity implements OnNavigationListener {
/**
* Mobile Service Client reference
*/
private MobileServiceClient mClient;
private ConnectWithService service;
/**
* Progress spinner to use for table operations
*/
private ProgressBar mProgressBar;
/**
* Sensor stuff
*/
SensorManager mSensor;
Detection orientation;
//Spinner Listener
mOnNavigationListener = new OnNavigationListener() {
// Get the same strings provided for the drop-down's ArrayAdapter
String[] strings = getResources().getStringArray(R.array.action_list);
#Override
public boolean onNavigationItemSelected(int position, long itemId) {
//toast
Toast toast = Toast.makeText(this, "whoop whoop!", toast.LENGTH_SHORT);
toast.show();
}
};
/**
* Initializes the activity
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_program);
//Load progress bar view
mProgressBar = (ProgressBar) findViewById(R.id.loadingProgressBar);
// Initialize the progress bar
mProgressBar.setVisibility(ProgressBar.GONE);
//Spinner Adapter
setNavigationMode(NAVIGATION_MODE_LIST);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list,
android.R.layout.simple_spinner_dropdown_item);
//innitialize Sensor Manager
mSensor = (SensorManager)getSystemService(SENSOR_SERVICE);
//signin
try {
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
mClient = new MobileServiceClient(
"secret",
"secret",
this).withFilter(new ProgressFilter());
} catch (MalformedURLException e) {
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
authenticate();
}
/**
* Initializes the activity menu
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Select an option from the menu
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_refresh) {
}
return true;
}
/**
* Creates a dialog and shows it
*
* #param exception
* The exception to show in the dialog
* #param title
* The dialog title
*/
private void createAndShowDialog(Exception exception, String title) {
createAndShowDialog(exception.toString(), title);
}
/**
* Creates a dialog and shows it
*
* #param message
* The dialog message
* #param title
* The dialog title
*/
private void createAndShowDialog(String message, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private class ProgressFilter implements ServiceFilter {
#Override
public void handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback,
final ServiceFilterResponseCallback responseCallback) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.VISIBLE);
}
});
nextServiceFilterCallback.onNext(request, new ServiceFilterResponseCallback() {
#Override
public void onResponse(ServiceFilterResponse response, Exception exception) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.GONE);
}
});
if (responseCallback != null) responseCallback.onResponse(response, exception);
}
});
}
}
private void authenticate() {
// Login using the Google provider.
mClient.login(MobileServiceAuthenticationProvider.MicrosoftAccount,
new UserAuthenticationCallback() {
#Override
public void onCompleted(MobileServiceUser user,
Exception exception, ServiceFilterResponse response) {
if (exception == null) {
createAndShowDialog(String.format(
"You are now logged in - %1$2s",
user.getUserId()), "Success");
service = new ConnectWithService(mClient,user.getUserId());
orientation = new Detection(mSensor);
} else {
createAndShowDialog("You must log in. Login Required", "Error");
}
}
});
}
//start sensors camera etc if needed
protected void onResume() {
super.onResume();
if(orientation!=null)
orientation.startSensorsListening();
}
// stop sensors etc
protected void onPause() {
super.onPause();
orientation.stopSensorListening();
}
}
theres at least two errors i think mOnNavigationListener should be somewhere else
setnavigationMode() has an error
don't use OnNavigationListener with (ActionBar.NAVIGATION_MODE_LIST)
use:
final ActionBar bar = getActionBar();
bar.setDisplayShowCustomEnabled(true);
bar.setCustomView(R.layout.action_bar_custom);
then all as normal.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>....

Categories

Resources