Change camera orientation android - java

Hello Before starting this i would like to tell you that there are many topics with the similar title but my problem is different i am not able to change the orientation of the camera at all i have tried many things.
Following are my codes and its a live streaming project.
public class MainActivity extends Activity implements
OnClickListener,
RtspClient.Callback,
Session.Callback,
SurfaceHolder.Callback,
OnCheckedChangeListener {
public final static String TAG = "MainActivity";
private Button mButtonSave;
private Button mButtonVideo;
private ImageButton mButtonStart;
private ImageButton mButtonFlash;
private ImageButton mButtonCamera;
private ImageButton mButtonSettings;
private RadioGroup mRadioGroup;
private FrameLayout mLayoutVideoSettings;
private FrameLayout mLayoutServerSettings;
private SurfaceView mSurfaceView;
private TextView mTextBitrate;
private EditText mEditTextURI;
private EditText mEditTextPassword;
private EditText mEditTextUsername;
private ProgressBar mProgressBar;
private Session mSession;
private RtspClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mButtonVideo = (Button) findViewById(R.id.video);
mButtonSave = (Button) findViewById(R.id.save);
mButtonStart = (ImageButton) findViewById(R.id.start);
mButtonFlash = (ImageButton) findViewById(R.id.flash);
mButtonCamera = (ImageButton) findViewById(R.id.camera);
mButtonSettings = (ImageButton) findViewById(R.id.settings);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mEditTextURI = (EditText) findViewById(R.id.uri);
mEditTextUsername = (EditText) findViewById(R.id.username);
mEditTextPassword = (EditText) findViewById(R.id.password);
mTextBitrate = (TextView) findViewById(R.id.bitrate);
mLayoutVideoSettings = (FrameLayout) findViewById(R.id.video_layout);
mLayoutServerSettings = (FrameLayout) findViewById(R.id.server_layout);
mRadioGroup = (RadioGroup) findViewById(R.id.radio);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mRadioGroup.setOnCheckedChangeListener(this);
mRadioGroup.setOnClickListener(this);
mButtonStart.setOnClickListener(this);
mButtonSave.setOnClickListener(this);
mButtonFlash.setOnClickListener(this);
mButtonCamera.setOnClickListener(this);
mButtonVideo.setOnClickListener(this);
mButtonSettings.setOnClickListener(this);
mButtonFlash.setTag("off");
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
if (mPrefs.getString("uri", null) != null) mLayoutServerSettings.setVisibility(View.GONE);
mEditTextURI.setText(mPrefs.getString("uri", "default_stream"));
mEditTextPassword.setText(mPrefs.getString("password", ""));
mEditTextUsername.setText(mPrefs.getString("username", ""));
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_AAC)
.setAudioQuality(new AudioQuality(8000,16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView)
.setPreviewOrientation(90)//I tried changing this value but nothing happened it works even if i comment this line.
.setCallback(this)
.build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
Camera camera;
mSurfaceView.getHolder().addCallback(this);
selectQuality();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
mLayoutVideoSettings.setVisibility(View.GONE);
mLayoutServerSettings.setVisibility(View.VISIBLE);
selectQuality();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
mLayoutServerSettings.setVisibility(View.GONE);
toggleStream();
break;
case R.id.flash:
if (mButtonFlash.getTag().equals("on")) {
mButtonFlash.setTag("off");
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
} else {
mButtonFlash.setImageResource(R.drawable.ic_flash_off_holo_light);
mButtonFlash.setTag("on");
}
mSession.toggleFlash();
break;
case R.id.camera:
mSession.switchCamera();
break;
case R.id.settings:
if (mLayoutVideoSettings.getVisibility() == View.GONE &&
mLayoutServerSettings.getVisibility() == View.GONE) {
mLayoutServerSettings.setVisibility(View.VISIBLE);
} else {
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.GONE);
}
break;
case R.id.video:
mRadioGroup.clearCheck();
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.VISIBLE);
break;
case R.id.save:
mLayoutServerSettings.setVisibility(View.GONE);
break;
}
}
#Override
public void onDestroy(){
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
private void selectQuality() {
int id = mRadioGroup.getCheckedRadioButtonId();
RadioButton button = (RadioButton) findViewById(id);
if (button == null) return;
String text = button.getText().toString();
Pattern pattern = Pattern.compile("(\\d+)x(\\d+)\\D+(\\d+)\\D+(\\d+)");
Matcher matcher = pattern.matcher(text);
matcher.find();
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
int framerate = Integer.parseInt(matcher.group(3));
int bitrate = Integer.parseInt(matcher.group(4))*1000;
mSession.setVideoQuality(new VideoQuality(width, height, framerate, bitrate));
Toast.makeText(this, ((RadioButton)findViewById(id)).getText(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "Selected resolution: "+width+"x"+height);
}
private void enableUI() {
mButtonStart.setEnabled(true);
mButtonCamera.setEnabled(true);
}
// Connects/disconnects to the RTSP server and starts/stops the stream
public void toggleStream() {
mProgressBar.setVisibility(View.VISIBLE);
if (!mClient.isStreaming()) {
String ip,port,path;
// We save the content user inputs in Shared Preferences
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Editor editor = mPrefs.edit();
editor.putString("uri", mEditTextURI.getText().toString());
editor.putString("password", mEditTextPassword.getText().toString());
editor.putString("username", mEditTextUsername.getText().toString());
editor.commit();
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d*)/(.+)");
Matcher m = uri.matcher(mEditTextURI.getText()); m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
// mClient.setCredentials(mEditTextUsername.getText().toString(), mEditTextPassword.getText().toString());
mClient.setCredentials("umair", "123456");
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/"+path);
mClient.startStream();
} else {
// Stops the stream and disconnects from the RTSP server
mClient.stopStream();
}
}
private void logError(final String msg) {
final String error = (msg == null) ? "Error unknown" : msg;
// Displays a popup to report the eror to the user
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(msg).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onBitrateUpdate(long bitrate) {
mTextBitrate.setText(""+bitrate/1000+" kbps");
}
#Override
public void onPreviewStarted() {
if (mSession.getCamera() == CameraInfo.CAMERA_FACING_BACK) {
mButtonFlash.setEnabled(true);
mButtonFlash.setTag("off");
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
}
else {
mButtonFlash.setEnabled(true);
}
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
enableUI();
mButtonStart.setImageResource(R.drawable.ic_switch_video_active);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onSessionStopped() {
enableUI();
mButtonStart.setImageResource(R.drawable.ic_switch_video);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
mProgressBar.setVisibility(View.GONE);
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
mButtonFlash.setTag("off");
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
VideoQuality quality = mSession.getVideoTrack().getVideoQuality();
logError("The following settings are not supported on this phone: "+
quality.toString()+" "+
"("+e.getMessage()+")");
e.printStackTrace();
return;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
logError(e.getMessage());
e.printStackTrace();
}
}
#Override
public void onRtspUpdate(int message, Exception e) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
mProgressBar.setVisibility(View.GONE);
enableUI();
logError(e.getMessage());
e.printStackTrace();
break;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
//tried adding the setPreiviewOrientation(90) here also but still nothing changed.
mSession.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mClient.stopStream();
}
}
I have tried to change setPreviewOrientation also but still no changes check the codes i have commented whatever i tried please help me. click here to see the API that i have used

Add this method and call it where camera is open
private void setUpCamera(Camera c) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
rotation = getWindowManager().getDefaultDisplay().getRotation();
int degree = 0;
switch (rotation) {
case Surface.ROTATION_0:
degree = 0;
break;
case Surface.ROTATION_90:
degree = 90;
break;
case Surface.ROTATION_180:
degree = 180;
break;
case Surface.ROTATION_270:
degree = 270;
break;
default:
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// frontFacing
rotation = (info.orientation + degree) % 330;
rotation = (360 - rotation) % 360;
} else {
// Back-facing
rotation = (info.orientation - degree + 360) % 360;
}
c.setDisplayOrientation(rotation);
Parameters params = c.getParameters();
params.setRotation(rotation);
}
Add these in surfaceChanged method for image clarity and other.
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
Camera.Size size = sizes.get(0);
for(int i=0;i<sizes.size();i++)
{
if(sizes.get(i).width > size.width)
size = sizes.get(i);
}
parameters.setPictureSize(size.width, size.height);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
parameters.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
parameters.setExposureCompensation(0);
parameters.setPictureFormat(ImageFormat.JPEG);
parameters.setJpegQuality(100);
try{
camera.setParameters(parameters);
camera.startPreview();
}catch (Exception e){
}

Related

How to make customize mediacontroller for videoview

I make whole video player app but stuck at mediacontroller. I want to show my own mediacontroller with different button, not the default one. It's 4rth day, i'm just trying to make my own mediacontroller but didn't succeed.
I succeed by doing it with surfaceview but i want to use it with videoview.
I try the following code.
public class MyMediaController extends MediaController {
private static final String TAG = "VideoControllerView";
MediaController.MediaPlayerControl mPlayer;
private Context mContext;
private View mAnchor;
private View mRoot;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mSubtitleButton;
private ImageButton mResizeButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private final AccessibilityManager mAccessibilityManager;
public MyMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = null;
mContext = context;
mUseFastForward = true;
mFromXml = true;
mAccessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
public MyMediaController(Context context, boolean useFastForward) {
super(context, useFastForward);
mUseFastForward = useFastForward;
mAccessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
public MyMediaController(Context context) {
this(context, true);
mContext = context;
}
#Override
public void setMediaPlayer(MediaController.MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
}
#Override
public void setAnchorView(View view) {
mAnchor = view;
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
removeAllViews();
View v = makeControllerView();
addView(v, frameParams);
}
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.media_controller_layout, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View mRoot) {
mPauseButton = mRoot.findViewById(R.id.pause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mResizeButton = mRoot.findViewById(R.id.resize);
if (mResizeButton != null) {
mResizeButton.requestFocus();
mResizeButton.setOnClickListener(mResizeListener);
}
mSubtitleButton = mRoot.findViewById(R.id.subtitle);
if (mSubtitleButton != null)
{
mSubtitleButton.requestFocus();
mSubtitleButton.setOnClickListener(mSubtitleListener);
}
mNextButton = mRoot.findViewById(R.id.next);
if (mNextButton != null ) {
mNextButton.requestFocus();
mNextButton.setOnClickListener(mNextListener);
}
mPrevButton = mRoot.findViewById(R.id.prev);
if (mPrevButton != null ) {
mPrevButton.requestFocus();
mPrevButton.setOnClickListener(mPrevListener);
}
mProgress = mRoot.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = mRoot.findViewById(R.id.time);
mCurrentTime = mRoot.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
}
public final View.OnClickListener mPauseListener = new OnClickListener() {
#Override
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private void doPauseResume() {
if (mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private void updatePausePlay() {
if (mRoot == null || mPauseButton == null)
return;
if (mPlayer.isPlaying())
mPauseButton.setImageResource(R.drawable.ic_pause);
else
mPauseButton.setImageResource(R.drawable.ic_play);
}
public final View.OnClickListener mResizeListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"Resize is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mNextListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"NextBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mPrevListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"PreviousBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mSubtitleListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"subtitleBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
private final SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
mDragging = true;
// By removing these pending progress messages we make sure
// that a) we won't update the progress while the user adjusts
// the seekbar and b) once the user is done dragging the thumb
// we will post one of these messages to the queue again and
// this ensures that there will be exactly one message queued up.
removeCallbacks(mShowProgress);
}
#Override
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (!fromuser) {
// We're not interested in programmatically generated changes to
// the progress bar's position.
return;
}
long duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo( (int) newposition);
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime( (int) newposition));
}
#Override
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
// Ensure that progress is properly updated in the future,
// the call to show() does not guarantee this because it is a
// no-op if we are already showing.
post(mShowProgress);
}
};
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress( (int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private final Runnable mShowProgress = new Runnable() {
#Override
public void run() {
int pos = setProgress();
if (!mDragging && mShowing && mPlayer.isPlaying()) {
postDelayed(mShowProgress, 1000 - (pos % 1000));
}
}
};
#Override
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
setProgress();
if (mPauseButton != null) {
mPauseButton.requestFocus();
}
FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
addView(this, tlp);
mShowing = true;
}
updatePausePlay();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
post(mShowProgress);
if (timeout != 0 && !mAccessibilityManager.isTouchExplorationEnabled()) {
removeCallbacks(mFadeOut);
postDelayed(mFadeOut, timeout);
}
}
#Override
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
#Override
public void hide() {
if (mAnchor == null)
return;
if (mShowing) {
try {
removeCallbacks(mShowProgress);
removeView(this);
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
mShowing = false;
}
}
private final Runnable mFadeOut = new Runnable() {
#Override
public void run() {
hide();
}
};
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
show(0);
break;
case MotionEvent.ACTION_UP:
show(sDefaultTimeout);
break;
case MotionEvent.ACTION_CANCEL:
hide();
break;
default:
break;
}
return true;
}
}
Plz someone suggest my the right way to do it. I realy need help.

What is the easiest way to update a textView from a service?

I am making an app which consists of an activity and a service. By pressing a button the service is started, it collects data in the background from a sensor and classifies it and outputs a string. I want to display the string in a textView. Right now I can see in the log that the variable is updated 2 times every second, but when I try and update the textView from the service class nothing is happening unless I press the button, whenever I press the button, the string is displayed in the textView.
What is the easiest solution here? I tried to make the textView static and it still can't update it. Can you make it so that the view is updated automatically every second? Can I add a listener somehow? Since I am not very experienced I would like an easy solution that does not have to be a "good" one.
Here is my code
Activity:
public class CollectorActivity extends Activity {
private enum State {
IDLE, COLLECTING, TRAINING, CLASSIFYING
};
private final String[] mLabels = { Globals.CLASS_LABEL_STANDING,
Globals.CLASS_LABEL_WALKING, Globals.CLASS_LABEL_RUNNING,
Globals.CLASS_LABEL_OTHER };
private RadioGroup radioGroup;
private final RadioButton[] radioBtns = new RadioButton[4];
private Intent mServiceIntent;
private File mFeatureFile;
public static TextView mCurrentLabel;
private State mState;
private Button btnDelete;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radioGroup = (RadioGroup) findViewById(R.id.radioGroupLabels);
radioBtns[0] = (RadioButton) findViewById(R.id.radioStanding);
radioBtns[1] = (RadioButton) findViewById(R.id.radioWalking);
radioBtns[2] = (RadioButton) findViewById(R.id.radioRunning);
radioBtns[3] = (RadioButton) findViewById(R.id.radioOther);
btnDelete = (Button) findViewById(R.id.btnDeleteData);
mCurrentLabel = (TextView) findViewById(R.id.textView);
mState = State.IDLE;
mFeatureFile = new File(getExternalFilesDir(null),
Globals.FEATURE_FILE_NAME);
mServiceIntent = new Intent(this, SensorsService.class);
}
public void onCollectClicked(View view) {
if (mState == State.IDLE) {
mState = State.COLLECTING;
((Button) view).setText(R.string.ui_collector_button_stop_title);
btnDelete.setEnabled(false);
radioBtns[0].setEnabled(false);
radioBtns[1].setEnabled(false);
radioBtns[2].setEnabled(false);
radioBtns[3].setEnabled(false);
int acvitivtyId = radioGroup.indexOfChild(findViewById(radioGroup
.getCheckedRadioButtonId()));
String label = mLabels[acvitivtyId];
Bundle extras = new Bundle();
extras.putString(Globals.CLASS_LABEL_KEY, label);
mServiceIntent.putExtras(extras);
startService(mServiceIntent);
} else if (mState == State.COLLECTING) {
mState = State.IDLE;
((Button) view).setText(R.string.ui_collector_button_start_title);
btnDelete.setEnabled(true);
radioBtns[0].setEnabled(true);
radioBtns[1].setEnabled(true);
radioBtns[2].setEnabled(true);
radioBtns[3].setEnabled(true);
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();
}
}
public void onDeleteDataClicked(View view) {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
if (mFeatureFile.exists()) {
mFeatureFile.delete();
}
Toast.makeText(getApplicationContext(),
R.string.ui_collector_toast_file_deleted,
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (mState == State.TRAINING) {
return;
} else if (mState == State.COLLECTING || mState == State.CLASSIFYING) {
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel(Globals.NOTIFICATION_ID);
}
super.onBackPressed();
}
#Override
public void onDestroy() {
// Stop the service and the notification.
// Need to check whether the mSensorService is null or not.
if (mState == State.TRAINING) {
return;
} else if (mState == State.COLLECTING || mState == State.CLASSIFYING) {
stopService(mServiceIntent);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancelAll();
}
finish();
super.onDestroy();
}
And this is the "doInBackground" method in my service class. The line "CollectorActivity.mCurrentLabel.setText(classification);" is the problem. I want this to update the textView continously.
public class OnSensorChangedTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Instance inst = new DenseInstance(mFeatLen);
inst.setDataset(mDataset);
Instance inst2 = new DenseInstance(65);
int blockSize = 0;
FFT fft = new FFT(Globals.ACCELEROMETER_BLOCK_CAPACITY);
double[] accBlock = new double[Globals.ACCELEROMETER_BLOCK_CAPACITY];
double[] re = accBlock;
double[] im = new double[Globals.ACCELEROMETER_BLOCK_CAPACITY];
double max = Double.MIN_VALUE;
while (true) {
try {
// need to check if the AsyncTask is cancelled or not in the while loop
if (isCancelled () == true)
{
return null;
}
// Dumping buffer
accBlock[blockSize++] = mAccBuffer.take().doubleValue();
if (blockSize == Globals.ACCELEROMETER_BLOCK_CAPACITY) {
blockSize = 0;
testList = new ArrayList<Double>();
// time = System.currentTimeMillis();
max = .0;
for (double val : accBlock) {
if (max < val) {
max = val;
}
}
fft.fft(re, im);
for (int i = 0; i < re.length; i++) {
double mag = Math.sqrt(re[i] * re[i] + im[i]
* im[i]);
inst.setValue(i, mag);
testList.add(i,mag);
im[i] = .0; // Clear the field
}
// Append max after frequency component
inst.setValue(Globals.ACCELEROMETER_BLOCK_CAPACITY, max);
inst2.setValue(Globals.ACCELEROMETER_BLOCK_CAPACITY, max);
testList.add(max);
classificationIndex = WekaClassifier.classify(testList.toArray());
classification = testLabel.get((int) classificationIndex);
CollectorActivity.mCurrentLabel.setText(classification);
inst.setValue(mClassAttribute, mLabel);
mDataset.add(inst);
Log.i("new instance", mDataset.size() + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
In doInBackground(Void... arg0) change CollectorActivity.mCurrentLabel.setText(classification); to publishProgress(classification); then change second argument from Void to String: public class OnSensorChangedTask extends AsyncTask<Void, Srting, Void> and add onProgressUpdate().
Finally your code should looks like:
public class OnSensorChangedTask extends AsyncTask<Void, Srting, Void> {
#Override
protected Void doInBackground(Void... arg0) {
//...
publishProgress(classification);
//...
}
#Override
protected Void onProgressUpdate(String... classification) {
CollectorActivity.mCurrentLabel.setText(classification[0]);
}

Countdown timer, points and incorrect multiplying

I have this code as a method:
String resultTimeString = ct.toString()
if(resultTimeString.length() == 2 ){
resultTime1ASCII = resultTimeString.charAt(0);
resultTime2ASCII = resultTimeString.charAt(1);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime2 = (int)resultTime2ASCII - 48;
resultTime = resultTime1 + resultTime2;
}
else{
resultTime1ASCII = resultTimeString.charAt(0);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime = resultTime1;
}
punkty = punkty * resultTime;
//Globals.setScore(punkty);
ct.cancel();
The problem is in counting. Final score ("punkty") isn't multiply punkty and resultTime and I don't know why. Variable punkty is define as a points from giving a good answer.
Timer count down from 60 to 0.
You have said that the final score always remains 0.
The only way this could be happening is when you have initialized punkty as 0.
Each time, it multiplies by 0, and remains 0.
You should initialize punkty as 1. Then your code will work.
#Hackerdarshi, maybe I will show You all code:
public class QuestionActivity extends Activity {
private static final String TAG = "suemar";
int position = 0;
Button buttonA;
Button buttonB;
Button buttonC;
Button buttonD;
TextView textView;
TextView count;
Retrofit retrofit;
QuestionService questionService;
Call<pytania> QACall;
pytania questionsAnswers;
int licz = 0, punkty = 0;
String id;
char resultTime1ASCII,resultTime2ASCII;
int resultTime=0, resultTime1=0, resultTime2=0;
CountDownTimer ct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
buttonA = (Button) findViewById(R.id.buttonA);
buttonB = (Button) findViewById(R.id.buttonB);
buttonC = (Button) findViewById(R.id.buttonC);
buttonD = (Button) findViewById(R.id.buttonD);
textView = (TextView) findViewById(R.id.textView_pytanie);
count = (TextView) findViewById(R.id.countText);
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
ct = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
String v = String.format("%02d", millisUntilFinished/60000);
int va = (int)( (millisUntilFinished%60000)/1000);
count.setText(String.format("%02d", va));
}
public void onFinish() {
count.setText("0");
koniec();
}
};
ct.start();
Intent intent = getIntent();
position = intent.getExtras().getInt("position");
position++;
id = Integer.toString(position);
//Retrofit magic part
retrofit = new Retrofit.Builder()
.baseUrl("http://46.101.128.24/")
.addConverterFactory(GsonConverterFactory.create())
.build();
questionService = retrofit.create(QuestionService.class);
QACall = questionService.getQuestionsAnswers(id);
QACall.enqueue(new Callback<pytania>() {
#Override
public void onResponse(Call<pytania> call, Response<pytania> response) {
if (response.isSuccessful()) {
questionsAnswers = response.body();
// textView.setText(Integer.toString(questionsAnswers.success));
giveQuestions();
for (Questions c : questionsAnswers.Questions) {
Log.i(TAG, String.format("%s: %s", c.question, c.answer1));
Log.i(TAG, "---------");
}
} else {
Toast.makeText(QuestionActivity.this, "LOL2", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<pytania> call, Throwable t) {
Log.d("Coś się zepsuło", t.getMessage());
Toast.makeText(QuestionActivity.this, "LOL", Toast.LENGTH_SHORT).show();
}
});
}
public void onAnswer(View view) {
licz++;
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
switch (view.getId()) {
case R.id.buttonA:
buttonA.setBackgroundResource(R.drawable.button_game_click);
if (buttonA.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonB:
buttonB.setBackgroundResource(R.drawable.button_game_click);
if (buttonB.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonC:
buttonC.setBackgroundResource(R.drawable.button_game_click);
if (buttonC.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonD:
buttonD.setBackgroundResource(R.drawable.button_game_click);
if (buttonD.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
}
if (licz == 5) {
koniec();
} else {
Runnable r = new Runnable() {
#Override
public void run() {
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
giveQuestions();
}
};
Handler h = new Handler();
h.postDelayed(r, 300);
}
}
private void koniec() {
String resultTimeString = ct.toString();
//resultTime1ASCII = resultTimeString.charAt(resultTimeString.length() - 2);
//resultTime2ASCII = resultTimeString.charAt(resultTimeString.length()-1);
if(resultTimeString.length() == 2 ){
resultTime1ASCII = resultTimeString.charAt(0);
resultTime2ASCII = resultTimeString.charAt(1);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime2 = (int)resultTime2ASCII - 48;
resultTime = (resultTime1*10) + resultTime2;
}
else{
resultTime1ASCII = resultTimeString.charAt(0);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime = resultTime1;
}
punkty = punkty * resultTime;
//Globals.setScore(punkty);
ct.cancel();
Intent intent = new Intent(QuestionActivity.this, YourResultActivity.class);
startActivity(intent);
finish();
}
public void giveQuestions() {
questionsAnswers.Questions.get(licz).ShuffleAnswers();
textView.setText(questionsAnswers.Questions.get(licz).question);
buttonA.setText(questionsAnswers.Questions.get(licz).getAnswer(0));
buttonB.setText(questionsAnswers.Questions.get(licz).getAnswer(1));
buttonC.setText(questionsAnswers.Questions.get(licz).getAnswer(2));
buttonD.setText(questionsAnswers.Questions.get(licz).getAnswer(3));
}
}

How to create game loop for Android Wear app

What I'm trying to do is make an version of the game Simon for android wear. I don't want to use libgdx, tho I could if I have no other choice.
The way the game works is that the computer shows a button sequence to the player and then the player is to repeat the sequence back. I've got it all working fine except for I can't seem to animate a sequence to the player.
What I have is a random number generator. Using the number generated I want to change the color of the button background for a small time, then change it back. And I loop this a set number of times. I've tried SystemClock.sleep(500), but it just runs the loop before even showing the app.
The main problem is that everything has to be done inside an onLayoutInflated because of how wear has to choose between round and square faces. And this has to be done in the onCreate method as far as I know.
Does anyone know a way of doing some sort of game loop and/or animation sequence for android wear.
P.S. I will append my code as soon as I fix it. I've been fiddling with it a lot.
package com.happypantzinc.memory;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.wearable.view.WatchViewStub;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends Activity {
private ImageButton mOverlay, mTopLeft, mTopRight, mBotLeft, mBotRight;
private Boolean isPlayerTurn = false;
private Boolean isRunning = false;
private Random random = new Random();
private int level = 10;
private ArrayList<Integer> compSeq;
private ArrayList<Integer> playSeq;
private float screenW, screenH;
//setup colors
final int RED_UP = Color.rgb(180, 0, 0);
final int RED_DOWN = Color.rgb(255, 77, 0);
final int GREEN_UP = Color.rgb(0, 180, 0);
final int GREEN_DOWN = Color.rgb(0, 255, 77);
final int BLUE_UP = Color.rgb(0, 0, 180);
final int BLUE_DOWN = Color.rgb(0, 77, 255);
final int YELLOW_UP = Color.rgb(180, 180, 0);
final int YELLOW_DOWN = Color.rgb(255, 255, 0);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
compSeq = new ArrayList<Integer>();
playSeq = new ArrayList<Integer>();
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mOverlay = (ImageButton) stub.findViewById(R.id.overlay);
mTopLeft = (ImageButton) stub.findViewById(R.id.topLeft);
mTopRight = (ImageButton) stub.findViewById(R.id.topRight);
mBotLeft = (ImageButton) stub.findViewById(R.id.botLeft);
mBotRight = (ImageButton) stub.findViewById(R.id.botRight);
setupButtons();
setupButtonActions(mTopLeft, GREEN_UP, GREEN_DOWN);
setupButtonActions(mTopRight, RED_UP, RED_DOWN);
setupButtonActions(mBotLeft, YELLOW_UP, YELLOW_DOWN);
setupButtonActions(mBotRight, BLUE_UP, BLUE_DOWN);
mOverlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isRunning = true;
mOverlay.setClickable(false);
mOverlay.setVisibility(View.GONE);
gameLoop();
}
});
}
});
//get screen size
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenW = size.x;
screenH = size.y;
}
private void gameLoop() {
while(isRunning) {
//Computer turn
while (compSeq.size() < level) {
int val = random.nextInt(4);
if (!mOverlay.isShown()) {
//Computer shows sequence
switch (val) {
case 0:
mTopLeft.getBackground().setColorFilter(GREEN_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
SystemClock.sleep(500);
mTopLeft.getBackground().setColorFilter(GREEN_UP, PorterDuff.Mode.MULTIPLY);
break;
case 1:
mTopRight.getBackground().setColorFilter(RED_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
SystemClock.sleep(500);
mTopRight.getBackground().setColorFilter(RED_UP, PorterDuff.Mode.MULTIPLY);
break;
case 2:
mBotLeft.getBackground().setColorFilter(YELLOW_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
SystemClock.sleep(500);
mBotLeft.getBackground().setColorFilter(YELLOW_UP, PorterDuff.Mode.MULTIPLY);
break;
case 3:
mBotRight.getBackground().setColorFilter(BLUE_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
SystemClock.sleep(500);
mBotRight.getBackground().setColorFilter(BLUE_UP, PorterDuff.Mode.MULTIPLY);
break;
default:
break;
}
compSeq.add(val);
SystemClock.sleep(300);
}
}
isPlayerTurn = true;
while (playSeq.size() < level) {
//Check for correct input
if (playSeq.size() > 0 && (playSeq.get(playSeq.size()-1) != compSeq.get(playSeq.size()-1))) {
isRunning = false;
break;
}
}
playSeq.clear();
compSeq.clear();
isPlayerTurn = false;
}
}
private void setupButtons() {
//set width and height of buttons
android.view.ViewGroup.LayoutParams params;
params = mOverlay.getLayoutParams();
params.height = (int) screenH;
params.width = (int) screenW;
mOverlay.setLayoutParams(params);
params = mTopLeft.getLayoutParams();
params.height = (int)(screenH/2);
params.width = (int)(screenW/2);
mTopLeft.setLayoutParams(params);
params = mTopRight.getLayoutParams();
params.height = (int)(screenH/2);
params.width = (int)(screenW/2);
mTopRight.setLayoutParams(params);
params = mBotLeft.getLayoutParams();
params.height = (int)(screenH/2);
params.width = (int)(screenW/2);
mBotLeft.setLayoutParams(params);
params = mBotRight.getLayoutParams();
params.height = (int)(screenH/2);
params.width = (int)(screenW/2);
mBotRight.setLayoutParams(params);
//set position of buttons
mOverlay.setX(0);
mOverlay.setY(0);
mTopLeft.setX(0);
mTopLeft.setY(0);
mTopRight.setX(screenW / 2);
mTopRight.setY(0);
mBotLeft.setX(0);
mBotLeft.setY(screenH / 2);
mBotRight.setX(screenW / 2);
mBotRight.setY(screenH / 2);
//set initial background tints
mTopLeft.getBackground().setColorFilter(GREEN_UP, PorterDuff.Mode.MULTIPLY);
mTopRight.getBackground().setColorFilter(RED_UP, PorterDuff.Mode.MULTIPLY);
mBotLeft.getBackground().setColorFilter(YELLOW_UP, PorterDuff.Mode.MULTIPLY);
mBotRight.getBackground().setColorFilter(BLUE_UP, PorterDuff.Mode.MULTIPLY);
}
private void setupButtonActions(final ImageButton button, final int tint_up, final int tint_down) {
//create button listeners and tints
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isPlayerTurn) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
button.getBackground().setColorFilter(tint_down, PorterDuff.Mode.MULTIPLY);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
button.getBackground().setColorFilter(tint_up, PorterDuff.Mode.MULTIPLY);
}
//Enter correct sequence value
int val = 4;
if (button == mTopLeft) {
val = 0;
} else if (button == mTopRight) {
val = 1;
} else if (button == mBotLeft) {
val = 2;
} else if (button == mBotRight) {
val = 3;
}
playSeq.add(val);
}
return false;
}
});
}
}
You should not use SystemClock.sleep() as you are blocking the UI thread. Probably this is the cause that the animation is done before showing the activity (The activity will not show until onCreate() finishes). This can also cause the famous ANR dialog.
You can use Handlers to do the work later without blocking the UI thread:
private Handler mHandler;
private int
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
computerTurnDown();
}
}, 500); //Delay time in ms
...
}
private void computerTurnDown(){
final int val = random.nextInt(4);
if (!mOverlay.isShown()) {
//Computer shows sequence
switch (val) {
case 0:
mTopLeft.getBackground().setColorFilter(GREEN_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
break;
case 1:
mTopRight.getBackground().setColorFilter(RED_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
break;
case 2:
mBotLeft.getBackground().setColorFilter(YELLOW_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
break;
case 3:
mBotRight.getBackground().setColorFilter(BLUE_DOWN, PorterDuff.Mode.MULTIPLY);
System.out.println(val);
break;
default:
break;
}
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
computerTurnUp(val);
}
}, 500);
}
private void computerTurnUp(){
switch (val) {
case 0:
mTopLeft.getBackground().setColorFilter(GREEN_UP, PorterDuff.Mode.MULTIPLY);
break;
case 1:
mTopRight.getBackground().setColorFilter(RED_UP, PorterDuff.Mode.MULTIPLY);
break;
case 2:
mBotLeft.getBackground().setColorFilter(YELLOW_UP, PorterDuff.Mode.MULTIPLY);
break;
case 3:
mBotRight.getBackground().setColorFilter(BLUE_UP, PorterDuff.Mode.MULTIPLY);
break;
default:
break;
}
compSeq.add(val);
if (compSeq.size() < level){
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
computerTurnDown();
}
}, 300);
}else{
isPlayerTurn = true;
}
}
Whenever you want to do some work delayed use mHandler.postDelayed() and put the code in run() method.
To check the user should be done in the button listener because the way you have currently the "while (playSeq.size() < level)" will block the thread.
private void setupButtonActions(final ImageButton button, final int tint_up, final int tint_down) {
//create button listeners and tints
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (isPlayerTurn) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
button.getBackground().setColorFilter(tint_down, PorterDuff.Mode.MULTIPLY);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
button.getBackground().setColorFilter(tint_up, PorterDuff.Mode.MULTIPLY);
}
//Enter correct sequence value
int val = 4;
if (button == mTopLeft) {
val = 0;
} else if (button == mTopRight) {
val = 1;
} else if (button == mBotLeft) {
val = 2;
} else if (button == mBotRight) {
val = 3;
}
playSeq.add(val);
if(playSeq.size() < level) {
//Check for correct input
if (playSeq.size() > 0 && (playSeq.get(playSeq.size()-1) != compSeq.get(playSeq.size()-1))) {
isRunning = false;
isPlayerTurn = false;
}
}else{
playSeq.clear();
compSeq.clear();
isPlayerTurn = false;
onComputerDown();
}
}
return false;
}
});

Sharing Intent Not working Properly

I have one quote application. I have implemented share and copy function in it. I am facing issue is that I am not getting shared first time sharing quote. Means if there 50 quote in list and if I try to share any quote from list than it is not sharing anything. after that if I move on another quote and try to sharing than its working fine. I have same issue in copy function also. I also face some time issue like if I share quote number 50 than its sharing another number quote. Please help me for solve the bug. Thanks
My Activity for it is like below.
public class QuoteDialogActivity extends Activity {
DAO db;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_FAVORITE = "qu_favorite";
static final String KEY_WEB_ID = "au_web_id";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ImageButton btnnext,btnprev,star,copy;
int pos,lstcount = 0;
ScrollView ll_quote;
String quote_id;
TextView text;
String quText, quAuthor, quPicture, quFavorite,quoteShare;
int auPictureSDCard;
String isFavorite;
String auPictureDir;
String siteUrl;
private ImageLoader imgLoader;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
String TWITTER_CONSUMER_KEY;
String TWITTER_CONSUMER_SECRET;
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
Typeface tf;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
String quote;
ProgressDialog pDialog;
private SharedPreferences mSharedPreferences;
private static SharedPreferences facebookPreferences, twitterPreferences;
Cursor c, c2;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
//private UiLifecycleHelper uiHelper;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgLoader = new ImageLoader(this);
//TWITTER_CONSUMER_KEY = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
// uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
//facebookPreferences = getApplicationContext().getSharedPreferences("facebookPref", 0);
//twitterPreferences = getApplicationContext().getSharedPreferences("twitterPref", 0);
db = new DAO(this);
db.open();
c2 = db.getSettings();
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
c = db.getOneQuote(mSharedPreferences.getString("QOTD", ""));
} else {
c = db.getOneQuote(getIntent().getStringExtra("QuoteId"));
}
// if (c.getCount() != 0) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quote_dialog);
// ============================ check if user want to display
// ============================ background image for quote
if (c2.getString(c2.getColumnIndex("background")).equals("1")) {
Random random = new Random();
int idNumber = random.nextInt(20 - 1 + 1) + 1;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Drawable d = null;
try {
View topShadow = (View) findViewById(R.id.topShadow);
View bottomShadow = (View) findViewById(R.id.bottomShadow);
topShadow.setVisibility(View.INVISIBLE);
bottomShadow.setVisibility(View.INVISIBLE);
d = Drawable.createFromStream(getAssets().open("backgrounds/" + String.valueOf(idNumber) + ".jpg"),
null);
layout.setBackgroundDrawable(d);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// ===========================================================================================
quText = c.getString(c.getColumnIndex(KEY_TEXT));
quAuthor = c.getString(c.getColumnIndex(KEY_AUTHOR));
quPicture = c.getString(c.getColumnIndex(KEY_PICTURE));
auPictureSDCard = c.getInt(c.getColumnIndex(KEY_PICTURE_SDCARD));
quFavorite = c.getString(c.getColumnIndex(KEY_FAVORITE));
text = (TextView) findViewById(R.id.text); // title
// tf = Typeface.createFromAsset(getAssets(), "fonts/devnew.ttf");
//text.setTypeface(tf);
// author = (TextView) findViewById(R.id.author); // author
// picture = (ImageView) findViewById(R.id.picture); // thumb
text.setText(quText);
// author.setText("- " + quAuthor.trim());
// if (auPictureSDCard == 0) {
// AssetManager assetManager = getAssets();
// InputStream istr = null;
// try {
// istr = assetManager.open("authors_pics/" + quPicture);
// } catch (IOException e) {
// Log.e("assets", assetManager.toString());
// e.printStackTrace();
// }
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
// } else {
// siteUrl = getResources().getString(R.string.siteUrl);
//
// auPictureDir = siteUrl + "global/uploads/authors/";
// imgLoader.DisplayImage(
// auPictureDir + quPicture, picture);
// }
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open("authors_pics/" + quPicture);
} catch (IOException e) {
Log.e("assets", assetManager.toString());
e.printStackTrace();
}
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
final ImageButton dismiss = (ImageButton) findViewById(R.id.close);
dismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//=============================Next Button and Prev Button
star = (ImageButton) findViewById(R.id.star);
btnnext = (ImageButton)findViewById(R.id.nextButton);
btnprev = (ImageButton)findViewById(R.id.PrevioustButton);
pos= getIntent().getIntExtra("Pos",0);
quote_id = getIntent().getStringExtra("QuoteId");
lstcount = getIntent().getIntExtra("LstCount",0);
#SuppressWarnings("unchecked")
final ArrayList<HashMap<String, String>> quotesList =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("Quotes");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
text.setText(quotesList.get(pos).get(KEY_TEXT));
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quoteShare = quotesList.get(pos).get(KEY_TEXT);
Log.e("ErrorMsg", "quoteShare is: " + quoteShare);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();//new
Log.i("quote is",quote_id);
}
}
});
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == 1 ||pos == 0)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
text.setText(quotesList.get(p-1).get(KEY_TEXT));
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();
}
}
});
//======================================================= Swipe
ll_quote = (ScrollView)findViewById(R.id.scrollView1);
ll_quote.setOnTouchListener(new OnTouchListener() {
int downX, upX;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
if(pos == 0 || pos == 1)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(p-1).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
else if (downX - upX > -100) {
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(pos).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
return true;
}
return false;
}
});
// ========================== share button
final ImageButton share = (ImageButton) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,pos);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
//copy button
final ImageButton copyy = (ImageButton) findViewById(R.id.copy);
copyy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",quoteShare);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Status Copied",
Toast.LENGTH_LONG).show();
}
});
// ========================== set as favorite and unfavorite
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
star.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFavorite.equals("0")) {
isFavorite = "1";
star.setImageResource(R.drawable.star_on);
} else {
isFavorite = "0";
star.setImageResource(R.drawable.star_off);
}
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
db.addOrRemoveFavorites(mSharedPreferences.getString("QOTD", ""), isFavorite);
} else {
// Log.i("quotes",quotesList.get(pos).get(String.valueOf(KEY_WEB_ID))+"POS"+pos+"quid"+quotesList.get(pos).get(KEY_ID));
db.addOrRemoveFavorites(quote_id, isFavorite);
// db.addOrRemoveFavorites(getIntent().getStringExtra("QuoteId"), isFavorite);
if (getIntent().getIntExtra("quotesType", 0) == 2 && isFavorite.equals("0")) {
Intent i = new Intent(QuoteDialogActivity.this, QuotesActivity.class);
i.putExtra("quotesType", 2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(i);
}
}
}
});
// }
}
// ==============================================================================
public void FirstFav()
{
String Image_id=quote_id;
quFavorite = db.getFavQuotes(quote_id);
if(quFavorite.length()>0)
isFavorite = quFavorite;
else
isFavorite = "0";
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
}
//===================================================================================
}
Thanks

Categories

Resources