Rotation of screen causes text colour change [duplicate] - java

This question already has an answer here:
android rotating screen causes text colour to change to default
(1 answer)
Closed 4 years ago.
I am having a slight issue with my android app where the text colour changes back to a default color once I rotate my screen.
Basically I have an if statement where if Player one makes a move in selecting a button (12 buttons altogether), their selection is displayed as a particular colour, if it's not player one's move then it must be Player two where their selection is marked as a different text colour.
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("A");
((Button) v).setTextColor(Color.parseColor("#e8e5e5"));
} else {
((Button) v).setText("Z");
((Button) v).setTextColor(Color.parseColor("#737374"));
}
...
}
The above code is within OnCreate(). How can I keep my test colour within rotation? I know there is protected void onSaveInstanceState(Bundle outState) and protected void onRestoreInstanceState(Bundle savedInstanceState) but how do I call on my buttons within them?
UPDATE
private Button btnObj1;
private Button btnObj2;
private Button btnObj3;
private Button btnObj4;
private Button btnObj5;
private Button btnObj6;
private Button btnObj7;
private Button btnObj8;
private Button btnObj9;
private static final String TEXT_COLOR = "textColor";
private String textColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
textColor = savedInstanceState.getString(TEXT_COLOR);
if(btnObj1 != null) {
btnObj1.setTextColor(Color.parseColor(textColor));
}
if (btnObj2 != null) {
btnObj2.setTextColor(Color.parseColor(textColor));
}
if (btnObj3 != null) {
btnObj3.setTextColor(Color.parseColor(textColor));
}
if (btnObj4 != null) {
btnObj4.setTextColor(Color.parseColor(textColor));
}
if (btnObj5 != null) {
btnObj5.setTextColor(Color.parseColor(textColor));
}
if (btnObj6 != null) {
btnObj6.setTextColor(Color.parseColor(textColor));
}
if (btnObj7 != null) {
btnObj7.setTextColor(Color.parseColor(textColor));
}
if (btnObj8 != null) {
btnObj8.setTextColor(Color.parseColor(textColor));
}
if (btnObj9 != null) {
btnObj9.setTextColor(Color.parseColor(textColor));
}
}
if (savedInstanceState != null) {
textColor = savedInstanceState.getString(TEXT_COLOR);
btnObj1.setTextColor(Color.parseColor(textColor));
btnObj2.setTextColor(Color.parseColor(textColor));
btnObj3.setTextColor(Color.parseColor(textColor));
btnObj4.setTextColor(Color.parseColor(textColor));
btnObj5.setTextColor(Color.parseColor(textColor));
btnObj6.setTextColor(Color.parseColor(textColor));
btnObj7.setTextColor(Color.parseColor(textColor));
btnObj8.setTextColor(Color.parseColor(textColor));
btnObj9.setTextColor(Color.parseColor(textColor));
}
setContentView(R.layout.activity_main_player2);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("A");
textColor = "#e8e5e5";
((Button) v).setTextColor(Color.parseColor(textColor));
} else {
((Button) v).setText("Z");
textColor = "#737374";
((Button) v).setTextColor(Color.parseColor(textColor));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("playerOneMove", playerOneMove);
outState.putString(TEXT_COLOR, textColor);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
playerOneMove = savedInstanceState.getBoolean("playerOneMove");
textColor = savedInstanceState.getString(TEXT_COLOR);
super.onRestoreInstanceState(savedInstanceState);
}
Thanks

Whenever screen is rotated and you are not handling the configuration changes, your activity will be re-created as a result all the state of your views won't be maintained. If you can use onSaveInstanceState to store the state as follows:
private static final String TEXT_COLOR = "TEXT_COLOR";
private String textColor;
private Button btnObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnObj = findViewById(<button id>);
if (savedInstanceState != null) {
textColor = savedInstanceState.getString(TEXT_COLOR);
btnObj.setTextColor(Color.parseColor(textColor));
}
...
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("A");
textColor = "#e8e5e5";
((Button) v).setTextColor(Color.parseColor(textColor));
} else {
((Button) v).setText("Z");
textColor = "#737374";
((Button) v).setTextColor(Color.parseColor(textColor));
}
...
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(TEXT_COLOR, textColor);
super.onSaveInstanceState(savedInstanceState);
}

Related

Implement Back Pressed In Android Fragments

I've been stuck in a situation and i need some help over here. There are many articles on this topic here but none of them answered my question. I want to implement onBackPressed() in fragments and show dialog box which shows to exit the application or not. Any help would be appreciated.
LoginFragment.java
public class LoginFragment extends Fragment {
public static final String TAG = LoginFragment.class.getSimpleName();
private EditText mEtEmail;
private EditText mEtPassword;
private Button mBtLogin;
private TextView mTvRegister;
private TextView mTvForgotPassword;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private ProgressBar mProgressBar;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
#NonNull
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
mSubscriptions = new CompositeSubscription();
initViews(view);
initSharedPreferences();
return view;
}
private void initViews(View v) {
mEtEmail = v.findViewById(R.id.et_email);
mEtPassword = v.findViewById(R.id.et_password);
mBtLogin = v.findViewById(R.id.btn_login);
mTiEmail = v.findViewById(R.id.ti_email);
mTiPassword = v.findViewById(R.id.ti_password);
mProgressBar = v.findViewById(R.id.progress);
mTvRegister = v.findViewById(R.id.tv_register);
mTvForgotPassword = v.findViewById(R.id.tv_forgot_password);
mBtLogin.setOnClickListener(view -> login());
mTvRegister.setOnClickListener(view -> goToRegister());
mTvForgotPassword.setOnClickListener(view -> showDialog());
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
private void login() {
setError();
String email = mEtEmail.getText().toString();
String password = mEtPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
mProgressBar.setVisibility(View.VISIBLE);
} else {
showSnackBarMessage("Enter Valid Details !");
}
}
private void setError() {
mTiEmail.setError(null);
mTiPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email, password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
mProgressBar.setVisibility(View.GONE);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.apply();
mEtEmail.setText(null);
mEtPassword.setText(null);
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
private void handleError(Throwable error) {
mProgressBar.setVisibility(View.GONE);
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
showSnackBarMessage(response.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
} else {
showSnackBarMessage("No Internet Connection!");
}
}
private void showSnackBarMessage(String message) {
if (getView() != null) {
Snackbar.make(getView(),message,Snackbar.LENGTH_SHORT).show();
}
}
private void goToRegister(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
RegisterFragment fragment = new RegisterFragment();
ft.replace(R.id.fragmentFrame,fragment,RegisterFragment.TAG);
ft.addToBackStack(null).commit();
}
private void showDialog(){
ResetPasswordDialog fragment = new ResetPasswordDialog();
fragment.show(getFragmentManager(), ResetPasswordDialog.TAG);
}
#Override
public void onDestroy() {
super.onDestroy();
mSubscriptions.unsubscribe();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements ResetPasswordDialog.Listener {
public static final String TAG = MainActivity.class.getSimpleName();
private LoginFragment mLoginFragment;
private ResetPasswordDialog mResetPasswordDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
loadFragment();
}
}
private void loadFragment() {
if (mLoginFragment == null) {
mLoginFragment = new LoginFragment();
}
getFragmentManager().beginTransaction().replace(R.id.fragmentFrame, mLoginFragment, LoginFragment.TAG).commit();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String data = intent.getData().getLastPathSegment();
Log.d(TAG, "onNewIntent: " + data);
mResetPasswordDialog = (ResetPasswordDialog) getFragmentManager().findFragmentByTag(ResetPasswordDialog.TAG);
if (mResetPasswordDialog != null)
mResetPasswordDialog.setToken(data);
}
#Override
public void onPasswordReset(String message) {
showSnackBarMessage(message);
}
private void showSnackBarMessage(String message) {
Snackbar.make(findViewById(R.id.activity_main), message, Snackbar.LENGTH_SHORT).show();
}
}
In My Login Fragment, I want to show a dialog box "Do you want to exit the application or not". On Yes it dismiss the current fragment and end the activity otherwise it'll remain active. Help please!
You can even try this way
MainActivity.java
#Override
public void onBackPressed() {
if (getFragmentManager() != null && getFragmentManager().getBackStackEntryCount() >= 1) {
String fragmentTag = getFragmentManager().findFragmentById(R.id.frame_container).getTag();
if(fragmentTag.equals(LoginFragment.getTag())){
// show Dialog code
}else{
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
Add this code in your main activity so that when login fragment is added and you click backpress, then on first if the fragment is added to fragment transaction, then first it finds the fragment and check if its tag is equals to the login fragment tag. Then if both tag matches, then you can show your exit alert dialog.
Android team has prepared a new way of handling the back button pressed on Fragments for us, so you should check this out. It's called OnBackPressedDispatcher.
You need to register OnBackPressedCallback to the fragment where do you want to intercept back button pressed. You can do it like this inside of the Fragment:
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
//show exit dialog
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}

multiple onClickListener on a single Button

in my project, I have to use dialogs in different parts of the app and the downside is same code for creating and showing the Dialog used every time! So I decided to make a function for creating and showing a dialog and wherever I need I just call that,
the problem is, there are 2 buttons on my Dialog and before refactoring on the onClickListener I could easily use
dialog.dismiss();
// more codes ...
in setOnClickListener
but now with the incoming OnClickListener Object, I have no control over the dialog instance ...
this is the function I wrote
public static void warningAndErrorDialog(Activity activity, int titleResourceId, int iconResourceId, int contentResourceId
, HashMap<CustomDialogButton, View.OnClickListener> buttons) {
Typeface iranSansFont = setFont(activity, FontStyle.IRAN_SANS_REGULAR);
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog);
CustomFontTextView cftvTitle = (CustomFontTextView)
dialog.findViewById(R.id.txtViwDialogTitle);
if(activity.getString(titleResourceId) != null)
cftvTitle.setText(titleResourceId);
else cftvTitle.setText(" ");
CustomFontTextView cftvContent = (CustomFontTextView)
dialog.findViewById(R.id.txtViwDialogContent);
if(activity.getString(contentResourceId) != null)
cftvContent.setText(contentResourceId);
else cftvTitle.setText(" ");
ImageView imgViwDialogTitle = dialog.findViewById(R.id.imgViwDialogTitle);
imgViwDialogTitle.setImageResource(iconResourceId);
Button btnYes = null;
Button btnNo = null;
for (Map.Entry<CustomDialogButton, View.OnClickListener> button : buttons.entrySet())
switch (button.getKey()) {
case YES:
if (btnYes != null) break;
btnYes = dialog.findViewById(R.id.btnYes);
btnYes.setTypeface(iranSansFont);
if (button.getValue() != null)
btnYes.setOnClickListener(button.getValue());
break;
case NO:
if (btnNo != null) break;
btnNo = dialog.findViewById(R.id.btnNo);
if (button.getValue() != null) {
btnNo.setTypeface(iranSansFont);
btnNo.setOnClickListener(button.getValue());
} else
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
break;
case OK:
btnYes = dialog.findViewById(R.id.btnYes);
btnYes.setText(R.string.ok);
if (button.getValue() != null) btnYes.setOnClickListener(button.getValue());
else
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
btnNo = dialog.findViewById(R.id.btnNo);
btnNo.setVisibility(View.INVISIBLE);
return;
}
dialog.show();
}
notice of case YES:
I set button setOnClickListener from an onClickListener I passed to the function.
so I have no control over its content. now How Can I add statement dialog.dismiss(); ?
the Only thing I can think of is finding a way to pass an array of OnClickListener to the setOnCLickListener method.
one for dismissing the dialog and another one for setting the actual job of the button...
ps: I tried dismissing the dialog using setOnTouchListener but as I expected, that did not work...: -?
so what should I do?
final edit :
someone suggested
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (View.OnClickListener callback : callbacks)
if (callback != null)
callback.onClick(view);
}
});
(callbacks is a List of View.OnClickListener object) and thats the exact answer to "how to add multiple onClickListener on a single Button" question.
but #greenapps solution is the best solution that suits my need, thanks :)
so I share the final version of the code for whom the may concern :D :
public class CustomDialog {
private final Dialog dialog;
private Typeface font;
private CustomFontTextView cftvTitle;
private CustomFontTextView cftvContent;
private ImageView imgViwDialogTitle;
private Activity activity;
private Button btnYes;
private Button btnNo;
public CustomDialog(final Activity activity, int titleResourceId, int iconResourceId, int contentResourceId
, HashMap<CustomDialogButton, View.OnClickListener> buttons) {
font = Utility.setFont(activity, FontStyle.IRAN_SANS_REGULAR);
this.activity = activity;
dialog = new Dialog(this.activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog);
setTitleTextbyId(titleResourceId);
setContentTextById(contentResourceId);
setTitleIconById(iconResourceId);
setButtons(buttons);
}
public CustomDialog(Activity activity) {
font = Utility.setFont(activity, FontStyle.IRAN_SANS_REGULAR);
this.activity = activity;
dialog = new Dialog(this.activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog);
setTitleTextbyId(0);
setContentTextById(0);
setTitleIconById(0);
setButtons(null);
}
public void show() {
dialog.show();
}
public void setButtons(HashMap<CustomDialogButton, View.OnClickListener> buttons) {
for (final Map.Entry<CustomDialogButton, View.OnClickListener> button : buttons.entrySet())
switch (button.getKey()) {
case YES:
setButtonYes(button);
break;
case NO:
setButtonNo(button);
break;
case OK:
setButtonYes(button);
btnYes.setText(R.string.ok);
btnNo = dialog.findViewById(R.id.btnNo);
btnNo.setVisibility(View.INVISIBLE);
break;
}
}
#NonNull
private void setButtonNo(final Map.Entry<CustomDialogButton, View.OnClickListener> button) {
if (btnNo != null) return;
btnNo = dialog.findViewById(R.id.btnNo);
btnNo.setTypeface(font);
btnNo.setOnClickListener(button.getValue());
btnNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
if(button.getValue() != null)
button.getValue().onClick(view);
}
});
}
#NonNull
private void setButtonYes(final Map.Entry<CustomDialogButton, View.OnClickListener> button) {
if (btnYes != null) return;
btnYes = dialog.findViewById(R.id.btnYes);
btnYes.setTypeface(font);
btnYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
if(button.getValue() != null)
button.getValue().onClick(view);
}
});
}
public void setTitleIconById(int iconResourceId) {
this.imgViwDialogTitle = dialog.findViewById(R.id.imgViwDialogTitle);
if (activity.getResources().getDrawable(iconResourceId) != null)
imgViwDialogTitle.setImageResource(iconResourceId);
}
public void setContentTextById(int contentResourceId) {
this.cftvContent = (CustomFontTextView)
this.dialog.findViewById(R.id.txtViwDialogContent);
if (this.activity.getString(contentResourceId) != null)
cftvContent.setText(contentResourceId);
else cftvTitle.setText(" ");
}
public void setTitleTextbyId(int titleResourceId) {
this.cftvTitle = (CustomFontTextView)
this.dialog.findViewById(R.id.txtViwDialogTitle);
if (this.activity.getString(titleResourceId) != null)
cftvTitle.setText(titleResourceId);
else cftvTitle.setText(" ");
}
public void dismiss() {
dialog.dismiss();
}
}
btnYes.setOnClickListener(button.getValue());
Change to:
btnYes.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
dialog.dismiss();
button.getValue().onClick(view);
}
});

Android - java.lang.RuntimeException: takePicture failed - Is there a solution to resolve this exception for all?

public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private FrameLayout mFramePreview;
private boolean mSafeToTakePicture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
Bundle bundle = savedInstanceState;
if (savedInstanceState == null) {
bundle = getIntent().getExtras();
}
mFramePreview = (FrameLayout) findViewById(R.id.camera_preview);
mSafeToTakePicture = false;
}
#Override
protected void onResume() {
super.onResume();
// Create an instance of Camera
mCamera = getCameraInstance();
Camera.Parameters params = mCamera.getParameters();
List<Camera.Size> supportedSizes = mCamera.getParameters().getSupportedPictureSizes();
int max = 0;
int index = 0;
for (int i = 0; i < supportedSizes.size(); i++){
Camera.Size s = supportedSizes.get(i);
int size = s.height * s.width;
if (size > max) {
index = i;
max = size;
}
}
params.setPictureSize(supportedSizes.get(index).width, supportedSizes.get(index).height);
mCamera.setParameters(params);
mCamera.getParameters().setPictureSize(supportedSizes.get(index).width, supportedSizes.get(index).height);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
mFramePreview.addView(mPreview);
mSafeToTakePicture = true;
mFramePreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mSafeToTakePicture) {
takePhoto();
mFramePreview.setOnClickListener(null);
mSafeToTakePicture = false;
}
}
});
}
public void takePhoto() {
mCamera.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean b, Camera pCamera) {
mCamera.takePicture(null, null, picture);
}
});
}
final Camera.PictureCallback picture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
/* save picture... */
}
};
}
An exception sometimes happens when I take a picture.
RuntimeException->"takePicture failed" (#android.hardware.Camera:native_takePicture:-2), (#android.hardware.Camera:takePicture:1833), (#android.hardware.Camera:takePicture:1778), (#fr.selic.thuit.activities.CameraActivity$2:onAutoFocus:213), (#android.hardware.Camera$EventHandler:handleMessage:1283), (#android.os.Handler:dispatchMessage:111), (#android.os.Looper:loop:207), (#android.app.ActivityThread:main:5728), (#java.lang.reflect.Method:invoke:-2), (#com.android.internal.os.ZygoteInit$MethodAndArgsCaller:run:789), (#com.android.internal.os.ZygoteInit:main:679),

Pause music when phone receives any incoming calls, home button is pressed and when phone screen goes off(lockscreen)

while playing music using this mediaplayer, whenever a call comes, home button is pressed and lockscreen appears and on return to the app after the above problems...the play button in the app doesnt respond....I want to pause the music untill I return to the app and should continue playing from where it had stopped......plz help...
ekdanta.java
public class ekdanta extends AppCompatActivity implements Runnable,View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize((float)21.5);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
}
public void run() {
int currentPosition= play.getCurrentPosition();
int total = play.getDuration();
while (play!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setText("Play");
} else {
play.start();
but19.setText("Pause");
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
}
#Override
protected void onPause() {
if(play!=null){
play.stop();
}
super.onPause();
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize((float)21.5);
count = 0;
}
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play",Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
#Override
protected void onPause()
{
super.onPause();
if (play3!= null)
{
play3.pause();
}
}
#Override
protected void onResume()
{
super.onResume();
if ((play3 != null) && (!play3.isPlaying())) {
but32.setText("Play");
but32.setOnClickListener(this);
}
}
This helped me to overcome my problems.....I'm able to play the music which gets paused when home button/lockscreen/calls appears...from where it had stopped

how to make a graph in achartengine plot slowly

Would it b possible using the achartengine library to make it so that when a graph is plotted it does it slowly. like plot a point every milisecond? Not really sure wer to put that change.
Yes, it is possible.
You can make a timertask to do things below at intervals:
add a (x,y) pair to current series
repaint the graph
In this way, you can plot a graph "slowly".
Here is a sample written by me, which will draw a y = x^2 graph at intervals. It is not exactly what you want to do, but the principle is the same, play with it and modify it to suit your needs, tell me if you meet with any problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.plot);
// Buttons
mButtonStart = (Button) findViewById(R.id.button_plot_start);
mButtonStop = (Button) findViewById(R.id.button_plot_stop);
mButtonStart.setOnClickListener(this);
mButtonStop.setOnClickListener(this);
// Chart
mRenderer.setZoomButtonsVisible(true);
String seriesTitle = "SAMPLE"
XYSeries series = new XYSeries(seriesTitle);
mDataSet.addSeries(series);
mCurrentSeries = series;
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
renderer.setDisplayChartValues(true);
renderer.setColor(Color.RED);
mRenderer.addSeriesRenderer(renderer);
mRenderer.setXLabels(0);
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
if (mChartView == null) {
// Enable click and pan
mRenderer.setClickEnabled(true);
mRenderer.setPanEnabled(true, true);
LinearLayout layout = (LinearLayout) findViewById(R.id.linearlayout_chart);
mChartView = ChartFactory.getLineChartView(this, mDataSet, mRenderer);
mRenderer.setClickEnabled(true);
mChartView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
mChartView.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
return false;
}
});
mChartView.addZoomListener(new ZoomListener() {
public void zoomApplied(ZoomEvent e) {
}
public void zoomReset() {
}
}, true, true);
mChartView.addPanListener(new PanListener() {
public void panApplied() {
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
} else {
mChartView.repaint();
}
}
#Override
protected void onDestroy() {
if (mTimerTask != null) {
mTimerTask.cancel();
}
if (mTimer != null) {
mTimer.cancel();
}
super.onDestroy();
}
protected void updateChart() {
mCurrentSeries.add(mX, mX*mX);
mX++;
// Update the chart by repaint()
if (mChartView != null) {
mChartView.repaint();
}
}
/**
* A TimerTask class
*
*/
private class MyTimerTask extends TimerTask {
#Override
public void run() {
updateChart();
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_plot_start:
// "Start" button clicked
// Cancel current timer and timer task if existed
if (mTimerTask != null ) {
mTimerTask.cancel();
}
if (mTimer != null) {
mTimer.cancel();
}
mTimer = new Timer();
mX = 0;
// Clear current X-axis
mCurrentSeries.clear();
mRenderer.clearXTextLabels();
mTimerTask = new MyTimerTask();
// Delay 100(0.1s), interval is 3000 (3s)
mTimer.schedule(mTimerTask, 100, 3000);
break;
case R.id.button_plot_stop:
// "Stop" button clicked
// Cancel current timer and timer task
if (mTimerTask != null) {
mTimerTask.cancel();
}
if (mTimer != null) {
mTimer.cancel();
}
break;
}
}

Categories