setOnTouchListener issue - java

I have added a timer to my game but by doing so i keep getting the error "The method setOnTouchListener(View.OnTouchListener) in the type View is not applicable for the arguments (scene5.MyCountDownTimer)" I can not seem to fix it. This might just be me making a simple mistake but any solutions would be great. The error is about halfway down my code, I have tagged it with //THIS IS MY PROBLEM AREA!! Cheers guys
public class scene5 extends Activity implements OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView text;
private final long startTime = 20 * 1000;
private final long interval = 1 * 1000;
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("FindIt")
.setMessage("Exit to main menu?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level5);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime/1000));
}
#Override
public void onClick(View v) {
startB.setVisibility(View.INVISIBLE);
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Intent intent = new Intent(scene5.this, timeUp.class);
scene5.this.startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished/1000);
}
{
ImageView iv = (ImageView) findViewById (R.id.image);
if (iv != null) {
iv.setOnTouchListener (this); //THIS IS MY PROBLEM AREA!!
}
toast ("20 seconds to find IT!");}
}
public boolean onTouch (View v, MotionEvent ev)
{
boolean handledHere = false;
final int action = ev.getAction();
final int evX = (int) ev.getX();
final int evY = (int) ev.getY();
int nextImage = -1;
ImageView imageView = (ImageView) v.findViewById (R.id.image);
if (imageView == null) return false;
Integer tagNum = (Integer) imageView.getTag ();
int currentResource = (tagNum == null) ? R.drawable.levels : tagNum.intValue ();
switch (action) {
case MotionEvent.ACTION_DOWN :
if (currentResource == R.drawable.levels) {
nextImage = R.drawable.wrong5;
handledHere = true;
} else handledHere = true;
break;
case MotionEvent.ACTION_UP :
int touchColor = getHotspotColor (R.id.image_areas, evX, evY);
ColorTool ct = new ColorTool ();
int tolerance = 25;
nextImage = R.drawable.levels;
if (ct.closeMatch (Color.RED, touchColor, tolerance)){
Intent intent = new Intent(scene5.this, LevelComplete.class);
scene5.this.startActivity(intent);
}
if (currentResource == nextImage) {
nextImage = R.drawable.levels;
}
handledHere = true;
break;
default:
handledHere = false;
}
if (handledHere) {
if (nextImage > 0) {
imageView.setImageResource (nextImage);
imageView.setTag (nextImage);
}
}
return handledHere;
}
public int getHotspotColor (int hotspotId, int x, int y) {
ImageView img = (ImageView) findViewById (hotspotId);
if (img == null) {
Log.d ("ImageAreasActivity", "Hot spot image not found");
return 0;
} else {
img.setDrawingCacheEnabled(true);
Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
if (hotspots == null) {
Log.d ("ImageAreasActivity", "Hot spot bitmap was not created");
return 0;
} else {
img.setDrawingCacheEnabled(false);
return hotspots.getPixel(x, y);
}
}
}
public void toast (String msg)
{
Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_LONG).show ();
}
}

Your problem is here:
public class scene5 extends Activity implements OnClickListener, OnTouchListener {
...
#Override
public boolean onTouch(View v, MotionEvent event) {
...
}
}
You have to implements also OnTouchListener.

Use
scene5.this
instead of this

the problem is iv.setOnTouchListener (this);
the this context you are passing belongs to the timer task, You need to use iv.setOnTouchListener (scene5.this);
Also, I think you need to find the ImageView reference in the onCreate itself. What you are doing currently ImageView iv = (ImageView) findViewById (R.id.image); won't work.

Related

MediaPlayer - handler.getCurrentPosition()

The issue is with these lines
seekBar1.setProgress(player.getCurrentPosition());
and
seekBar2.setProgress(player2.getCurrentPosition());
Error
Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
also, a small request I have an issue with the handler.postDelayed can you please check this user question too I have the same issue, here is the link to that question
Code // full code is belove this
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}
Full Code // the code can be a little confusing and written badly
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer player, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView totalTime1, totalTime2;
Handler handler1 = new Handler();
Handler handler2 = new Handler();
ImageView play, pause, stop, play2, pause2, stop2;
int pauseCurrentPosition, pauseCurrentPosition2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.dog_howl);
player2 = MediaPlayer.create(this, R.raw.dog_bark);
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
play = findViewById(R.id.playbtn);
pause = findViewById(R.id.pausebtn);
stop = findViewById(R.id.stopbtn);
play2 = findViewById(R.id.playbtn2);
pause2 = findViewById(R.id.pausebtn2);
stop2 = findViewById(R.id.stopbtn2);
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
totalTime1 = findViewById(R.id.totalTime1);
totalTime2 = findViewById(R.id.totalTime2);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
play2.setOnClickListener(this);
pause2.setOnClickListener(this);
stop2.setOnClickListener(this);
seekBar1.setMax(player.getDuration());
seekBar2.setMax(player2.getDuration());
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
player.seekTo(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
player2.seekTo(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
String totTime1 = createTimerLable1(player.getDuration());
totalTime1.setText(totTime1);
String totTime2 = createTimerLable2(player2.getDuration());
totalTime1.setText(totTime2);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.playbtn:
UpdateSeekBar1 updateSeekBar1 = new UpdateSeekBar1();
handler1.post(updateSeekBar1);
if (player == null) {
player = MediaPlayer.create(getApplicationContext(), R.raw.dog_howl);
player.start();
} else if (!player.isPlaying()) {
player.seekTo(pauseCurrentPosition);
player.start();
}
break;
case R.id.pausebtn:
if (player != null) {
player.pause();
pauseCurrentPosition = player.getCurrentPosition();
}
break;
case R.id.stopbtn:
if (player != null) {
player.stop();
player = null;
}
break;
case R.id.playbtn2:
UpdateSeekBar2 updateSeekBar2 = new UpdateSeekBar2();
handler2.post(updateSeekBar2);
if (player2 == null) {
player2 = MediaPlayer.create(getApplicationContext(), R.raw.dog_bark);
player2.start();
} else if (!player2.isPlaying()) {
player2.seekTo(pauseCurrentPosition2);
player2.start();
}
break;
case R.id.pausebtn2:
if (player2 != null) {
player2.pause();
pauseCurrentPosition2 = player2.getCurrentPosition();
}
break;
case R.id.stopbtn2:
if (player2 != null) {
player2.stop();
player2 = null;
}
break;
}
}
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}
}
Enter this code:-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer player, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView totalTime1, totalTime2;
Handler handler1 = new Handler();
Handler handler2 = new Handler();
ImageView play, pause, stop, play2, pause2, stop2;
int pauseCurrentPosition, pauseCurrentPosition2;
UpdateSeekBar1 updateSeekBar1 = new UpdateSeekBar1();
UpdateSeekBar2 updateSeekBar2 = new UpdateSeekBar2();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = MediaPlayer.create(this, R.raw.bekhayali);
player2 = MediaPlayer.create(this, R.raw.hawabanke);
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
play = findViewById(R.id.playbtn);
pause = findViewById(R.id.pausebtn);
stop = findViewById(R.id.stopbtn);
play2 = findViewById(R.id.playbtn2);
pause2 = findViewById(R.id.pausebtn2);
stop2 = findViewById(R.id.stopbtn2);
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
totalTime1 = findViewById(R.id.totalTime1);
totalTime2 = findViewById(R.id.totalTime2);
play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);
play2.setOnClickListener(this);
pause2.setOnClickListener(this);
stop2.setOnClickListener(this);
seekBar1.setMax(player.getDuration());
seekBar2.setMax(player2.getDuration());
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.seekTo(seekBar.getProgress());
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player2.seekTo(seekBar.getProgress());
}
});
String totTime1 = createTimerLable1(player.getDuration());
totalTime1.setText(totTime1);
String totTime2 = createTimerLable2(player2.getDuration());
totalTime1.setText(totTime2);
}
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.playbtn:
handler1.post(updateSeekBar1);
if (player == null) {
player = MediaPlayer.create(getApplicationContext(), R.raw.bekhayali);
player.start();
} else if (!player.isPlaying()) {
player.seekTo(pauseCurrentPosition);
player.start();
}
break;
case R.id.pausebtn:
if (player != null) {
player.pause();
pauseCurrentPosition = player.getCurrentPosition();
}
break;
case R.id.stopbtn:
if (player != null) {
player.stop();
handler1.removeCallbacks(updateSeekBar1);
player = null;
}
break;
case R.id.playbtn2:
handler2.post(updateSeekBar2);
if (player2 == null) {
player2 = MediaPlayer.create(getApplicationContext(), R.raw.hawabanke);
player2.start();
} else if (!player2.isPlaying()) {
player2.seekTo(pauseCurrentPosition2);
player2.start();
}
break;
case R.id.pausebtn2:
if (player2 != null) {
player2.pause();
pauseCurrentPosition2 = player2.getCurrentPosition();
}
break;
case R.id.stopbtn2:
if (player2 != null) {
player2.stop();
handler2.removeCallbacks(updateSeekBar2);
player2 = null;
}
break;
}
}
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public class UpdateSeekBar1 implements Runnable {
#Override
public void run() {
currentTime1.setText(createTimerLable1(seekBar1.getProgress()));
seekBar1.setProgress(player.getCurrentPosition());
handler1.postDelayed(this, 100);
}
}
public class UpdateSeekBar2 implements Runnable {
#Override
public void run() {
currentTime2.setText(createTimerLable2(seekBar2.getProgress()));
seekBar2.setProgress(player2.getCurrentPosition());
handler2.postDelayed(this, 100);
}
}}

facing nulls for no reason in android studio [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am facing 2 nulls in my app when I try to use some buttons in it . I have checking and reviewing my codes for 3 days till now but I can not solve the null
logCat shows me that the
null is at ".Question.getCorrectAnswer() /
QuestionFragment.showCorrectAnswer(QuestionFragment.java:175) and
QuestionActivity.onActivityResult(QuestionActivity.java:419)"
and other button shows null at
"AnswerSheetHelperAdapter.notifyDataSetChanged() / at
QuestionActivity.onActivityResult(QuestionActivity.java:436)"
But I'm sure that there are no nulls at all: I need help from expert people maybe they find something I cannot find cause I am a rookie for now.
This is my Question script:
public class ResultGridAdapter extends RecyclerView.Adapter<ResultGridAdapter.MyViewHolder> {
Context context;
List<CurrentQuestion> currentQuestionList;
public ResultGridAdapter(Context context, List<CurrentQuestion> currentQuestionList) {
this.context = context;
this.currentQuestionList = currentQuestionList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(context).inflate(R.layout.layout_result_item, viewGroup, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
Drawable img;
myViewHolder.btn_question.setText(new StringBuilder("Question").append(currentQuestionList.get(i)
.getQuestionIndex() + 1));
if (currentQuestionList.get(i).getType() == Common.ANSWER_TYPE.RIGHT_ANSWER) {
myViewHolder.btn_question.setBackgroundColor(Color.parseColor("#ff99cc00"));
img = context.getResources().getDrawable(R.drawable.ic_check_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
} else if (currentQuestionList.get(i).getType() == Common.ANSWER_TYPE.WRONG_ANSWER) {
myViewHolder.btn_question.setBackgroundColor(Color.parseColor("#ffcc0000"));
img = context.getResources().getDrawable(R.drawable.ic_clear_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
} else {
img = context.getResources().getDrawable(R.drawable.ic_error_outline_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
}
}
#Override
public int getItemCount() {
return currentQuestionList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
Button btn_question;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
btn_question = (Button) itemView.findViewById(R.id.btn_question);
btn_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LocalBroadcastManager.getInstance(context)
.sendBroadcast(new Intent(Common.KEY_BACK_FROM_RESULT).putExtra(Common.KEY_BACK_FROM_RESULT
, currentQuestionList.get(getAdapterPosition()).getQuestionIndex()));
}
});
}
}
}
This is my QuestionFragment:
public class QuestionFragment extends Fragment implements IQuestion {
TextView txt_question_text;
CheckBox ckbA, ckbB, ckbC, ckbD;
FrameLayout layout_image;
ProgressBar progressBar;
Question question;
int questionIndex = -1;
public QuestionFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View itemView = inflater.inflate(R.layout.fragment_question, container, false);
questionIndex = getArguments().getInt("index", -1);
question = Common.questionList.get(questionIndex);
if (question != null) {
layout_image = (FrameLayout) itemView.findViewById(R.id.layout_image);
progressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
if (question.isImageQuestion()) {
ImageView img_question = (ImageView) itemView.findViewById(R.id.img_question);
Picasso.get().load(question.getQuestionImage()).into(img_question, new Callback() {
#Override
public void onSuccess() {
progressBar.setVisibility(View.GONE);
}
#Override
public void onError(Exception e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else
layout_image.setVisibility(View.GONE);
txt_question_text = (TextView) itemView.findViewById(R.id.txt_question_text);
txt_question_text.setText(question.getQuestionText());
ckbA = (CheckBox) itemView.findViewById(R.id.ckbA);
ckbA.setText(question.getAnswerA());
ckbA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbA.getText().toString());
else
Common.selected_values.remove(ckbA.getText().toString());
}
});
ckbB = (CheckBox) itemView.findViewById(R.id.ckbB);
ckbB.setText(question.getAnswerB());
ckbB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbB.getText().toString());
else
Common.selected_values.remove(ckbB.getText().toString());
}
});
ckbC = (CheckBox) itemView.findViewById(R.id.ckbC);
ckbC.setText(question.getAnswerC());
ckbC.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbC.getText().toString());
else
Common.selected_values.remove(ckbC.getText().toString());
}
});
ckbD = (CheckBox) itemView.findViewById(R.id.ckbD);
ckbD.setText(question.getAnswerD());
ckbD.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbD.getText().toString());
else
Common.selected_values.remove(ckbD.getText().toString());
}
});
}
return itemView;
}
#Override
public CurrentQuestion getSelectedAnswer() {
CurrentQuestion currentQuestion = new CurrentQuestion(questionIndex, Common.ANSWER_TYPE.NO_ANSWER);
StringBuilder result = new StringBuilder();
if (Common.selected_values.size() > 1) {
//for multi choices this will make it multi arrays for answer if it has multi value
Object[] arrayAnswer = Common.selected_values.toArray();
for (int i = 0; i < arrayAnswer.length; i++)
if (i < arrayAnswer.length - 1)
result.append(new StringBuilder(((String) arrayAnswer[i]).substring(0, 1)).append(","));
else
result.append(new StringBuilder((String) arrayAnswer[i]).substring(0, 1));
} else if (Common.selected_values.size() == 1) {
Object[] arrayAnswer = Common.selected_values.toArray();
result.append((String) arrayAnswer[0]).substring(0, 1);
}
if (question != null) {
if (!TextUtils.isEmpty(result)) {
if (result.toString().equals(question.getCorrectAnswer()))
currentQuestion.setType(Common.ANSWER_TYPE.RIGHT_ANSWER);
else
currentQuestion.setType(Common.ANSWER_TYPE.WRONG_ANSWER);
} else
currentQuestion.setType(Common.ANSWER_TYPE.NO_ANSWER);
} else {
Toast.makeText(getContext(), "Cannot get Question", Toast.LENGTH_SHORT).show();
currentQuestion.setType(Common.ANSWER_TYPE.NO_ANSWER);
}
Common.selected_values.clear();
return currentQuestion;
}
#Override
public void showCorrectAnswer() {
String[] correctAnswer = question.getCorrectAnswer().split(",");
for (String answer : correctAnswer) {
if (answer.equals("A")) {
ckbA.setTypeface(null, Typeface.BOLD);
ckbA.setTextColor(Color.RED);
} else if (answer.equals("B")) {
ckbB.setTypeface(null, Typeface.BOLD);
ckbB.setTextColor(Color.RED);
} else if (answer.equals("C")) {
ckbC.setTypeface(null, Typeface.BOLD);
ckbC.setTextColor(Color.RED);
} else if (answer.equals("D")) {
ckbD.setTypeface(null, Typeface.BOLD);
ckbD.setTextColor(Color.RED);
}
}
}
#Override
public void disapleAnswer() {
ckbA.setEnabled(false);
ckbB.setEnabled(false);
ckbC.setEnabled(false);
ckbD.setEnabled(false);
}
#Override
public void resetQuestion() {
ckbA.setEnabled(true);
ckbB.setEnabled(true);
ckbC.setEnabled(true);
ckbD.setEnabled(true);
ckbA.setChecked(false);
ckbB.setChecked(false);
ckbC.setChecked(false);
ckbD.setChecked(false);
ckbA.setTypeface(null, Typeface.NORMAL);
ckbA.setTextColor(Color.BLACK);
ckbB.setTypeface(null, Typeface.NORMAL);
ckbB.setTextColor(Color.BLACK);
ckbC.setTypeface(null, Typeface.NORMAL);
ckbC.setTextColor(Color.BLACK);
ckbD.setTypeface(null, Typeface.NORMAL);
ckbD.setTextColor(Color.BLACK);
}
}
This is my QuestionActivity:
public class QuestionActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private static final int CODE_GET_RESULT = 9999;
ActionBarDrawerToggle toggle;
int time_play = Common.TOTAL_TIME;
private static final String time_Format = "%02d:%02d:%02d";
boolean isAnswerModeView = false;
TextView txt_right_answer, txt_timer, txt_wrong_answer;
RecyclerView answer_sheet_view;
AnswerSheetAdapter answerSheetAdapter;
AnswerSheetHelperAdapter answerSheetHelperAdapter;
ViewPager viewPager;
TabLayout tabLayout;
#Override
protected void onDestroy() {
if (Common.countDownTimer != null)
Common.countDownTimer.cancel();
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(Common.selectedCategory.getName());
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//we need to import question from db
takeQuestion();
if (Common.questionList.size() > 0) {
//to show timer and answer
txt_right_answer = (TextView) findViewById(R.id.txt_question_right);
txt_timer = (TextView) findViewById(R.id.txt_timer);
txt_timer.setVisibility(View.VISIBLE);
txt_right_answer.setVisibility(View.VISIBLE);
txt_right_answer.setText(new StringBuilder(String.format("%d/%d", Common.right_answer_count, Common.questionList.size())));
countTimer();
//view
answer_sheet_view = (RecyclerView) findViewById(R.id.grid_answer);
answer_sheet_view.setHasFixedSize(true);
if (Common.questionList.size() > 5)
answer_sheet_view.setLayoutManager(new GridLayoutManager(this, Common.questionList.size() / 2));
answerSheetAdapter = new AnswerSheetAdapter(this, Common.answerSheetList);
answer_sheet_view.setAdapter(answerSheetAdapter);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
genFragmentList();
QuestionFragmentAdapter questionFragmentAdapter = new QuestionFragmentAdapter(getSupportFragmentManager(),
this,
Common.fragmentsList);
viewPager.setAdapter(questionFragmentAdapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int SCROLLING_RIGHT = 0;
int SCROLLING_LEFT = 1;
int SCROLLING_UNDETERMINED = 2;
int currentScrollDirection = 2;
private void setScrollingDirection(float positionOffset) {
if ((1 - positionOffset) >= 0.5)
this.currentScrollDirection = SCROLLING_RIGHT;
else if ((1 - positionOffset) <= 0.5)
this.currentScrollDirection = SCROLLING_LEFT;
}
private boolean isScrolledDirectionUndetermined() {
return currentScrollDirection == SCROLLING_UNDETERMINED;
}
private boolean isScrollingRight() {
return currentScrollDirection == SCROLLING_RIGHT;
}
private boolean isScrollingLeft() {
return currentScrollDirection == SCROLLING_LEFT;
}
#Override
public void onPageScrolled(int i, float v, int i1) {
if (isScrolledDirectionUndetermined())
setScrollingDirection(v);
}
#Override
public void onPageSelected(int i) {
QuestionFragment questionFragment;
int position = 0;
if (i > 0) {
if (isScrollingRight()) {
questionFragment = Common.fragmentsList.get(i - 1);
position = i - 1;
} else if (isScrollingLeft()) {
questionFragment = Common.fragmentsList.get(i + 1);
position = i + 1;
} else {
questionFragment = Common.fragmentsList.get(position);
}
} else {
questionFragment = Common.fragmentsList.get(0);
position = 0;
}
CurrentQuestion question_state = questionFragment.getSelectedAnswer();
Common.answerSheetList.set(position, question_state);
answerSheetAdapter.notifyDataSetChanged();
countCorrectAnswer();
txt_right_answer.setText(new StringBuilder(String.format("%d", Common.right_answer_count))
.append("/")
.append(String.format("%d", Common.questionList.size())).toString());
txt_wrong_answer.setText(String.valueOf(Common.wrong_answer_count));
if (question_state.getType() != Common.ANSWER_TYPE.NO_ANSWER) {
questionFragment.showCorrectAnswer();
questionFragment.disapleAnswer();
}
}
#Override
public void onPageScrollStateChanged(int i) {
if (i == ViewPager.SCROLL_STATE_IDLE)
this.currentScrollDirection = SCROLLING_UNDETERMINED;
}
});
}
}
private void finishGame() {
int position = viewPager.getCurrentItem();
QuestionFragment questionFragment = Common.fragmentsList.get(position);
CurrentQuestion question_state = questionFragment.getSelectedAnswer();
Common.answerSheetList.set(position, question_state);
answerSheetAdapter.notifyDataSetChanged();
countCorrectAnswer();
txt_right_answer.setText(new StringBuilder(String.format("%d", Common.right_answer_count))
.append("/")
.append(String.format("%d", Common.questionList.size())).toString());
txt_wrong_answer.setText(String.valueOf(Common.wrong_answer_count));
if (question_state.getType() != Common.ANSWER_TYPE.NO_ANSWER) {
questionFragment.showCorrectAnswer();
questionFragment.disapleAnswer();
}
Intent intent = new Intent(QuestionActivity.this, ResultActivity.class);
Common.timer = Common.TOTAL_TIME - time_play;
Common.no_answer_count = Common.questionList.size() - (Common.wrong_answer_count + Common.right_answer_count);
Common.data_question = new StringBuilder(new Gson().toJson(Common.answerSheetList));
startActivityForResult(intent, CODE_GET_RESULT);
}
private void countCorrectAnswer() {
Common.right_answer_count = Common.wrong_answer_count = 0;
for (CurrentQuestion item : Common.answerSheetList)
if (item.getType() == Common.ANSWER_TYPE.RIGHT_ANSWER)
Common.right_answer_count++;
else if (item.getType() == Common.ANSWER_TYPE.WRONG_ANSWER)
Common.wrong_answer_count++;
}
private void genFragmentList() {
for (int i = 0; i < Common.questionList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putInt("index", i);
QuestionFragment fragment = new QuestionFragment();
fragment.setArguments(bundle);
Common.fragmentsList.add(fragment);
}
}
private void countTimer() {
if (Common.countDownTimer == null) {
Common.countDownTimer = new CountDownTimer(Common.TOTAL_TIME, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txt_timer.setText(String.format(time_Format,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
#Override
public void onFinish() {
//finish the game :]
finishGame();
}
}.start();
} else {
Common.countDownTimer.cancel();
Common.countDownTimer = new CountDownTimer(Common.TOTAL_TIME, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txt_timer.setText(String.format(time_Format,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
#Override
public void onFinish() {
//finish the game :]
}
}.start();
}
}
private void takeQuestion() {
Common.questionList = DBHelper.getInstance(this).getQuestionByCategory(Common.selectedCategory.getId());
if (Common.questionList.size() == 0) {
//this one in case category is empty
new MaterialStyledDialog.Builder(this)
.setTitle("Coming Soon !")
.setIcon(R.drawable.ic_sentiment_very_dissatisfied_black_24dp)
.setDescription("The content is coming soon waite for " + Common.selectedCategory.getName() + " category ")
.setPositiveText("ok")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
finish();
}
}).show();
} else {
if (Common.answerSheetList.size() > 0)
Common.answerSheetList.clear();
//gen answers from answersheet each question will has online 1 answer sheet content
for (int i = 0; i < Common.questionList.size(); i++) {
Common.answerSheetList.add(new CurrentQuestion(i, Common.ANSWER_TYPE.NO_ANSWER)); //no answer is default
}
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.menu_wrong_answer);
ConstraintLayout constraintLayout = (ConstraintLayout) item.getActionView();
txt_wrong_answer = (TextView) constraintLayout.findViewById(R.id.txt_wrong_answer);
txt_wrong_answer.setText(String.valueOf(0));
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.question, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_finish_game) {
if (!isAnswerModeView) {
new MaterialStyledDialog.Builder(this)
.setTitle("Finish ?")
.setIcon(R.drawable.ic_mood_black_24dp)
.setDescription("Do you really want to finish?")
.setNegativeText("NO")
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
}
})
.setPositiveText("YES")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dialog.dismiss();
finishGame();
}
}).show();
} else
finishGame();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_GET_RESULT) {
if (resultCode == Activity.RESULT_OK) {
String action = data.getStringExtra("action");
if (action == null || TextUtils.isEmpty(action)) {
int questionNum = data.getIntExtra(Common.KEY_BACK_FROM_RESULT, -1);
viewPager.setCurrentItem(questionNum);
isAnswerModeView = true;
Common.countDownTimer.cancel();
txt_wrong_answer.setVisibility(View.GONE);
txt_right_answer.setVisibility(View.GONE);
txt_timer.setVisibility(View.GONE);
} else {
if (action.equals("viewquizanswer")) {
viewPager.setCurrentItem(0);
isAnswerModeView = true;
Common.countDownTimer.cancel();
txt_wrong_answer.setVisibility(View.GONE);
txt_right_answer.setVisibility(View.GONE);
txt_timer.setVisibility(View.GONE);
for (int i = 0; i < Common.fragmentsList.size(); i++) {
Common.fragmentsList.get(i).showCorrectAnswer();
Common.fragmentsList.get(i).disapleAnswer();
}
} else if (action.equals("doitagain")) {
viewPager.setCurrentItem(0);
isAnswerModeView = false;
countTimer();
txt_wrong_answer.setVisibility(View.VISIBLE);
txt_right_answer.setVisibility(View.VISIBLE);
txt_timer.setVisibility(View.VISIBLE);
for (CurrentQuestion item : Common.answerSheetList)
item.setType(Common.ANSWER_TYPE.NO_ANSWER);
answerSheetAdapter.notifyDataSetChanged();
answerSheetHelperAdapter.notifyDataSetChanged();
for (int i = 0; i < Common.fragmentsList.size(); i++)
Common.fragmentsList.get(i).resetQuestion();
}
}
}
}
}
}
You're never initializing answerSheetHelperAdapter, so it's null. That's one of your problems.
It's impossible to tell why the other one is null without an actual stack trace and more code, but you're probably setting it to null in
question = Common.questionList.get(questionIndex);
See What is a NullPointerException, and how do I fix it? for more information on how to debug this.

Android MediaPlayer seekBar not working correctly

Currently, I'm developing a media player and I need seekBar to work together, at the moment, it's everything okay! but, when I touch at determinated position of the seekbar, the mediaplayer must follow and set the song to this determinated position, but the song and seekBar back to the start and I don't know why it's happening.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
public TextView song_detail;
public TextView time1;
public TextView time2;
private String player_status = "playing";
private ImageButton player_img;
public static SeekBar seekBar;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
song_detail = findViewById(R.id.song_detail);
song_detail.setVisibility(View.GONE);
time1 = findViewById(R.id.time_1);
time2 = findViewById(R.id.time_2);
seekBar = findViewById(R.id.seekBar);
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
if(mediaPlayer != null){
int CurrentPosition = mediaPlayer.getCurrentPosition();
String m_1;
String s_1;
seekBar.setProgress(CurrentPosition/1000);
final int minutes_1 = (CurrentPosition/1000)/60;
final int seconds_1 = ((CurrentPosition/1000)%60);
if (minutes_1 < 10) {
m_1 = "0" + minutes_1;
} else {
m_1 = "" + minutes_1;
}
if (seconds_1 < 10) {
s_1 = "0" + seconds_1;
} else {
s_1 = "" + seconds_1;
}
time1.setText(m_1 + ":" + s_1);
int Duration = mediaPlayer.getDuration();
String m_2;
String s_2;
final int minutes_2 = (Duration/1000)/60;
final int seconds_2 = ((Duration/1000)%60);
if (minutes_2 < 10) {
m_2 = "0" + minutes_2;
} else {
m_2 = "" + minutes_2;
}
if (seconds_2 < 10) {
s_2 = "0" + seconds_2;
} else {
s_2 = "" + seconds_2;
}
time2.setText(m_2 + ":" + s_2);
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
});
seekBar.setMax(mediaPlayer.getDuration()/1000);
mediaPlayer.start();
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public static void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
}
This is the part of code that I'm using to work with mediaPlayer and seekBar
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
But as I have said, instead of mediaPlayer seek and continue the audio from the position that I've clicked, the audio simply back to the start. What I'm doing wrong?
Thank you.
The max value for progress is 100. The seekTo function takes time in milliseconds. This is why it seeks to the start (almost) of the audio.
So instead of mediaPlayer.seekTo(progress);, you need to do:
long newTime = (progress/100.0) * total_audio_duration_in_millisecond;
mediaPlayer.seekTo(newTime);

Regarding issue on App Lock Service Android

I am working for App Locker. I have made services that will check locked apps and will show LOCK APP SCREEN so that user can enter password code. My code is working fine till this stage when Lock App open.
I need to stop my service because my service is continuously running? It is showing my Login Activity again and again while user has already enter correct credentials. How can I stop this issue?
code:
Service:
public class ProcessService extends Service {
private Set<String> mLockedApps = new HashSet<String>();
private long lastModified = 0;
private BroadcastReceiver mScreenStateReceiver;
private File mLockedAppsFile;
ArrayList<String> packagezList;
SharedPreferences sharedPrefs;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
Object obj;
private String prefix;
private Handler handler;
private DbAccess dbAccess;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(new Intent(this, ProcessService.class));
dbAccess=new DbAccess(this);
if (TIMER == null) {
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 3000, 750);
mScreenStateReceiver = new BroadcastReceiver() {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
if (screenOff) {
//Log.i(TAG, "Cancel Timer");
TIMER.cancel();
} else {
// Log.i(TAG, "Restart Timer");
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, filter);
}
// this.stopSelf();
//startforeground goes here
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, ProcessService.class));
}
private class LockAppsTimerTask extends TimerTask {
#Override
public void run() {
sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
allEntries= null;
allEntries = sharedPrefsapp.getAll();
//prefix = "m";
packagezList= null;
packagezList = new ArrayList<String>();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.e("right key: ", entry.getKey().toString() + "right value: " + entry.getValue().toString());
packagezList.add(entry.getKey());
}
for(Object object: packagezList){
Log.e("Object!", (String) object);
// Log.e("Package",""+packagezList.get(0));
}
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
Log.e("activity on Top", "" + activityOnTop);
Log.e(" My package name", "" + getApplicationContext().getPackageName());
//for (Object data : newArrayList) {
for(Object object: packagezList){
Log.e("My Object!", (String)object);
if(activityOnTop.equals("com.android.settings"))
{ // you have to make this check even better
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
i.putExtra("callFromService",true);
i.putExtra("ApppakageName", "com.android.settings" );
startActivity(i);
}
}
} catch (Exception e) {
Log.e("Foreground App", e.getMessage(), e);
}
}
}
}
LockScreenActivity:
public class SeconActivity extends Activity {
public static final String TAG = "AppLock-Abhishek";
private String oldPasscode = null;
protected EditText codeField1 = null;
protected EditText codeField2 = null;
protected EditText codeField3 = null;
protected EditText codeField4 = null;
protected TextView tvMessage = null;
protected InputFilter[] filters = null;
private String str1,str2,str3,str4;
private ProgressDialog dialog;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
ArrayList<String> packagezList;
private DbAccess dbAccess;
private ActionBar actionBar;
private int type=0;
private String confirmPass=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbAccess=new DbAccess(this);
dialog=new ProgressDialog(this);
setContentView(R.layout.page_passcode);
Cursor c;
c=dbAccess.getType();
if(c.moveToNext())
type=c.getInt(c.getColumnIndex("type"));
Cursor cursor;
cursor=dbAccess.getPasssword();
if (cursor.moveToNext()) {
confirmPass = cursor.getString(cursor.getColumnIndex("password"));
}
tvMessage = (TextView) findViewById(R.id.tv_message);
tvMessage.setText(R.string.reenter_passcode);
//editcodeFields
filters = new InputFilter[2];
filters[0] = new InputFilter.LengthFilter(1);
filters[1] = numberFilter;
codeField1 = (EditText) findViewById(R.id.passcode_1);
setupEditText(codeField1);
codeField2 = (EditText) findViewById(R.id.passcode_2);
setupEditText(codeField2);
codeField3 = (EditText) findViewById(R.id.passcode_3);
setupEditText(codeField3);
codeField4 = (EditText) findViewById(R.id.passcode_4);
setupEditText(codeField4);
// setup the keyboard
((Button) findViewById(R.id.button0)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button1)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button2)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button3)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button4)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button5)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button6)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button7)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button8)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button9)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button_clear))
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clearFields();
}
});
((Button) findViewById(R.id.button_erase))
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onDeleteKey();
}
});
}
private InputFilter numberFilter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source.length() > 1) {
return "";
}
if (source.length() == 0) // erase
{
return null;
}
try {
int number = Integer.parseInt(source.toString());
if ((number >= 0) && (number <= 9))
return String.valueOf(number);
else
return "";
} catch (NumberFormatException e) {
return "";
}
}
};
protected void reEnterePass()
{
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.requestFocus();
// set the value and move the focus
}
protected void onPasscodeError() {
Toast toast = Toast.makeText(this, getString(R.string.passcode_wrong),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 30);
toast.show();
Thread thread = new Thread() {
public void run() {
Animation animation = AnimationUtils.loadAnimation(
SeconActivity.this, R.anim.shake);
findViewById(R.id.ll_applock).startAnimation(animation);
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.requestFocus();
}
};
runOnUiThread(thread);
}
protected void setupEditText(EditText editText) {
editText.setInputType(InputType.TYPE_NULL);
editText.setFilters(filters);
editText.setOnTouchListener(touchListener);
editText.setTransformationMethod(PasswordTransformationMethod
.getInstance());
}
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.performClick();
clearFields();
return false;
}
};
private void clearFields() {
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.postDelayed(new Runnable() {
#Override
public void run() {
codeField1.requestFocus();
}
}, 200);
}
private View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int currentValue = -1;
int id = view.getId();
if (id == R.id.button0) {
currentValue = 0;
} else if (id == R.id.button1) {
currentValue = 1;
} else if (id == R.id.button2) {
currentValue = 2;
} else if (id == R.id.button3) {
currentValue = 3;
} else if (id == R.id.button4) {
currentValue = 4;
} else if (id == R.id.button5) {
currentValue = 5;
} else if (id == R.id.button6) {
currentValue = 6;
} else if (id == R.id.button7) {
currentValue = 7;
} else if (id == R.id.button8) {
currentValue = 8;
} else if (id == R.id.button9) {
currentValue = 9;
} else {
}
// set the value and move the focus
String currentValueString = String.valueOf(currentValue);
if (codeField1.isFocused()) {
codeField1.setText(currentValueString);
str1=currentValueString;
codeField2.requestFocus();
codeField2.setText("");
} else if (codeField2.isFocused()) {
codeField2.setText(currentValueString);
str2=currentValueString;
codeField3.requestFocus();
codeField3.setText("");
} else if (codeField3.isFocused()) {
codeField3.setText(currentValueString);
str3=currentValueString;
codeField4.requestFocus();
codeField4.setText("");
} else if (codeField4.isFocused()) {
codeField4.setText(currentValueString);
str4=currentValueString;
}
if (codeField4.getText().toString().length() > 0
&& codeField3.getText().toString().length() > 0
&& codeField2.getText().toString().length() > 0
&& codeField1.getText().toString().length() > 0) {
Log.e(TAG, str1 + str2 + str3 + str4);
String passCode=(str1+str2+str3+str4).trim();
switch (type){
case 1:
if (passCode.equals(confirmPass)){
startActivity(new Intent(getApplicationContext(),LockScreenActivity.class));
}else
{
onPasscodeError();
}
break;
case 2:
if(passCode.equalsIgnoreCase(confirmPass)){
finish();
}else
{
Intent startHomescreen=new Intent(Intent.ACTION_MAIN);
startHomescreen.addCategory(Intent.CATEGORY_HOME);
startHomescreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(startHomescreen);
}
break;
default:
break;
}
}
}
};
private void onDeleteKey() {
if (codeField1.isFocused()) {
} else if (codeField2.isFocused()) {
codeField1.requestFocus();
codeField1.setText("");
} else if (codeField3.isFocused()) {
codeField2.requestFocus();
codeField2.setText("");
} else if (codeField4.isFocused()) {
codeField3.requestFocus();
codeField3.setText("");
}
}
}//end of class
First of all I would like to tell you that you should not rely on Timer for your code to run repetitively because timer is destroyed by system after sometime , i hope u would have realized this bug. And for your problem you should create a hashmap to know weather the foreground activity is already accessed by user or not by verifying the password.

How to stop a Splash Screen with a click before the end?

I created an activity splashScreen in my application.
This works very well with animation is my code :
public class SpalshScreenActivity extends Activity {
private static final int STOPSPLASH = 0;
private static final long SPLASHTIME = 3000;
private boolean flagBack = false;
private final transient Handler splashHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what == STOPSPLASH && !flagBack) {
StartMainActivity();
}
super.handleMessage(msg);
}
};
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.HideActionBar);
setContentView(R.layout.splash);
StartAnimations();
final Message msg = new Message();
msg.what = STOPSPLASH;
splashHandler.sendMessageDelayed(msg, SPLASHTIME);
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l=(LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.logo);
iv.clearAnimation();
iv.startAnimation(anim);
}
private void StartMainActivity() {
final Intent intent = new Intent(SpalshScreenActivity.this, MainFragmentActivity.class);
startActivity(intent);
finish();
}
public boolean onKeyDown(int keyCode, KeyEvent evt) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
flagBack = true;
finish();
return true;
}
return false;
}}
Now I would like to add the ability to click on the screen to stop the SplashScreen.
I tried this way, it works but I think it is not an optimal solution (slow) :
#Override
public boolean onTouchEvent(MotionEvent evt) {
if(evt.getAction() == MotionEvent.ACTION_DOWN) {
flagBack = true;
StartMainActivity();
}
return true;
}
Thank you in advance!
set an OnClickListener to the activity with the same code as in the onTouchEvent

Categories

Resources