I am developing an android application that opens a PDF file and extract its content using itext then convert the results to an audio file using TTS engine and finally open the audio file using Media Player.
The app works fine for me and I am able to view PDF files but I can't view the Media player. I need a way to view media player upon the PDF file like this pdf_activity.xml
here is my code for PDF Activity:
public class PDF_Activity extends AppCompatActivity {
private Button b1,b2,b3,b4;
private MediaPlayer mediaPlayer;
private double startTime = 0;
private double finalTime = 0;
private Handler myHandler = new Handler();;
private int forwardTime = 5000;
private int backwardTime = 5000;
private SeekBar seekbar;
private TextView tx1,tx2,tx3;
public static int oneTimeOnly = 0;
private TextToSpeech mTts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
//PDFVIEW SHALL DISPLAY OUR PDFS
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
//UNPACK OUR DATA FROM INTENT
Intent i = this.getIntent();
String path = i.getExtras().getString("PATH");
//GET THE PDF FILE
File file = new File(path);
if (file.canRead()) {
//LOAD IT
pdfView.fromFile(file).defaultPage(1).onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
Toast.makeText(PDF_Activity.this, String.valueOf(nbPages), Toast.LENGTH_LONG).show();
}
}).load();
try {
String parsedText = "";
PdfReader reader = new PdfReader(path);
int n = reader.getNumberOfPages();
for (int page = 0; page < n; page++) {
parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, page + 1).trim() + "\n"; //Extracting the content from the different pages
}
reader.close();
HashMap<String, String> myHashRender = new HashMap();
String destFileName = path.concat(".wav");
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, parsedText);
mTts.synthesizeToFile(parsedText, myHashRender, destFileName);
} catch (Exception e) {
e.printStackTrace();
}
}
String pdfMediaPalyer = path.concat(".wav");
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
tx1 = (TextView) findViewById(R.id.textView2);
tx2 = (TextView) findViewById(R.id.textView3);
tx3 = (TextView) findViewById(R.id.textView4);
tx3.setText(file.getName());
try {
mediaPlayer.setDataSource(pdfMediaPalyer);
} catch (IOException e) {
e.printStackTrace();
}
seekbar = (SeekBar) findViewById(R.id.seekBar);
seekbar.setClickable(false);
b2.setEnabled(false);
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Playing sound", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
if (oneTimeOnly == 0) {
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
tx2.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
finalTime)))
);
tx1.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
startTime)))
);
seekbar.setProgress((int) startTime);
myHandler.postDelayed(UpdateSongTime, 100);
b2.setEnabled(true);
b3.setEnabled(false);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Pausing sound", Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
b2.setEnabled(false);
b3.setEnabled(true);
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int temp = (int) startTime;
if ((temp + forwardTime) <= finalTime) {
startTime = startTime + forwardTime;
mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(), "You have Jumped forward 5 seconds", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show();
}
}
});
b4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int temp = (int) startTime;
if ((temp - backwardTime) > 0) {
startTime = startTime - backwardTime;
mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(), "You have Jumped backward 5 seconds", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show();
}
}
});
}
private Runnable UpdateSongTime = new Runnable() {
public void run() {
startTime = mediaPlayer.getCurrentPosition();
tx1.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) startTime)))
);
seekbar.setProgress((int)startTime);
myHandler.postDelayed(this, 100);
}
};
}
Related
I have a project in which it plays IPTV. I would like to identify if there is video signal in order to show an alertdialog if there isn't signal. I could set a timer to wait for the signal to return, but I don't know how to identify if there is a signal or not. Could you please help me. I leave the code with which I am working. SdkVersion 22.
public class Television extends Activity {
VideoView videoView;
ImageView volmas, volmenos, voloff;
SeekBar seekbar;
TextView textview, tvvolumen;
AudioManager audioManager;
int i = 50;
int volumen = 7;
int volumenporcentaje;
Toast toast;
Exception e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_television);
try {
String canal = getIntent().getStringExtra("Canal");
volmas = (ImageView) findViewById(R.id.volmas);
volmenos = (ImageView) findViewById(R.id.volmenos);
voloff = (ImageView) findViewById(R.id.voloff);
tvvolumen = (TextView) findViewById(R.id.tvvolumen);
volumenporcentaje = (volumen * 100) / 15;
tvvolumen.setText("" + volumenporcentaje + "%");
e = null;
videoView = (VideoView) this.findViewById(R.id.videoViewTV);
videoView.setVideoURI(Uri.parse(canal));
videoView.requestFocus();
videoView.start();
voloff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
volumen = 0;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumen, 0);
volumenporcentaje = (volumen * 100) / 15;
tvvolumen.setText("" + volumenporcentaje + "%");
}
});
volmas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (volumen < 15) {
volumen = volumen + 1;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumen, 0);
volumenporcentaje = (volumen * 100) / 15;
tvvolumen.setText("" + volumenporcentaje + "%");
}
if (volumen >= 15) {
Toast.makeText(Television.this, "Volumen al máximo", Toast.LENGTH_SHORT).show();
}
}
});
volmenos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (volumen > 0) {
volumen = volumen - 1;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumen, 0);
volumenporcentaje = (volumen * 100) / 15;
tvvolumen.setText("" + volumenporcentaje + "%");
}
if (volumen == 0) {
Toast.makeText(Television.this, "Volumen al mínimo", Toast.LENGTH_SHORT).show();
}
}
});
seekbar = (SeekBar) findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumen, 0);
} catch (Exception e) {
Errores.exception(e, this.getApplicationContext());
}
}
I recommend you to change your approach! Use Exomedia or Exoplayer library. They are very simple.
Depend on your choice, you can use their function to solve your problem :)
I have tried to make an countdown timer in a list veiw implementation. Each list item has a separate countdown timer that can be started or stopped. However I have noticed that if I add the first timer in list and set its time. When I start the timer it starts two seconds less than the actual time. e.g If I added a count down of 12 seconds. Then it will start counting from 10. But when the countdown is taking place and I add another new timer and set its time, it starts on the exact given time. The new counter starts at the wrong time only when either there is no other counter in the list or when all counters are already stopped and not counting down. Similarly it will only start the right time only when other timers are counting down. Would really appreciate if someone can help me figure out where is the problem. I have been looking at the code for days.
Here's my Adapter class
public class CustomAdapterCounter extends ArrayAdapter<CounterData> {
private final LayoutInflater mInflater;
Context context;
Uri sound = Uri.parse("android.resource://com.tattooalarmclock.free/" + R.raw.counter);
String counterString = "";
private List<ViewHolder> lstHolders;
private List<CounterData> list = new ArrayList<CounterData>();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
// if(!holder.counterData.isStopped)
holder.updateTimeRemaining(System.currentTimeMillis());
}
}
}
};
public CustomAdapterCounter(Context context, List<CounterData> l) {
super(context, 0, l);
this.context = context;
lstHolders = new ArrayList<>();
list = l;
mInflater = LayoutInflater.from(context);
for(int i=0; i<list.size(); i++) {
CounterData[] array = list.toArray(new CounterData[list.size()]);
if(!array[i].isStopped)
startUpdateTimer();
}
}
public double getScreenSize() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int dens = dm.densityDpi;
double wi = (double) width / (double) dens;
double hi = (double) height / (double) dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
public boolean getListSharedPreferences() {
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getString("CL", null) != null) {
counterString = sharedPreferences.getString("CL", null);
Gson gson = new Gson();
TypeToken<List<CounterData>> token = new TypeToken<List<CounterData>>() {};
list = gson.fromJson(counterString, token.getType());
return true;
}
else
return false;
}
public void saveListSharedPreferences(List counterList) {
Gson gson = new Gson();
counterString = gson.toJson(counterList);
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CL", counterString).commit();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
if(getScreenSize() <= 4 )
convertView = mInflater.inflate(R.layout.list_view_counter_small, parent, false);
else
convertView = mInflater.inflate(R.layout.list_view_item_counter, parent, false);
holder.counterTextView = (TextView) convertView.findViewById(R.id.counterTextView);
holder.stopCounter = (Button) convertView.findViewById(R.id.counterStopInList);
holder.startCounter = (Button) convertView.findViewById(R.id.counterStartInList);
holder.deleteCounter = (Button) convertView.findViewById(R.id.deleteCounter);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData2(getItem(position));
final ViewHolder finalHolder = holder;
holder.stopCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long store = finalHolder.counterData.expirationTime - System.currentTimeMillis();
finalHolder.counterData.isStopped = true;
finalHolder.counterData.expirationTime = store;
finalHolder.stopCounter.setEnabled(false);
finalHolder.stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
/* if(getListSharedPreferences()) {
System.out.println("List before change in stop button " + list.toString());
list = stringToArray(counterString, CounterData[].class);
list.set(position, finalHolder.counterData);
System.out.println("List before change in stop button " + list.toString());
saveListSharedPreferences(list);
}
else {
System.out.println(list.toString());
list.set(position, finalHolder.counterData);
System.out.println(list.toString());
saveListSharedPreferences(list);
}
*/
}
});
holder.startCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
finalHolder.counterData.isStopped = false;
//finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
//finalHolder.setData(finalHolder.counterData);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.stopCounter.setEnabled(true);
finalHolder.stopCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
startUpdateTimer();
/* if(getListSharedPreferences()) {
list = stringToArray(counterString, CounterData[].class);
System.out.println("List before change in start button " + list.toString());
list.set(position, finalHolder.counterData);
System.out.println("List after change in start button " + list.toString());
saveListSharedPreferences(list);
}
else {
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
} */
}
});
final ViewHolder finalHolder1 = holder;
holder.deleteCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* if(finalHolder1.mediaPlayer.isPlaying()) {
finalHolder.mediaPlayer.stop();
// finalHolder.counterData.isSoundPlayedBefore = true;
} */
list.remove(position);
notifyDataSetChanged();
saveListSharedPreferences(list);
}
});
return convertView;
}
}
class ViewHolder {
public TextView counterTextView;
//public List<Long> l;
CounterData counterData;
Button startCounter;
Button stopCounter;
Button deleteCounter;
boolean stop = false;
long timeDiff;
// Context context;
// MediaPlayer mediaPlayer;
// List<CounterData> counterDataList;
public void setData(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void setData2(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
if (!counterData.isStopped) {
timeDiff = counterData.expirationTime - currentTime;
//System.out.println("Time Diff Inside Method " + timeDiff);
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
stopCounter.setEnabled(true);
stopCounter.getBackground().setColorFilter(null);
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
} else {
counterTextView.setText("Times Up");
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
// Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
// v.vibrate(5000);
/* if(!counterData.isSoundPlayedBefore) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
});
counterData.isSoundPlayedBefore = true;
if(findIndex(counterData) != -1) {
int index = findIndex(counterData);
counterDataList.set(index,counterData);
saveListSharedPreferences(counterDataList);
}
} */
}
}
else {
long store = counterData.expirationTime + System.currentTimeMillis() - currentTime;
int seconds = (int) (store / 1000) % 60;
int minutes = (int) ((store / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(store);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
startCounter.setEnabled(true);
startCounter.getBackground().setColorFilter(null);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
}
}
}
And here's my CounterData class
class CounterData {
long expirationTime;
boolean isStopped;
boolean isSoundPlayedBefore;
int id;
public CounterData(long expirationTime, int id) {
this.expirationTime = expirationTime;
isStopped = true;
isSoundPlayedBefore = false;
this.id = id;
}
public String toString() {
return String.valueOf("Remaining Time: " + TimeUnit.MILLISECONDS.toMinutes(this.expirationTime) + ":" + TimeUnit.MILLISECONDS.toSeconds(this.expirationTime));
}
public void setCounterID(int id) {
this.id = id;
}
public int getCounterID() {
return this.id;
}
}
And I add the time from number pickers of Hour, Minute and Second.
case R.id.counterStartStopButton:
long hour = TimeUnit.HOURS.toMillis(numberPickerHour.getValue());
long minute = TimeUnit.MINUTES.toMillis(numberPickerMinute.getValue());
long second = TimeUnit.SECONDS.toMillis(numberPickerSecond.getValue());
// if(getListSharedPreferences()) {
if(getCounterIDSharedPreferences()) {
counterID = counterID + 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
else {
counterID = 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
UPDATE
Here's the shared preferences code
public void saveCounterIDSharedPreferences(int id) {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("Counter ID123", id).commit();
}
public boolean getCounterIDSharedPreferences() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getInt("Counter ID123", -1) != -1) {
counterID = sharedPreferences.getInt("Counter ID123", -1);
return true;
}
else
return false;
}
What turned out to work for me was changing the timer task as following:
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 500, 500);
}
I'm streaming a video in my app, and it works fine.
The problem is that when I try to make it full screen (in a new activity or otherwise), the screen is blank.
I have tried doing it without starting a new activity, as suggested here:
In my main activity:
butFullScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isFS)
setContentView(R.layout.activity_full_screen_video);
else
setContentView(R.layout.activity_starting_point);
}
});
I've also tried opening it in a new activity (which I prefer):
butFullScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start fs intent
Intent myIntent = new Intent(StartingPoint.this, FullScreenVideo.class);
StartingPoint.this.startActivity(myIntent);
}
});
Where FullScreenVideo:
public class FullScreenVideo extends StartingPoint{
//private VideoView vv;
public FullScreenVideo(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen_video);
vv.start();
}
}
And activity_full_screen_video:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:background="#ff000000">
<VideoView
android:id="#+id/vv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And in my manifest:
<activity
android:name=".FullScreenVideo"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize" />
It doesn't show any error or crash, just a blank screen. Also, I'm not using the media controller, so answers without that would be appreciated :)
Edit::
StartingPoint:
public class PlayVid extends ActionBarActivity {
int play = -1;
int k;
int m = 0;
int where;
int pausePressed = 0;
int displaySub = 0;
String curSub = " ";
ArrayList<Stime> timeArray = new ArrayList<Stime>();
Button but;
Button butStop;
Button butSub;
Button butFS;
TextView subs, log;
VideoView vv;
ProgressBar pBar;
int isFS, space;
String srt = "00:00:01,478 --> 00:00:04,020\n" +
"VimeoSrtPlayer Example\n" +
"\n" +
"00:00:05,045 --> 00:00:09,545\n" +
"Support for <i>italic</i> font\n" +
"\n" +
"00:00:09,378 --> 00:00:13,745\n" +
"Support for <b>bold</b> font\n" +
"\n" +
"00:00:14,812 --> 00:00:16,144\n" +
"Multi\n" +
"Line\n" +
"Support ;)\n" +
"\n" +
"00:00:18,211 --> 00:00:21,211\n" +
"Fonts: DejaVu\n" +
"http://dejavu-fonts.org\n" +
"\n" +
"00:00:22,278 --> 00:00:25,678 \n" +
"END OF EXAMPLE FILE";
subParse sp = new subParse(this, srt);
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
pBar = (ProgressBar) findViewById(R.id.progressBar);
subs = (TextView) findViewById(R.id.subtitleBox);
log = (TextView) findViewById(R.id.logBox);
but = (Button) findViewById(R.id.but);
butStop = (Button) findViewById(R.id.butStop);
butSub = (Button) findViewById(R.id.butSub);
butFS = (Button) findViewById(R.id.butFS);
vv = (VideoView) findViewById(R.id.vv);
vv.setVideoPath("#string/video_link");
String[] lines = {" \n", " \n"};
sp.parseSub(srt);
subs.setText("--Click Play to start--\n--Click on SUB to view subtitles--");
final String[] sub2 = log.getText().toString().split(System.getProperty("line.separator"));
final subHelper sob = new subHelper(this, sub2);
final onPauseHelper oph = new onPauseHelper();
final fsHelper fsh = new fsHelper(this);
final playHelper ph = new playHelper();
timeArray.add(new Stime(vv.getDuration(), 0));
but.setOnClickListener(new View.OnClickListener() {
long startTime = 0, trop = 0;
int space = 0;
public void onClick(View v) {
subs.setText(curSub);
fsh.space = space;
if (fsh.isFS == 1) {
//Chill
} else if (play == 0 || play == -1) {
vv.start();
pBar.setVisibility(View.VISIBLE);
if (vv.isPlaying()) {
startTime = Calendar.getInstance().getTimeInMillis();
pBar.setVisibility(View.INVISIBLE);
//Play
if (play == -1) {
sob.setDefaults();
}
oph.putAttr(3, startTime);
but.setText("||");
but.setTextColor(Color.parseColor("#ffaaaaaa"));
if (k < m) {
play = 1;
final Handler handler = new Handler();
final Runnable run = new Runnable() {
#Override
public void run() {
if (k < m && play == 1 && fsh.isFS == 0) {
if (pausePressed == 0) {
oph.putAttr(0, Calendar.getInstance().getTimeInMillis());
} else {
oph.putAttr(0, startTime);
where--;
}
//oph.nextPressed=Calendar.getInstance().getTimeInMillis();
if (space == 0) {
space = 1;
fsh.space = space;
play = sob.subPlay(startTime, 0);
fsh.play = play;
trop = (timeArray.get(k).getTime(1) - timeArray.get(k).getTime(0));
handler.postDelayed(this, Math.abs(trop > 0 ? (trop - oph.done) : 0));
} else if (space == 1) {
space = 0;
fsh.space = space;
play = sob.subPlay(startTime, 1);
fsh.play = play;
trop = timeArray.get(k + 1).getTime(0) - timeArray.get(k).getTime(1);
handler.postDelayed(this, Math.abs(trop > 0 ? (trop - oph.done) : 0));
k++;
}
oph.putAttr(1, Calendar.getInstance().getTimeInMillis());
pausePressed = 0;
sob.pp = 0;
oph.reset();
oph.done = 0;
} else if (k >= m && fsh.isFS == 0) {
final Runnable run = new Runnable() {
#Override
public void run() {
but.setText("↻");
but.setTextColor(Color.parseColor("#ffcdcdcd"));
subs.setText("Play Again?");
handler.removeCallbacks(this);
play = -1;
fsh.play = play;
//ph.saveState(play,0,k,0,curSub,displaySub);
curSub = " ";
}
};
while (vv.isPlaying()) {
}
handler.postDelayed(run, 0);
}
}
};
if (k == 0)
handler.postDelayed(run, (timeArray.get(0).getTime(0)));
else if (k < m) handler.postDelayed(run, 0);
}
}
} else if (play == 1) {
//Pause
vv.pause();
oph.reset();
oph.putAttr(2, Calendar.getInstance().getTimeInMillis());
subs.setText(curSub);
pausePressed = 1;
oph.done = +oph.getProg();
sob.pp++;
but.setText("▶");
but.setTextColor(Color.parseColor("#ffcdcdcd"));
if (k < m) {
if (space == 0) {
space = 1;
fsh.space = space;
} else if (space == 1) {
space = 0;
fsh.space = space;
}
play = sob.subPause(oph.getAttr(2));
fsh.play = play;
}
}
}
});
butStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vv.stopPlayback();
sob.setDefaults();
play = 0;
fsh.play = play;
but.setText("▶");
subs.setText("--Click Play to start--");
curSub = " ";
}
});
butSub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (displaySub == 0) {
displaySub = 1;
subs.setText(curSub);
butSub.setTextColor(Color.parseColor("#ffaaaaaa"));
} else if (displaySub == 1) {
displaySub = 0;
subs.setText(" ");
butSub.setTextColor(Color.parseColor("#ffcdcdcd"));
}
}
});
butFS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start fs intent
Intent myIntent = new Intent(PlayVid.this, TwoFullScreenVideo.class);
PlayVid.this.startActivity(myIntent);
}
});
}
}
FullScreenVideo:
public class FullScreenVideo extends StartingPoint {
fsHelper fsh;
onPauseHelper oph;
subHelper sob;
playHelper ph;
protected PlayVid context;
TextView subs;
Button but, butStop, butSub, butFS;
public FullScreenVideo(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen_video);
subs = (TextView) findViewById(R.id.subtitleBox);
but = (Button) findViewById(R.id.but);
butStop = (Button) findViewById(R.id.butStop);
butSub = (Button) findViewById(R.id.butSub);
butFS = (Button) findViewById(R.id.butFS);
vv = (VideoView) findViewById(R.id.vv);
butFS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FullScreenVideo.this.finish();
}
});
}
}
I have been working on application that displays a problem and 4 possible answers. Answer correctly, and the next problem appears. A wrong answer or letting the timer run out results in a popup that tells the correct answer and that you just lost a "life". Everything works well except that when the popup appears, the countdown timer continues and generates another popup. I can't find a way to get the activity to wait for the button on the dialog to be pressed before continuing to the next problem. I have read many questions/answers here and combed through many pages on the android developers site. Any help with this problem would be greatly appreciated.
public class MainActivity extends Activity {
String problems[][] = {{},{"Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"},
{"Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"}};
String answers[][] = {{},{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"},
{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"}};
public int level;
private int lister[] = {1,1,2,3,4};
Random rand = new Random();
int holder, probcount = 0, score = 0, lives = 5;
String problem, answer1, answer2, answer3, answer4, corrAnswer, l1, l2, l3;
boolean correct = false, changeBG = false, timeup = false, nolives = false, inpopup = false;
MyCount counter;
View lv, lf1, lf2, lf3, lf4, lf5;
MediaPlayer soundright, soundwrong;
final Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
lv = findViewById(R.id.quizshow);
lf1 = findViewById(R.id.Life1);
lf2 = findViewById(R.id.Life2);
lf3 = findViewById(R.id.Life3);
lf4 = findViewById(R.id.Life4);
lf5 = findViewById(R.id.Life5);
Log.v("Events","onCreate");
soundright = MediaPlayer.create(this, R.raw.correct1);
soundwrong = MediaPlayer.create(this, R.raw.correct2);
Button btnAnswer1 = (Button)findViewById(R.id.Answer1);
btnAnswer1.setOnClickListener(onAnswer1);
Button btnAnswer2 = (Button)findViewById(R.id.Answer2);
btnAnswer2.setOnClickListener(onAnswer2);
Button btnAnswer3 = (Button)findViewById(R.id.Answer3);
btnAnswer3.setOnClickListener(onAnswer3);
Button btnAnswer4 = (Button)findViewById(R.id.Answer4);
btnAnswer4.setOnClickListener(onAnswer4);
Button btnExit = (Button)findViewById(R.id.btnExit);
btnExit.setOnClickListener(onExit);
Log.v("Events","onCreate2");
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
level = 1;
doNext();
}
protected void onResume() {
Log.d("Events", "onResume");
super.onResume();
}
protected void onPause() {
Log.d("Events", "onPause");
super.onPause();
counter.cancel();
}
protected void onDestroy() {
Log.d("Events", "onDestroy");
super.onDestroy();
}
private View.OnClickListener onAnswer1=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer1");
if (lister[1] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer2=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer2");
if (lister[2] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer3=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer3");
if (lister[3] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer4=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer4");
if (lister[4] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onExit = new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onExit");
finish();
};
};
private void doNext() {
if (changeBG == true) {
l1 = getResources().getString(R.string.LevelDone1);
l2 = getResources().getString(R.string.LevelDone2)+" "+String.valueOf(level);
l3 = getResources().getString(R.string.LevelDone3);
doPopup();
changeBG = false;
level = level + 1;
score = 0;
probcount = 0;
}
Log.v("Events", "DoNext1");
probcount = probcount + 1;
lister[0] = rand.nextInt(9);
holder = rand.nextInt(3);
lister[holder+1] = lister[0];
This is where I have boring code that makes sure that the 4 answers are different.
problem = problems[level][lister[0]];
TextView pr = (TextView) findViewById(R.id.Problem);
pr.setText(problem);
answer1 = answers[level][lister[1]];
TextView a1 = (TextView) findViewById(R.id.Answer1);
a1.setText(answer1);
answer2 = answers[level][lister[2]];
TextView a2 = (TextView) findViewById(R.id.Answer2);
a2.setText(answer2);
answer3 = answers[level][lister[3]];
TextView a3 = (TextView) findViewById(R.id.Answer3);
a3.setText(answer3);
answer4 = answers[level][lister[4]];
TextView a4 = (TextView) findViewById(R.id.Answer4);
a4.setText(answer4);
corrAnswer = answers[level][lister[0]];
if (probcount < 6){
counter = new MyCount(4000, 1);
} else if (probcount < 11) {
counter = new MyCount(3000, 1);
} else if (probcount < 21) {
counter = new MyCount(2500, 1);
} else if (probcount < 31) {
counter = new MyCount(2000, 1);
} else if (probcount < 41) {
counter = new MyCount(1500, 1);
} else if (probcount < 51) {
counter = new MyCount(1000, 1);
} else {
counter = new MyCount(750, 1);
}
counter.start();
}
private void doRight() {
Log.v("Events", "DoRight");
counter.cancel();
soundright.start();
if (probcount < 6){
score = score +10;
} else if (probcount < 11) {
score = score + 20;
} else if (probcount < 21) {
score = score +30;
} else if (probcount < 31) {
score = score +40;
} else if (probcount < 41) {
score = score + 50;
} else if (probcount < 51) {
score = score + 100;
} else {
score = score + 200;
}
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
if (score > 590) {
changeBG = true;
}
doNext();
}
private void doWrong() {
Log.v("Events", "DoWrong");
counter.cancel();
soundwrong.start();
lives = lives - 1;
if (lives != 5) {
if (lives == 4) {
lf5.setVisibility(View.INVISIBLE);
} else if (lives == 3) {
lf4.setVisibility(View.INVISIBLE);
} else if (lives == 2) {
lf3.setVisibility(View.INVISIBLE);
} else if (lives == 1) {
lf2.setVisibility(View.INVISIBLE);
} else if (lives == 0) {
lf1.setVisibility(View.INVISIBLE);
nolives = true;
}
}
if (nolives) {
l1 = getResources().getString(R.string.LivesGone1);
l2 = getResources().getString(R.string.LivesGone2);
l3 = getResources().getString(R.string.LivesGone3);
} else {
if (timeup) {
l1 = getResources().getString(R.string.TimeExpired);
timeup = false;
} else {
l1 = getResources().getString(R.string.WrongChoice);
}
l2 = getResources().getString(R.string.LifeLost);
l3 = getResources().getString(R.string.CorrAnswer)+" "+corrAnswer;
}
doPopup();
if (nolives) {
score = 0;
probcount = 0;
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
lf1.setVisibility(View.VISIBLE);
lf2.setVisibility(View.VISIBLE);
lf3.setVisibility(View.VISIBLE);
lf4.setVisibility(View.VISIBLE);
lf5.setVisibility(View.VISIBLE);
nolives = false;
}
doNext();
}
private void doPopup() {
Log.v("Events", "DoPopup");
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup);
TextView ln1 = (TextView) dialog.findViewById(R.id.Line1);
TextView ln2 = (TextView) dialog.findViewById(R.id.Line2);
TextView ln3 = (TextView) dialog.findViewById(R.id.Line3);
ln1.setText(l1);
ln2.setText(l2);
ln3.setText(l3);
inpopup = true;
dialog.show();
Button dialogButton = (Button) dialog.findViewById(R.id.btnPopup);
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inpopup = false;
dialog.dismiss();
}
});
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
timeup = true;
doWrong();
}
#Override
public void onTick(long millisUntilFinished) {
double TimeLeft = millisUntilFinished;
TextView timer1 = (TextView) findViewById(R.id.Timer);
timer1.setText(String.valueOf(TimeLeft/1000));
}
}
}
You have a repetitive loop insisde a timer...
Let say, when your timer is is finished, it will call onFinish() and you are calling doWrong() in onFinish(). and doWrong() is calling doPopUp() which will open a Dialog again.(repetitively). To avoid, maintain some flags(like boolean or int) and based on the value of the flag, you decide whether to show PopUp Dialog when timer is finished or cancel the Timer when you are dismissing Diaog...
private void doWrong() {
Log.v("Events", "DoWrong");
counter.cancel();
soundwrong.start();
lives = lives - 1;
if (lives != 5) {
if (lives == 4) {
lf5.setVisibility(View.INVISIBLE);
} else if (lives == 3) {
lf4.setVisibility(View.INVISIBLE);
} else if (lives == 2) {
lf3.setVisibility(View.INVISIBLE);
} else if (lives == 1) {
lf2.setVisibility(View.INVISIBLE);
} else if (lives == 0) {
lf1.setVisibility(View.INVISIBLE);
nolives = true;
}
}
if (nolives) {
l1 = getResources().getString(R.string.LivesGone1);
l2 = getResources().getString(R.string.LivesGone2);
l3 = getResources().getString(R.string.LivesGone3);
} else {
if (timeup) {
l1 = getResources().getString(R.string.TimeExpired);
timeup = false;
} else {
l1 = getResources().getString(R.string.WrongChoice);
}
l2 = getResources().getString(R.string.LifeLost);
l3 = getResources().getString(R.string.CorrAnswer)+" "+corrAnswer;
}
// change here
if(!timeup)
doPopup();
if (nolives) {
score = 0;
probcount = 0;
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
lf1.setVisibility(View.VISIBLE);
lf2.setVisibility(View.VISIBLE);
lf3.setVisibility(View.VISIBLE);
lf4.setVisibility(View.VISIBLE);
lf5.setVisibility(View.VISIBLE);
nolives = false;
}
doNext();
}
I'm adding this answer to be able to mark the question as answered. Please read the comment I left after the question.
Thanks to all that provide help on this site. I have gained much knowledge here.
I am using the below class to rate my app. But the every time I do this, it says "Requested item not found". but the link < play.google.com/store/apps/details?id=com.xxx.xxx > works perfectly in the browser. Why is it not working here?
One more thing I noticed that if I change the package name to the same of some other app, it works. Is there any chance that something might have been missed while uploading the previous version?
public class apprater {
private final static String APP_TITLE = "abcd";
private final static String APP_PNAME = "com.xxx.xxx";
private final static int DAYS_UNTIL_PROMPT = 3;
private final static int LAUNCHES_UNTIL_PROMPT = 7;
public static void app_launched(Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
if (prefs.getBoolean("dontshowagain", false)) { return ; }
SharedPreferences.Editor editor = prefs.edit();
// Increment launch counter
long launch_count = prefs.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
// Get date of first launch
Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
if (date_firstLaunch == 0) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong("date_firstlaunch", date_firstLaunch);
}
// Wait at least n days before opening
if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= date_firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
showRateDialog(mContext, editor);
}
}
editor.commit();
}
public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle("Rate " + APP_TITLE);
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(mContext);
tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
tv.setWidth(240);
tv.setPadding(4, 0, 4, 10);
ll.addView(tv);
Button b1 = new Button(mContext);
b1.setText("Rate " + APP_TITLE);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
System.out.println("eeeeeeeeeeeee: "+APP_PNAME);
dialog.dismiss();
}
});
ll.addView(b1);
Button b2 = new Button(mContext);
b2.setText("Remind me later");
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
ll.addView(b2);
Button b3 = new Button(mContext);
b3.setText("No, thanks");
b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (editor != null) {
editor.putBoolean("dontshowagain", true);
editor.commit();
}
dialog.dismiss();
}
});
ll.addView(b3);
dialog.setContentView(ll);
dialog.show();
}
}
This what I am using now:
public void onClick(View v) {
final String appName = APP_PNAME;
try
{
mContext.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=com.xxx.xxx")));
}
catch (android.content.ActivityNotFoundException anfe)
{
mContext.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id=com.xxx.xxx")));
}
// mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
dialog.dismiss();
}
Try this one
final String appName = getPackageName();
try
{
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id="+ appName)));
}
catch (android.content.ActivityNotFoundException anfe)
{
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appName)));
}