YouTubePlayerFragment not working(Playing) in CollapsingToolbarLayout - android

YouTubePlayerFragment not working(Playing) in CollapsingToolbarLayout.
I want to play youtube video from youtube android api. Inside CollapsingToolbarLayout, YouTubePlayerFragment does not play, only thumbnail comes and after 1 seconds it goes to stop.
I it work fine inside other layout. I want material design collapsing layout with youtube video. Please help me.
<android.support.design.widget.CoordinatorLayout
android:id="#+id/root_coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<!--<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/ic_launcher"
android:visibility="visible"
app:layout_collapseMode="parallax" />-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutYoutube"
android:layout_width="match_parent"
android:layout_height="250dp"
android:visibility="visible"
app:layout_collapseMode="parallax">
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_collapseMode="pin">
<include
layout="#layout/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/frameContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="1dp"
android:background="#android:color/white"
android:paddingTop="2dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>

The official documentation says:
Note that while videos are playing, this View has a minimum size of 200x110 dp. If you make the view any smaller, videos will automatically stop playing. Also, it is not permitted to overlay this fragment's view with other views while a video is playing.
So there is no way to get to work YouTubePlayerFragment and
YouTubePlayerView in CollapsingToolbarLayout.
PS: If someone managed to do it - share the solution. I had this same problem, but I could not solve it.

It would have been helpful if you had posted the logic code or java code and the error log. I am posting the java code, please take a look at this one might work for you too...
public class YoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "xxxxxxxxxx";
public static final String VIDEO_ID = "xxxxxxx";
private YouTubePlayer youTubePlayer;
private YouTubePlayerFragment youTubePlayerFragment;
private TextView textVideoLog;
private Button btnViewFullScreen;
private static final int RQS_ErrorDialog = 1;
private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;
String log = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtube);
youTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerFragment.initialize(API_KEY, this);
textVideoLog = (TextView)findViewById(R.id.videolog);
myPlayerStateChangeListener = new MyPlayerStateChangeListener();
myPlaybackEventListener = new MyPlaybackEventListener();
btnViewFullScreen = (Button)findViewById(R.id.btnviewfullscreen);
btnViewFullScreen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
youTubePlayer.setFullscreen(true);
}});
Button btnPlay = (Button) findViewById(R.id.btnplay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(youTubePlayer.isPlaying())
youTubePlayer.pause();
else
youTubePlayer.play();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_splash_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.e("id", id+"");
switch(item.getItemId()){
case R.id.action_share:
break;
case 16908332:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youtube, boolean b) {
youTubePlayer = youtube;
Toast.makeText(getApplicationContext(), "YouTubePlayer.onInitializationSuccess()", Toast.LENGTH_LONG).show();
youtube.setPlayerStateChangeListener(myPlayerStateChangeListener);
youtube.setPlaybackEventListener(myPlaybackEventListener);
if (!b) {
youTubePlayer.cueVideo(VIDEO_ID);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,"YouTubePlayer.onInitializationFailure(): " + youTubeInitializationResult.toString(),Toast.LENGTH_LONG).show();
}
}
private final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
private void updateLog(String prompt){
log += "MyPlayerStateChangeListener" + "\n" +prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onAdStarted() {
updateLog("onAdStarted()");
}
#Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
updateLog("onError(): " + arg0.toString());
}
#Override
public void onLoaded(String arg0) {
updateLog("onLoaded(): " + arg0);
}
#Override
public void onLoading() {
updateLog("onLoading()");
}
#Override
public void onVideoEnded() {
updateLog("onVideoEnded()");
}
#Override
public void onVideoStarted() {
updateLog("onVideoStarted()");
}
}
private final class MyPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {
private void updateLog(String prompt){
log += "MyPlaybackEventListener" + "\n-" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onBuffering(boolean arg0) {
updateLog("onBuffering(): " + String.valueOf(arg0));
}
#Override
public void onPaused() {
updateLog("onPaused()");
}
#Override
public void onPlaying() {
updateLog("onPlaying()");
}
#Override
public void onSeekTo(int arg0) {
updateLog("onSeekTo(): " + String.valueOf(arg0));
}
#Override
public void onStopped() {
updateLog("onStopped()");
}
}

Related

YouTubePlayer api issue

I play video in MainActivityand video is playig fine. While playing video, if I open the same activity another time and come back to previous MainActivity youtube progressbar keeps turning and nothing happens. I read the documentation and couldn't find anything related this problem. Indeed, the documentation is very old (updated in 2015), and YouTubeAndroidPlayerApi library was updated in 2017. Guide me to right direction.
MainActivity.java
public class MainActivity extends YouTubeBaseActivity
implements YouTubePlayer.OnInitializedListener {
private String YOUTUBE_API_KEY = "api_key";
private YouTubePlayerView youtubePlayerView;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
youtubePlayerView = findViewById(R.id.youtubePlayer);
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Log.w("youtube_activity", "onInitialization success");
youTubePlayer.loadVideo("0KSOMA3QBU0");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(this, "Initialization failure", Toast.LENGTH_SHORT);
}
public void onClick(View view) {
startActivity(new Intent(this, MainActivity.class));
}
}
layout xml
<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">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.google.android.youtube.player.YouTubePlayerView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="onClick"
android:text="Button" />
</LinearLayout>
Found solution with releasing YouTubePlayer when going to another youtubeplayeractivity. When came back to previous youtubeplayeractivity reninitialized YouTubePlayerView.
public void onClick(View view) {
youTubePlayer.release();
startActivity(new Intent(this, MainActivity.class));
}
#Override
protected void onRestart() {
super.onRestart();
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}

YoutubePlayer is not playing video and giving error "Network error (400)

I am trying to load a YouTube's video and play it but it is showing network error with error code 400.I am using You tube player ( you can see in xml),I have already registered the app in developer console and followed instructions, but after loading sometimes, it is showing "An error occured" Don't know what i am missing.Any help is appreciated. Thanks
public class AboutDescriptionActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private YouTubePlayerView youTubeView;
Toolbar toolbar;
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_description);
toolbar = (Toolbar) findViewById(R.id.aboutscreentoolbar);
toolbar.setTitle("About");
youTubeView = (YouTubePlayerView) findViewById(R.id.videoviewabout);
youTubeView.initialize(Config.DEVELOPER_KEY,this);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.backarrowicon));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to do on back clicked
onBackPressed();
}
});
}
#Override
public void onBackPressed() {
finish();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
player.cueVideo("https://youtu.be/CMvxh_uXEUc",1);
player.play();
// Hiding player controls
player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST){
getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
}
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.videoviewabout);
}
}
And my XML file is
<?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:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.simpalm.peacenow_android.AboutDescriptionActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/aboutscreentoolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="#style/ToolbarStyle"
app:titleTextColor="#ffffff"/>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/aboutscreentoolbar"
android:fillViewport="false"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/abouttextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/aboutscreentoolbar"
android:layout_marginTop="20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/Abouttext"
android:textSize="18sp"
android:textStyle="bold"/>
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:id="#+id/videoviewabout">
</com.google.android.youtube.player.YouTubePlayerView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Instead of passing complete URL pass only YouTube VideoID
Instead of this
player.cueVideo("https://youtu.be/CMvxh_uXEUc",1);
Try this
player.cueVideo("CMvxh_uXEUc",1);

Getting Youtube videos using RecyclerView and cardView with Firebase in Android studio

I have been working on an android project in which I have used YouTube API and Firebase as a database, I also used recyclerView in it but my videos from Firebase database are not showing in the application, I have implemented it correctly I guess but there is something wrong with it, please help.
I am using Android Studio
YouTube Firebase Adapter java class:
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.youtube_videos);
YDatabaseReference = FirebaseDatabase.getInstance().getReference().child("youT");
YouRecycler = (RecyclerView)findViewById(R.id.Youtube_recycler);
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder> firebaseRecyclerAdapter = 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.getYoutubing());
}
};
YouRecycler.setAdapter(firebaseRecyclerAdapter);
}
public static class YoutubeViewHolder extends RecyclerViewPager.ViewHolder {
View yView;
public YoutubeViewHolder(View itemView) {
super(itemView);
yView = itemView;
}
public void setYoutube(final String youtubing){
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.cueVideo(youtubing);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
Getter and setters class :
public class post2youtube {
private String youtubing;
public post2youtube(){
}
public post2youtube(String youtubing) {
this.youtubing = youtubing;
}
public String getYoutubing() {
return youtubing;
}
public void setYoutubing(String youtubing) {
this.youtubing = youtubing;
}
}
RecyclerView xml 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>
CardView xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtuber"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
</android.support.v7.widget.CardView>

SwipeRefreshLayout got error and cannot refresh (load more) in the first time

I am trying to implement "Swipe to load more" method in my application but I got that error when I swipe down in the first time. This is what it showed in the console:
E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have an active
pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have
an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but
don't have an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE
event but don't have an active pointer id.
This is my layout code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="training.com.chatgcmapplication.ChatActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="380dp">
<ListView
android:id="#+id/listMessage"
android:layout_width="match_parent"
android:layout_height="380dp"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:divider="#null"
android:listSelector="#android:color/transparent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />
</android.support.v4.widget.SwipeRefreshLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txt_chat"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.92"
android:inputType="text" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:text="#string/btn_send" />
</LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
And when I swipe in the second time: it load double data.
This is ChatActivity, what implement that method:
public class ChatActivity extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
private static EditText txt_chat;
private String registId;
private String chatTitle;
private MessageSender mgsSender;
private int userId;
private DatabaseHelper databaseHelper;
private TimeUtil timeUtil;
private MessageAdapter messageAdapter;
private int offsetNumber = 5;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Button btn_send = (Button) findViewById(R.id.btn_send);
txt_chat = (EditText) findViewById(R.id.txt_chat);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
swipeRefreshLayout.setOnRefreshListener(this);
ListView lv_message = (ListView) findViewById(R.id.listMessage);
timeUtil = new TimeUtil();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
btn_send.setOnClickListener(this);
Bundle bundle = getIntent().getExtras();
chatTitle = bundle.getString("titleName");
if (getIntent().getBundleExtra("INFO") != null) {
chatTitle = getIntent().getBundleExtra("INFO").getString("name");
this.setTitle(chatTitle);
} else {
this.setTitle(chatTitle);
}
registId = bundle.getString("regId");
userId = databaseHelper.getUser(chatTitle).getUserId();
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), 0);
messageAdapter = new MessageAdapter(getApplicationContext(), R.layout.chat_item, (ArrayList<Message>) messages);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if (messages.size() > 0) lv_message.setAdapter(messageAdapter);
}
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(userId);
messageObj.setSender_id(AppConfig.USER_ID);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
super.onDestroy();
}
private static MessageSenderContent createMegContent(String regId, String title) {
String message = txt_chat.getText().toString();
MessageSenderContent mgsContent = new MessageSenderContent();
mgsContent.addRegId(regId);
mgsContent.createData(title, message);
return mgsContent;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
String message = txt_chat.getText().toString();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
mgsSender = new MessageSender();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
MessageSenderContent mgsContent = createMegContent(registId, AppConfig.USER_NAME);
mgsSender.sendPost(mgsContent);
return null;
}
}.execute();
databaseHelper.addMessage(message, timeUtil.getCurrentTime(), userId, AppConfig.USER_ID);
txt_chat.setText("");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(AppConfig.USER_ID);
messageObj.setSender_id(userId);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), offsetNumber);
messageAdapter.insertToTheFirst(messages);
messageAdapter.notifyDataSetChanged();
offsetNumber += 5;
Log.i("Offset number", offsetNumber + "");
swipeRefreshLayout.setRefreshing(false);
}
}
UPDATE ISSUE's REASON
I found the reason of that issue. It due to I force the listview scroll to the bottom when it init with this code :
android:stackFromBottom="true"
I replace that code with this but still have same issue:
lv_message.post(new Runnable() {
#Override
public void run() {
lv_message.setSelection(lv_message.getCount() -1);
}
});
I think the problem is , You are trying to show , dismiss and refresh swipeRefreshLayout inside the same method i.e onRefresh().
Make seperate methods for showing and dismissing dialog and invoke them from the place where they are required as I have done below:
#Override
public void onRefresh() {
// refresh code here.
}
#Override
public void showDialog() {
swipeRef.post(new Runnable() {
#Override
public void run() {
if(swipeRef != null)
swipeRef.setRefreshing(true);
}
});
}
#Override
public void dismissDialog() {
if(swipeRef!=null && swipeRef.isShown() )
swipeRef.setRefreshing(false);
}

Error saving image from camera(cwac camera)

I am trying to implement the cwac camera library for taking picture and storing them. When i tested the code on htc desire hd there were few complications. This is the screenshot of camera preview.
And when I take picture it shows image preview as.
The codes I have for this are as follows.
This is Activity for implementing camera preview fragment.
public class Camera extends ActionBarActivity implements CameraPreviewFragment.Contract {
private static final String STATE_SINGLE_SHOT="single_shot";
private static final String STATE_LOCK_TO_LANDSCAPE=
"lock_to_landscape";
private static final int CONTENT_REQUEST=1337;
private CameraPreviewFragment std=null;
private CameraPreviewFragment ffc=null;
private CameraPreviewFragment current=null;
private boolean hasTwoCameras=(android.hardware.Camera.getNumberOfCameras() > 1);
private boolean singleShot=false;
private boolean isLockedToLandscape=false;
private Toolbar mToolbar;
private void setToolBar(int toolbarId){
mToolbar = (Toolbar) findViewById(toolbarId);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
setToolBar(R.id.toolbar);
if (savedInstanceState == null) {
CameraPreviewFragment frag = new CameraPreviewFragment();
frag = CameraPreviewFragment.newInstance(false);
getFragmentManager().beginTransaction()
.add(R.id.container, frag)
.commit();
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
setSingleShotMode(savedInstanceState.getBoolean(STATE_SINGLE_SHOT));
isLockedToLandscape=
savedInstanceState.getBoolean(STATE_LOCK_TO_LANDSCAPE);
if (current != null) {
current.lockToLandscape(isLockedToLandscape);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(STATE_SINGLE_SHOT, isSingleShotMode());
outState.putBoolean(STATE_LOCK_TO_LANDSCAPE, isLockedToLandscape);
}
#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_menu_camera, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean isSingleShotMode() {
return true;
}
#Override
public void setSingleShotMode(boolean mode) {
}
}
And here is my camera preview fragment.(to load camera and has button for taking image)
public class CameraPreviewFragment extends CameraFragment implements SeekBar.OnSeekBarChangeListener, View.OnClickListener{
private static final String DEBUG = CameraPreviewFragment.class.getSimpleName();
private static final String KEY_USE_FFC=
"com.commonsware.cwac.camera.demo.USE_FFC";
private MenuItem singleShotItem=null;
private boolean singleShotProcessing=false;
private static final int FLASH_ALWAYS_OFF = 0;
private static final int FLASH_ALWAYS_ON = 1;
private static final int FLASH_AUTO_MODE = 2;
private SeekBar zoom=null;
private View mCameraView;
private ImageButton mTakePicture;
private Button mFlashButton;
private Button mGridButton;
private ImageView mGridLines;
private long lastFaceToast=0L;
private int flashState = 2;
String flashMode=null, autoFlashMode=null, noFlashMode= null;
private DemoCameraHost cameraHost;
static CameraPreviewFragment newInstance(boolean useFFC) {
CameraPreviewFragment f=new CameraPreviewFragment();
Bundle args=new Bundle();
args.putBoolean(KEY_USE_FFC, useFFC);
f.setArguments(args);
return(f);
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setHasOptionsMenu(true);
cameraHost = new DemoCameraHost(getActivity());
SimpleCameraHost.Builder builder=
new SimpleCameraHost.Builder(cameraHost);
setHost(builder.useFullBleedPreview(true).build());
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
mCameraView=
super.onCreateView(inflater, container, savedInstanceState);
View results=inflater.inflate(R.layout.fragment_camera, container, false);
mCameraView.setOnClickListener(this);
mGridLines = (ImageView) results.findViewById(R.id.ivGridLines);
mTakePicture = (ImageButton) results.findViewById(R.id.ibCaptureButton);
mTakePicture.setOnClickListener(this);
mFlashButton = (Button) results.findViewById(R.id.bFlash);
mFlashButton.setOnClickListener(this);
mGridButton = (Button) results.findViewById(R.id.bGrid);
mGridButton.setOnClickListener(this);
((ViewGroup) results.findViewById(R.id.camera)).addView(mCameraView);
zoom=(SeekBar)results.findViewById(R.id.sbZoomControl);
zoom.setKeepScreenOn(true);
return(results);
}
#Override
public void onPause() {
super.onPause();
getActivity().invalidateOptionsMenu();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_camera, menu);
singleShotItem=menu.findItem(R.id.single_shot);
singleShotItem.setChecked(getContract().isSingleShotMode());
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.single_shot:
item.setChecked(!item.isChecked());
getContract().setSingleShotMode(item.isChecked());
return(true);
case R.id.show_zoom:
item.setChecked(!item.isChecked());
zoom.setVisibility(item.isChecked() ? View.VISIBLE : View.GONE);
return(true);
}
return(super.onOptionsItemSelected(item));
}
boolean isSingleShotProcessing() {
return(singleShotProcessing);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
zoom.setEnabled(false);
zoomTo(zoom.getProgress()).onComplete(new Runnable() {
#Override
public void run() {
zoom.setEnabled(true);
}
}).go();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// ignore
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// ignore
}
Contract getContract() {
return((Contract)getActivity());
}
void takeSimplePicture() {
if (singleShotItem!=null && singleShotItem.isChecked()) {
singleShotProcessing=true;
mTakePicture.setEnabled(false);
}
PictureTransaction xact=new PictureTransaction(getHost());
xact.flashMode(getFlashMode());
takePicture(xact);
}
#Override
public void onClick(View v) {
if(v == mTakePicture){
takeSimplePicture();
}
if(v == mFlashButton){
if(flashState == FLASH_ALWAYS_OFF){
//flash to be always on
flashState = FLASH_ALWAYS_ON;
setFlashMode(flashMode);
Toast.makeText(getActivity(), "Flash! on", Toast.LENGTH_SHORT).show();
}else if(flashState == FLASH_ALWAYS_ON){
flashState = FLASH_AUTO_MODE;
setFlashMode(autoFlashMode);
Toast.makeText(getActivity(), "Flash! auto", Toast.LENGTH_SHORT).show();
}else if(flashState == FLASH_AUTO_MODE){
flashState = FLASH_ALWAYS_OFF;
setFlashMode(noFlashMode);
Toast.makeText(getActivity(), "Flash! off", Toast.LENGTH_SHORT).show();
}
}
if(v == mCameraView){
Log.i(DEBUG,"OnClick autofocus");
autoFocus();
}
if(v == mGridButton){
if(mGridLines.getVisibility() == View.VISIBLE){
mGridLines.setVisibility(View.GONE);
}else if(mGridLines.getVisibility() == View.GONE){
mGridLines.setVisibility(View.VISIBLE);
}
}
}
interface Contract {
boolean isSingleShotMode();
void setSingleShotMode(boolean mode);
}
class DemoCameraHost extends SimpleCameraHost implements
android.hardware.Camera.FaceDetectionListener {
boolean supportsFaces=false;
public DemoCameraHost(Context _ctxt) {
super(_ctxt);
}
#Override
protected File getPhotoDirectory() {
return CameraUtility.getOutputDirectory(CameraUtility.DIRECTORY_TYPE_CAMERA);
}
#Override
public boolean useFrontFacingCamera() {
if (getArguments() == null) {
return(false);
}
return(getArguments().getBoolean(KEY_USE_FFC));
}
#Override
public boolean useSingleShotMode() {
if (singleShotItem == null) {
return(false);
}
return(singleShotItem.isChecked());
}
#Override
public Camera.Size getPictureSize(PictureTransaction xact, Camera.Parameters parameters) {
return super.getPictureSize(xact, parameters);
}
#Override
public void saveImage(PictureTransaction xact, byte[] image) {
if (useSingleShotMode()) {
singleShotProcessing=false;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mTakePicture.setEnabled(true);
}
});
ImagePreviewActivity.imageToShow=image;
startActivity(new Intent(getActivity(), ImagePreviewActivity.class));
}
else {
String path = getPhotoFilename();
super.saveImage(xact, image);
}
}
#Override
public void autoFocusAvailable() {
if (supportsFaces)
startFaceDetection();
}
#Override
public void autoFocusUnavailable() {
stopFaceDetection();
}
#Override
public void onCameraFail(CameraHost.FailureReason reason) {
super.onCameraFail(reason);
Toast.makeText(getActivity(),
"Sorry, but you cannot use the camera now!",
Toast.LENGTH_LONG).show();
}
#Override
public android.hardware.Camera.Parameters adjustPreviewParameters(android.hardware.Camera.Parameters parameters) {
autoFlashMode =
CameraUtils.findBestFlashModeMatch(parameters,
android.hardware.Camera.Parameters.FLASH_MODE_RED_EYE,
android.hardware.Camera.Parameters.FLASH_MODE_AUTO,
android.hardware.Camera.Parameters.FLASH_MODE_ON);
flashMode = CameraUtils.findBestFlashModeMatch(parameters,
android.hardware.Camera.Parameters.FLASH_MODE_ON);
noFlashMode = CameraUtils.findBestFlashModeMatch(parameters,
Camera.Parameters.FLASH_MODE_OFF);
if (doesZoomReallyWork() && parameters.getMaxZoom() > 0) {
zoom.setMax(parameters.getMaxZoom());
zoom.setOnSeekBarChangeListener(CameraPreviewFragment.this);
}
else {
zoom.setEnabled(false);
}
if (parameters.getMaxNumDetectedFaces() > 0) {
supportsFaces=true;
}
else {
Toast.makeText(getActivity(),
"Face detection not available for this camera",
Toast.LENGTH_LONG).show();
}
return(super.adjustPreviewParameters(parameters));
}
#Override
public void onFaceDetection(android.hardware.Camera.Face[] faces, android.hardware.Camera camera) {
if (faces.length > 0) {
long now= SystemClock.elapsedRealtime();
if (now > lastFaceToast + 10000) {
Toast.makeText(getActivity(), "I see your face!",
Toast.LENGTH_LONG).show();
lastFaceToast=now;
}
}
}
#Override
protected File getPhotoPath() {
return super.getPhotoPath();
}
#Override
#TargetApi(16)
public void onAutoFocus(boolean success, android.hardware.Camera camera) {
super.onAutoFocus(success, camera);
mTakePicture.setEnabled(true);
}
}
}
This one is for viewing the image taken. ImagePreviewActivity
public class ImagePreviewActivity extends ActionBarActivity {
static byte[] imageToShow = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (imageToShow == null) {
Toast.makeText(this, R.string.no_image, Toast.LENGTH_LONG).show();
finish();
} else {
ImageView iv = new ImageView(this);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPurgeable = true;
opts.inInputShareable = true;
opts.inMutable = false;
opts.inSampleSize = 2;
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setImageBitmap(BitmapFactory.decodeByteArray(imageToShow,
0,
imageToShow.length,
opts));
imageToShow = null;
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
setContentView(iv);
}
}
}
And as for the xml layouts I have:
for CameraPrevirewFragment
<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"
tools:context="com.example.ballard.CWACCamera.Camera$PlaceholderFragment"
android:orientation="vertical"
android:weightSum="4">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="3">
<FrameLayout
android:id="#+id/camera"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#android:drawable/gallery_thumb"
android:id="#+id/ivGridLines"
android:visibility="gone"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sbZoomControl"
android:layout_alignParentTop="true"
android:background="#null"
android:layout_toLeftOf="#+id/bFlash"
android:layout_alignBottom="#+id/bFlash"
android:layout_toRightOf="#+id/bGrid"
android:layout_toEndOf="#+id/bGrid" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ibCaptureButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="#android:drawable/ic_menu_camera"
android:background="#null"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Flash"
android:id="#+id/bFlash"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grid"
android:id="#+id/bGrid"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</LinearLayout>
and for the camera activity I have
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/rlHomeLayout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.ballard.Login.Home" tools:ignore="MergeRootFrame"
>
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<FrameLayout`enter code here`
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar">
</FrameLayout>
</RelativeLayout>
I am using v7 toolbar as the actionbar and is as follows(toolbar.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"/>
I tried the demo of the library and is working fine on the same mobile set. Also there seems to be no problem while I was testing it on Nexus 5. I am trying this library for the first time and have no clue for solving this

Categories

Resources