guys. There is a problem about threads in my android app. initializeGame() is the main method :
public void initializeGame()
{
Thread thread = new Thread(new onePoint());
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class, where i'm describing the thread :
class onePoint implements Runnable {
(...)
public void run() {
(...)
setBackgroundColorOnButton(...);
while (...) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
(...)
if (...) {
setOpacityOnButton(...);
}
}
}
Where it is "(...)", there is just a work with variables.
You see, there are two methods : setBackgroundColorOnButton() and setOpacityOnButton().
I'll show them :
void setBackgroundColorOnButton(int id, int num) {
int color = Color.parseColor("#cccaca");
switch (num) {
case 1: color = Color.RED; break;
case 2: color = Color.parseColor("#FF4F38"); break;
case 3: color = Color.YELLOW; break;
case 4: color = Color.GREEN; break;
case 5: color = Color.BLUE; break;
case 6: color = Color.parseColor("#09256C"); break;
case 7: color = Color.parseColor("#690069"); break;
}
final int col = color;
Message message = backgroundColorOnButton.obtainMessage();
message.obj = new int[] {id, col};
backgroundColorOnButton.sendMessage(message);
}
void setOpacityOnButton(int id, final int opacity) {
Message message = opacityOnButton.obtainMessage();
message.obj = new int[] {id, opacity};
opacityOnButton.sendMessage(message);
}
In this methods i'm sending messages to 2 handlers, which are described in onCreate() :
backgroundColorOnButton = new Handler() {
public void handleMessage(Message msg) {
int[] a = (int[]) msg.obj;
Button btn = (Button) findViewById(a[0]);
GradientDrawable drawable = (GradientDrawable) btn.getBackground();
drawable.setColor(a[1]);
}
};
opacityOnButton = new Handler() {
public void handleMessage(Message msg) {
int[] a = (int[]) msg.obj;
Button btn = (Button) findViewById(a[0]);
if (a[1] != 0) {
btn.setText(Integer.toString(a[1]));
}
else {
btn.setText("");
}
}
};
In method onCreate() i also create ui elements.
My problem: in method onCreate() i call initializeGame(), and i need to see ui changing after app starts, but i don't see it for 5 seconds. It is a white screen during 5 seconds and then ui's starting to change. What am i doing wrong?
Related
I am trying to wait after each for loop using Threads in my application but I have a problem. This for loop has to be executed when the film from URL is playing but...
Unfortunately the loop is executed with pauses that I put into the code and later the film starts with text updated. This should start simultaneously. The for loop and the film. During the film the texts should be updated one after another.
NOTE: I shorted the ArrayList dict to make code easier to understand.
NOTE2: The app tries to open video file from URL but it gives me a message:
W/MediaPlayer: Couldn't open (Video URL) : java.io.FileNotFoundException: No content provider: (Video URL).
EDIT: I am putting an entire class code for you.
public class Video extends Activity {
private VideoView videoView;
private TextView englishTrans1;
private TextView polishTrans1;
private TextView englishTrans2;
private TextView polishTrans2;
private TextView englishTrans3;
private TextView polishTrans3;
int j = 0;
int i =0;
public static final String TAG = "My tag";
ArrayList<Translations> dict = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
videoView = findViewById(R.id.video_view1);
MediaController mMedia = new MediaController(this);
mMedia.setMediaPlayer(videoView);
mMedia.setAnchorView(videoView);
videoView.setMediaController(mMedia);
String path1 = (HERE IS VIDEO URL);
Uri uri = Uri.parse(path1);
videoView.setVideoURI(uri);
videoView.start();
englishTrans1 = findViewById(R.id.english_trans1);
polishTrans1 = findViewById(R.id.polish_trans1);
englishTrans2 = findViewById(R.id.english_trans2);
polishTrans2 = findViewById(R.id.polish_trans2);
englishTrans3 = findViewById(R.id.english_trans3);
polishTrans3 = findViewById(R.id.polish_trans3);
dict.add(new Translations("kot","cat"));
dict.add(new Translations("pies","dog"));
dict.add(new Translations("kawa","coffee"));
dict.add(new Translations("herbata","tea"));
dict.add(new Translations("kościół","church"));
dict.add(new Translations("ślub","wedding"));
final Handler h = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
for(Translations x : dict){
try {
synchronized (this) {
Thread.sleep(2000);
}
}catch (InterruptedException e){
}
switch (j) {
case 1: {
Log.d(TAG, "First word translated");
englishTrans1.setText(x.getEnglishWord());
polishTrans1.setText(x.getPolishWord());
break;
}
case 2: {
Log.d(TAG, "Second word translated");
englishTrans2.setText(x.getEnglishWord());
polishTrans2.setText(x.getPolishWord());
break;
}
case 3: {
Log.d(TAG, "Third word translated");
englishTrans3.setText(x.getEnglishWord());
polishTrans3.setText(x.getPolishWord());
break;
}
}
if (j < 3) {
j++;
} else {
j = 1;
}
}
}
};
Runnable r = new Runnable() {
#Override
public void run() {
h.sendEmptyMessage(0);
}
};
Thread t = new Thread(r);
t.start();
}
}
Translations.java class with constructor.
public class Translations {
private String polishWord;
private String englishWord;
public Translations(){
}
public Translations(String mPolishWord,String mEnglishWord){
polishWord = mPolishWord;
englishWord = mEnglishWord;
}
public String getPolishWord() {
return polishWord;
}
public void setPolishWord(String polishWord) {
this.polishWord = polishWord;
}
public String getEnglishWord() {
return englishWord;
}
public void setEnglishWord(String englishWord) {
this.englishWord = englishWord;
}
}
Why loop at all, The "subtitles" as that is what the code snippet is doing, are linked to the video.
What if the person scrubs the film and fast forwards or rewinds, Most subtitle setups have the sentence on screen linked with a timecode for the film, so you then have the subtitle triggered on a change of timecode on the playing video, and pass in the timecode so it will get the sentence for that part of the video and display it on screen.
I have found a solution. The issue was that I was trying to sleep the Thread in Handler. The JVM thought that the main thread should be paused, not the "t" Thread. I moved the Thread.sleep() method to run() and the for loop too. I left only switch() in the Handler to change the UI. It works right now.
final Handler h = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
Translations x = dict.get(i-1);
switch (j) {
case 1: {
Log.d(TAG, "First word translated");
englishTrans1.setText(x.getEnglishWord());
polishTrans1.setText(x.getPolishWord());
break;
}
case 2: {
Log.d(TAG, "Second word translated");
englishTrans2.setText(x.getEnglishWord());
polishTrans2.setText(x.getPolishWord());
break;
}
case 3: {
Log.d(TAG, "Third word translated");
englishTrans3.setText(x.getEnglishWord());
polishTrans3.setText(x.getPolishWord());
break;
}
}
}
};
Runnable r = new Runnable() {
#Override
public void run() {
for(i = 0;i<dict.size();i++) {
try {
Thread.sleep(2000);
}catch (InterruptedException e){
}
if (j < 3) {
j++;
} else {
j = 1;
}
h.sendEmptyMessage(0);
}
}
};
Thread t = new Thread(r);
t.start();
}
}
I am working on project in which app responds to Commands uploaded in Firebase Realtime Database, to listen to changes in Firebase Realtime Database I am using ValueEventListner. A command is uploaded in FRDB must only be executed once and then removed from FRDB (Whenever a command is executed it is removed from FRDB and onDataChanged is called again, if there are more than 1 commands under the 'command' node then it gets executed more than once, to stop that I have Implemented the following code). I have called addValueEventListener in onCreate in a START_STICKY service. The app also uploads other data to FRDB which is working fine but the ValueEventListner is not working properly.
The code works fine for a 3 or 4 days and then stops working. I don't know whats wrong, I am completely lost. Any help would be appreciated.
mCommandsRef.addValueEventListener(new ValueEventListener() {
private long fcount = 0;
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Iterable<DataSnapshot> snapshots = dataSnapshot.getChildren();
if (fcount > dataSnapshot.getChildrenCount()) {
if (dataSnapshot.getChildrenCount() == 0) {
fcount = 0;
}
return;
}
int i = 0;
for (DataSnapshot snapshot : snapshots) {
if (i == 0) {
fcount = dataSnapshot.getChildrenCount();
}
long c = snapshot.getValue(Long.class);
executeCommand(c, snapshot);
i++;
}
} catch (DatabaseException | NullPointerException e) {
e.printStackTrace();
executeCommand(DATABASE_EXCEPTION_CODE, dataSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is the executeCommand method :
public void executeCommand(long c, DataSnapshot dataSnapshot) {
int a = Integer.parseInt(String.valueOf(c));
String command;
switch (a) {
case 0:
Log.i(TAG, COMMAND_SET_STATUS);
setStatus();
command = COMMAND_SET_STATUS;
break;
case 1:
try {
long count = Integer.parseInt(dataSnapshot.getKey());
mRootRef.child(CALL_LOGS_LIST).setValue(getCallLogs(count));
command = COMMAND_GET_CALLS;
break;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
break;
}
case 2:
try {
long count = Integer.parseInt(dataSnapshot.getKey());
Log.i(TAG, COMMAND_GET_MESSAGES);
mRootRef.child(SMS_LIST).setValue(getSmsList(count));
command = COMMAND_GET_MESSAGES;
break;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
break;
}
case 3:
Log.i(TAG, COMMAND_GET_CONTACTS);
mRootRef.child(CONTACTS_LIST).setValue(getContactList());
command = COMMAND_GET_CONTACTS;
break;
case 4:
dbHelper.setRecordOn();
setStatus();
command = COMMAND_SET_RECORD_TRUE;
break;
case 5:
dbHelper.setRecordOff();
setStatus();
command = COMMAND_SET_RECORD_FALSE;
break;
case 6:
try {
int count = Integer.parseInt(dataSnapshot.getKey());
getCameraPictures(count);
command = COMMAND_GET_CAMERA_PICTURES;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
}
break;
case 7:
try {
int count = Integer.parseInt(dataSnapshot.getKey());
getWhatsAppSentPictures(count);
command = COMMAND_GET_WHATSAPP_SENT_PICTURES;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
}
break;
case 8:
try {
int count = Integer.parseInt(dataSnapshot.getKey());
getWhatsAppReceivedPictures(count);
command = COMMAND_GET_WHATSAPP_RECEIVED_PICTURES;
} catch (NumberFormatException e) {
e.printStackTrace();
command = COMMAND_EXCEPTION;
}
break;
case 9:
List<String> recList = getRecsList();
if (recList.size() == 0) {
command = COMMAND_GET_RECS_ZERO;
break;
}
mRootRef.child(RECS_LIST).setValue(recList);
command = COMMAND_GET_RECS;
break;
default:
command = COMMAND_UNKNOWN_COMMAND;
break;
}
final String finalCommand = command;
dataSnapshot.getRef().removeValue(new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
CommandHistory commandHistory = new CommandHistory(finalCommand, new Date().toString());
mRootRef.child(COMMAND_HISTORY).push().setValue(commandHistory)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
}
}
});
}
});
}
I'm making a "Simon says" game as my final project for highschool, and it's mostly done but I have one problem.
Currently, I'm trying to make the buttons light when I press them.
However, they don't seem to light up and the sleep function doesn't really work.
They only change color when the function that displays the next sequence of colors lights up.
Here's the code:
package com.gabie212.simonsays;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class GameActivity extends AppCompatActivity implements View.OnClickListener {
private int i = 0, pNum = 0, pIndex = 0,score;
private Thread t = new Thread();
private Thread bt = new Thread();
private Button greenButton;
private Button redButton;
private Button blueButton;
private Button yellowButton;
private Button startButton;
private TextView Score;
private boolean startActivated = false;
private MediaPlayer greenBeep;
private MediaPlayer redBeep;
private MediaPlayer blueBeep;
private MediaPlayer yellowBeep;
private ArrayList<Integer> userColors = new ArrayList<Integer>();
private GameManger gm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Score = (TextView) findViewById(R.id.ScoreNum);
greenButton = (Button) findViewById(R.id.btnGreen);
redButton = (Button) findViewById(R.id.btnRed);
blueButton = (Button) findViewById(R.id.btnBlue);
yellowButton = (Button) findViewById(R.id.btnYellow);
startButton = (Button) findViewById(R.id.btnStart);
greenButton.setOnClickListener(this);
redButton.setOnClickListener(this);
blueButton.setOnClickListener(this);
yellowButton.setOnClickListener(this);
startButton.setOnClickListener(this);
greenBeep = MediaPlayer.create(this, R.raw.greenbeep);
redBeep = MediaPlayer.create(this, R.raw.redbeep);
blueBeep = MediaPlayer.create(this, R.raw.bluebeep);
yellowBeep = MediaPlayer.create(this, R.raw.yellowbeep);
/*
SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.apply();
*/
}
public void start() {
startActivated=true;
gm = new GameManger(this);
Score.setText("0");
lightUp(0);
}
public void beepStop(){
greenBeep.stop();
redBeep.stop();
blueBeep.stop();
yellowBeep.stop();
}
public void lightUp(final int i) {
android.os.Handler handler = new android.os.Handler();
if (i < gm.getRandomColors().size()) //light up code
{
switch (gm.getRandomColors().get(i)) {
case 1:
greenButton.setBackgroundResource(R.drawable.greenlightup);
greenBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
greenButton.setBackgroundResource(R.drawable.green);
lightUp(i+1);
}
}, 500);
break;
case 2:
redButton.setBackgroundResource(R.drawable.redlightup);
redBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
redButton.setBackgroundResource(R.drawable.red);
lightUp(i+1);
}
}, 500);
break;
case 3:
blueButton.setBackgroundResource(R.drawable.bluelightup);
blueBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
blueButton.setBackgroundResource(R.drawable.blue);
lightUp(i+1);
}
}, 500);
break;
case 4:
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
yellowBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yellowButton.setBackgroundResource(R.drawable.yellow);
lightUp(i+1);
}
}, 500);
break;
}
}
pIndex = 0;
}
#Override
public void onClick(View v) {
if (v.getId() == startButton.getId()) {
start();
} else {
if (startActivated) {
if (v.getId() == greenButton.getId()) {//here is the part where i try to make the buttons change colors
greenBeep.start();
greenButton.setBackgroundResource(R.drawable.greenlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
greenButton.setBackgroundResource(R.drawable.green);
pNum = 1;
}
if (v.getId() == redButton.getId()) { //here is the part where i try to make the buttons change colors
redBeep.start();
redButton.setBackgroundResource(R.drawable.redlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
redButton.setBackgroundResource(R.drawable.red);
pNum = 2;
}
if (v.getId() == blueButton.getId()) { //here is the part where i try to make the buttons change colors
blueBeep.start();
blueButton.setBackgroundResource(R.drawable.bluelightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
blueButton.setBackgroundResource(R.drawable.blue);
pNum = 3;
}
if (v.getId() == yellowButton.getId()) {//here is the part where i try to make the buttons change colors
yellowBeep.start();
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
yellowButton.setBackgroundResource(R.drawable.yellow);
pNum = 4;
}
if (!gm.check(pNum, pIndex)) {
beepStop();
SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
Intent i = null;
score = gm.getRandomColors().size()-1;
if(score > sp.getInt("scoreP3",0)) {
i = new Intent(GameActivity.this, InsertScoreActivity.class);
i.putExtra("score", gm.getRandomColors().size() - 1);
startActivity(i);
}
else {
i = new Intent(GameActivity.this, GameOverActivity.class);
i.putExtra("score", gm.getRandomColors().size() - 1);
startActivity(i);
}
}
pIndex++;
if (pIndex == gm.getRandomColors().size()) {
Score.setText("" + gm.getRandomColors().size() + "");
gm.addColor();
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
lightUp(0);//it either performs the color change here beofre the lightup function or it just sleeps and doesn't perform the color change at all
}
}
}
}
}
here's the game helper class:
package com.gabie212.simonsays;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by Ronit on 21/02/2018.
*/
public class GameManger {
private GameActivity gActivity;
static Random rnd = new Random();
private ArrayList<Integer> randomColors;
public GameManger(GameActivity mA)
{
randomColors = new ArrayList<Integer>();
this.gActivity =mA;
randomColors.add(getColor());
}
public void addColor()
{
randomColors.add(getColor());
}
public int getColor()
{
return rnd.nextInt(4)+1;
}
public ArrayList<Integer> getRandomColors()
{
return randomColors;
}
public boolean check(int num, int index)
{
return(randomColors.get(index)==num);
}
}
enter code here
I have some problems.
The sleep doesn't perform, does it have something to do with the way I did it in the if statements? Sleep just doesn't happen in the code I have written.
Color change doesn't happen for some reason and I don't know why it doesn't, maybe it has something to do with the thread.sleep.
Color change happens later in the program than its supposed to. Again, I think it has something to do with the sleep but when I removed the sleep, the color change still happens later in the code.
When I press the first time the buttons go and come back with other
letters, but when I press again nothing happens:
int d = -1; String btnanim = "0";
How to make it animated when I press the buttons again?
public void b_b1(View v) {
if (this.btnanim == "AB") {
btn("CD");
return;
}
do {
if (this.btnanim == "CD") {
btn("EF");
return;
}
if (this.btnanim == "EF") {
btn("GH");
return;
}
} while (this.btnanim != "1");
btn("AB");
}
Without animation, the text changes
void btn(String str) {
this.btnanim = str;
this.timer.schedule(new TimerTask() {
ObjectAnimator anim;
LinearLayout bgroup = (LinearLayout) MainActivity.this.findViewById(R.id.bg);
Button b1 = (Button) MainActivity.this.findViewById(R.id.b1);
Button b2 = (Button) MainActivity.this.findViewById(R.id.b2);
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
MainActivity.this.d += 1;
switch (MainActivity.this.d) {
case 0:
anim = ObjectAnimator.ofFloat(bgroup, "translationX", bgroup.getWidth() * 2);
anim.setDuration(500L).start();
break;
case 5:
anim = ObjectAnimator.ofFloat(bgroup, "translationX", -bgroup.getWidth() * 2);
anim.setDuration(0L).start();
anim = ObjectAnimator.ofFloat(bgroup, "translationX", 0);
anim.setDuration(500L).start();
switch (MainActivity.this.btnanim) {
case "AB":
b1.setText("A");
b2.setText("B");
break;
case "CD":
b1.setText("C");
b2.setText("D");
break;
case "EF":
//Do not repeat the animation this: Changes A and B to C and D then nothing
b1.setText("E");
b2.setText("F");
break;
}
}
}
});
}
}, 0L, 100L);
}
protected void onResume() {
super.onResume();
MainActivity.this.btnanim = "AB";
}
}
I added this.d = -1; in void btn(String str) {}
Now it works right!
For example if i display in a TextView the text "Uploading" now i want it to display the text as "Uploading..." and the 3 points to be delete and show again like it's processing doing something and not just static text.
I have this in the MainActivity onTouch event:
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (connectedtoipsuccess == true)
{
if (is_start == true)
{
uploadTimerBool = true;
timers.StartTimer(timerValueRecord, "Recording Time: ");
response = Get(iptouse + "start");
is_start = false;
} else
{
timers.StopTimer(timerValueRecord);
textforthespeacch = "Recording stopped and preparing the file to be shared on youtube";
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
status1.setText("Preparing the file");
}
});
MainActivity.this.initTTS();
response = Get(iptouse + "stop");
is_start = true;
startuploadstatusthread = true;
servercheckCounter = 0;
}
if (response != null)
{
try
{
a = new String(response, "UTF-8");
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (a.equals("Recording started"))
{
status1.setText("Recording");
}
if (a.equals("Recording stopped and preparing the file to be shared on youtube"))
{
status1.setText("Recording Stopped");
}
}
});
textforthespeacch = a;
MainActivity.this.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
return true;
}
This line:
status1.setText("Preparing the file");
Instead displaying only static text "Preparing the file" i was wondering how to make that it will display something like moving points like "Preparing the file..." then "Preparing the file.." and "Preparing the file." and again "Preparing the file..." then "Preparing the file.." and so on.
Use this awesome library, exactly what you are looking for:
https://github.com/tajchert/WaitingDots
Add this to dependencies
compile 'pl.tajchert:waitingdots:0.2.0'
and you can use the methos. The description is in the link
Handler handler = new Handler();
for (int i = 100; i <= 3500; i=i+100) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(i%300 == 0){
textView.setText("Uploading.");
}else if(i%200 == 0){
textView.setText("Uploading..");
}else if(i%100 == 0){
textView.setText("Uploading...");
}
}
}, i);
}