J2me+images in form - java-me

I want to make the clock application where user enters the number in the textbox and click ok then user get the number at every 1 sec.
Example if user enter 5 then the timer start the display screen shows the number 1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,...so on.
Now i had taken form and text field for user to enter the number,then a timer which will change the number at every second.and 10 images of number (0-9).As i want to dispaly the number in very large size.Now i had implement this logic in below way:-
public class Clock extends MIDlet implements CommandListener {
public Command GO, Exit;
TextField TxtData;
protected Display display;
int number, counter;
Form form;
private Timer timer;
private TestTimerTask task;
boolean increment, time;
private StringItem s1 = new StringItem("", "");
Image image0;
Image image1;
Image image2;
Image image3;
Image image4;
Image image5;
Image image6;
Image image7;
Image image8;
Image image9;
Image[] secondAnimation;
protected void startApp() {
display = Display.getDisplay(this);
increment = true;
time = false;
form = new Form("Clock");
TxtData = new TextField("Number:-", "", 5, TextField.NUMERIC);
try {
image0 = Image.createImage("/images/0.png");
image1 = Image.createImage("/images/1.png");
image2 = Image.createImage("/images/2.png");
image3 = Image.createImage("/images/3.png");
image4 = Image.createImage("/images/4.png");
image5 = Image.createImage("/images/5.png");
image6 = Image.createImage("/images/6.png");
image7 = Image.createImage("/images/7.png");
image8 = Image.createImage("/images/8.png");
image9 = Image.createImage("/images/9.png");
secondAnimation = new Image[]{image0,image1,image2, image3, image4, image5, image6, image7, image8, image9};
} catch (IOException ex) {
System.out.println("exception");
}
GO = new Command("Go", Command.OK, 1);
Exit = new Command("Exit", Command.EXIT, 2);
form.append(TxtData);
form.append(s1);
form.addCommand(GO);
form.addCommand(Exit);
form.setCommandListener(this);
display.setCurrent(form);
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional) {
timer.cancel();
notifyDestroyed();
}
public void commandAction(Command cmnd, Displayable dsplbl) {
String label = cmnd.getLabel();
if (label.equals("Go")) {
try {
System.out.println("txt==" + (TxtData.getString()));
if (!TxtData.getString().equalsIgnoreCase("")) {
counter = Integer.parseInt(TxtData.getString());
if (time) {
timer.cancel();
task.cancel();
}
number = 1;
timer = new Timer();
task = new TestTimerTask();
timer.schedule(task, 1000, 1000);
}
} catch (NumberFormatException ex) {
System.out.println("exception");
}
} else if (label.equals("Exit")) {
destroyApp(true);
}
}
private class TestTimerTask extends TimerTask {
public final void run() {
time = true;
s1.setText(""+ number);
if (counter < 10) {
form.append(secondAnimation[0]);
form.append(secondAnimation[0]);
form.append(secondAnimation[number]);
} else if (counter < 100) {
form.append(secondAnimation[0]);
form.append(secondAnimation[(number % 100) / 10]);
form.append(secondAnimation[(number % 10)]);
} else if (counter < 1000) {
form.append(secondAnimation[(number % 10)]);
form.append(secondAnimation[(number % 100) / 10]);
form.append(secondAnimation[(number / 100)]);
}
number++;
if (number == counter + 1) {
number = 0;
}
}
} }
But as the form goes on appending the image as timer moves it is not showing the desired output!
I had tried to do it through LWUIT but as i had user 10 .png files and adding LWUIT.jar file make the size of .jar file 557kb which is very heavy.
So i want to do it through normal forms only.
I cant use canvas as the keypad can vary like (touch,qwerty etc).So i need to do normal form or LWUIT only.Can anyone please help me for this.

I noticed you only append items but never remove - is that intended?
Also, did you try two different forms to animate instead of one? For simple test, say, fill them in parallel, just call setCurrent for one that is not displayed in the moment of update
//...
private void appendTwice(Image image) {
form1.append(image);
form2.append(image);
}
//...
public final void run() {
time = true;
s1.setText(""+ number);
if (counter < 10) {
appendTwice(secondAnimation[0]);
//...
}
display.setCurrent(number & 1 == 0 ? form1 : form2);
number++;
//...
}
//...

Related

Worker stop in the middle and not updating progress bar

I'm trying to load information with worker and using reportprogress to update progress bar until finshing, but the worker stop working and doesn't finish the for loop or continue after several minutes. I don't know what's the problem and I tried every post here I can find related to this problem and didn't get anything. I hope I can finally get an answer posting my problem here.
Here's the relevant code:
public class Class1
{
public BackgroundWorker unit_read_data_setting_Worker;
public Class1()
{
unit_read_data_setting_Worker = new BackgroundWorker();
unit_read_data_setting_Worker.WorkerReportsProgress = true;
unit_read_data_setting_Worker.WorkerSupportsCancellation = false;
unit_read_data_setting_Worker.DoWork += new DoWorkEventHandler(unit_read_data_setting);
unit_read_data_setting_Worker.ProgressChanged += new ProgressChangedEventHandler(_update_progress);
unit_read_data_setting_Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Completed);
}
public void unit_read_data_setting(object sender = null, DoWorkEventArgs e = null)
{
lock (FamilyTreeViewModel.Lock_ParameterList)
{
ObservableCollection<Parameter_UC_ViewModel> _internal_parameter_list =
FamilyTreeViewModel.GetInstance.ParameterList;
if (FamilyTreeViewModel.GetInstance.SelectedUnitSetting != null)
{
if (_internal_parameter_list.Count > 0)
{
for (int i = 0; i < _internal_parameter_list.Count; i++)
{
int startValue = i * 100 / _internal_parameter_list.Count;
unit_read_data_setting_Worker.ReportProgress(startValue);
// do stuff related to the index
// when progress_bar at 76 value, the loop stoppes and cotinue after a minute
}
}
}
}
}
private void _update_progress(object sender, ProgressChangedEventArgs e)
{
FamilyTreeViewModel.GetInstance.Unit_read_data_setting_progress_bar = e.ProgressPercentage;
}
private void Completed(object sender, RunWorkerCompletedEventArgs e)
{
// never gets here but there's no error
}
}

RecylerView to pdf

Hello am new to Android studio
I have made recylerview for transaction details . I need to create pdf for this recylerview items.
Example: I have 24 cardviews in recylerview so need to create pdf with each page 4 cardviews only . So totally I need to get pdf as 6 pages .
How to do that . Thanks in advance.
This is sample image of my view
Am passing below code
recyclerView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(),View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
Bitmap bm=Bitmap.createBitmap(recyclerView.getWidth(),recyclerView.getMeasuredHeight(),Bitmap.Config.ARGB_8888);
String mpath2="/mnt/sdcard/mathanpaymentpdf";
File imageFile = new File(mpath2);
PDFHelper pdfHelper = new PDFHelper(imageFile,this);
pdfHelper.saveImageToPDF(recyclerView,bm,"mathan"+System.currentTimeMillis());
public class PDFHelper {
private File mFolder;
private File mFile;
private Context mContext;
public PDFHelper(File folder, Context context) {
this.mContext = context;
this.mFolder = folder;
if(!mFolder.exists())
mFolder.mkdirs();
}
public void saveImageToPDF(View title, Bitmap bitmap, String filename) {
mFile = new File(mFolder, filename + ".pdf");
if (!mFile.exists()) {
int height = title.getHeight() + bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, title.getHeight(), bitmap.getWidth(),bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This am tried am getting pdf on a single page only
Just I need to split into multiple pages.
Note: I need code in java, not in kotlin
Am solved this by using itext library
implementation 'com.itextpdf:itextpdf:5.0.6'
Then call with RecylerView
public void generatePDF(RecyclerView view) {
RecyclerView.Adapter adapter = view.getAdapter();
int sie2=adapter.getItemCount();
if (sie2 == 0) {
Toast.makeText(this,"No Transactions",Toast.LENGTH_LONG).show();
}else{
Bitmap bigBitmap = null;
if (adapter != null) {
int size = adapter.getItemCount();
int height = 0;
Paint paint = new Paint();
int iHeight = 0;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
for (int i = 0; i < size; i++) {
RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
adapter.onBindViewHolder(holder, i);
holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
holder.itemView.setDrawingCacheEnabled(true);
holder.itemView.buildDrawingCache();
Bitmap drawingCache = holder.itemView.getDrawingCache();
if (drawingCache != null) {
bitmaCache.put(String.valueOf(i), drawingCache);
}
height += holder.itemView.getMeasuredHeight();
}
bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
Canvas bigCanvas = new Canvas(bigBitmap);
bigCanvas.drawColor(Color.WHITE);
Document document=new Document();
final File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MAT"+System.currentTimeMillis()+".pdf");
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < size; i++) {
try {
//Adding the content to the document
Bitmap bmp = bitmaCache.get(String.valueOf(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
com.itextpdf.text.Image image= com.itextpdf.text.Image.getInstance(stream.toByteArray());
//Image image = Image.getInstance(stream.toByteArray());
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 50) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER | com.itextpdf.text.Image.ALIGN_TOP);
if (!document.isOpen()) {
document.open();
}
document.add(image);
} catch (Exception ex) {
Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
}
}
if (document.isOpen()) {
document.close();
}
// Set on UI Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivityAdminMain.this);
builder.setTitle("Success")
.setMessage("PDF File Generated Successfully.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// dialog.dismiss();
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent56 = Intent.createChooser(target, "Open File");
try {
startActivity(intent56);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivityAdminMain.this,"No PDF Viewer Installed.",Toast.LENGTH_LONG).show();
}
}
}).show();
}
});
}}
}
100% working.. This helps to anyone needs

The need for the multithreading in javafx

I'm new to javafx and I have a question. My project is a voice browser with some simple command but I have an issue in switch(). The command at lines one and three of first case statement work, but line 2 does not. But if I remove the while loop, it works well! I have no idea how to solve this, help me please!
Here is my code
btSpeak.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
new Task<Void>(){
public Void call(){
int click=JOptionPane.showConfirmDialog(null, "Bạn đã sẵn sàng trải nghiệm với VoiceCommand chưa", "Speak", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(click==JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "Start", "Speak", JOptionPane.INFORMATION_MESSAGE);
// code for voice recognize
try {
URL url;
url = HelloWorld.class.getResource("helloworld.config.xml");
System.out.println("Loading..."+url.toString());
ConfigurationManager cm = new ConfigurationManager(url);
final Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
Microphone microphone = (Microphone) cm.lookup("microphone");
/* allocate the resource necessary for the recognizer */
recognizer.allocate();
/* the microphone will keep recording until the program exits */
if (microphone.startRecording())
{
System.out.println("Say: (Leen | Xuoongs| Trais | Phair | DDi |Veef| Dongs-Tab|Mowr-Tab| Noi - Dung| Trang-Chur|Trang-Truoc)") ;
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
/*
* This method will return when the end of speech
* is reached. Note that the endpointer will determine
* the end of speech.
*/
// Platform.runLater(new Runnable(){
// public void run(){
int i = 0;
while(i< 5) {
//Thread.this.notifyAll();
Result result = recognizer.recognize();
if (result != null)
{
int t = 0;
System.out.println("Enter your choise"+ "\n");
resultText = result.getBestFinalResultNoFiller();
System.out.println("You said: " + resultText + "\n");
if(resultText.equals("xuoongs")) {
t = 1;
} else if(resultText.equals("leen")) {
t = 2;
}
switch(t) {
case 1: {
JOptionPane.showMessageDialog(null, "xuống");//line 1
webEngine.executeScript("window.scrollBy(0,100)");line 2
break;// line 3
}
case 2: {
JOptionPane.showMessageDialog(null, "lên");
webEngine.executeScript("window.scrollBy(0,-100)");
break;
}
}// end switch
}// end if
}//end while()
}// end if
} catch (PropertyException e) {
System.err.println("Problem configuring HelloWorld: " + e);
e.printStackTrace();
}
}
}
}.run());
}// end button
});

Arguments and changing the value

A newbie, please excuse the terms and explanation.
I have a program that accepts arguments which are in seconds. This in turn runs a timer that shows on the form. I want to give the user the ability to pause the timer for a set amount of time. I am having difficulty in trying to add time after the user Clicks the button as the method that runs the timer and countdown I have a method that gets the parameters of the argument.
I would like to maybe just get the parameters/arguments globally and then use them in all the different methods or threads. I am trying to do this in c# and wpf.
Code below:
public partial class MainWindow : Window
{
//int TimeOutPeriod = Int32.Parse("3600");
//private Timer timer;
System.Timers.Timer timer = new System.Timers.Timer();
public MainWindow()
{
InitializeComponent();
//timer = new Timer(1000);
timer = new System.Timers.Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
string[] param = Environment.GetCommandLineArgs();
int TimeOutPeriod = Int32.Parse(param[1]);
ProgressBar1.Maximum = TimeOutPeriod;
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
string [] param = Environment.GetCommandLineArgs();
int TimeOutPeriod = Int32.Parse(param[1]);
int InYourFaceDisplay = Int32.Parse(param[2]);
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
{
if (ProgressBar1.Value < TimeOutPeriod)
{
ProgressBar1.Value += 1;
RebootCDown.Content = "Machine will reboot in : " + (TimeOutPeriod - ProgressBar1.Value) + " Secs";
if ((TimeOutPeriod - ProgressBar1.Value) < InYourFaceDisplay)
{
this.Activate();
}
}
else
{
ShutDownWindows("0");
timer.Stop();
this.Close();
}
}));
}
private void SnoozeNow_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
ShowInTaskbar = false;
ni.Icon = new System.Drawing.Icon("C:\\temp\\RebootIco.ico");
ni.Visible = true;
ShowInTaskbar = false;
ni.ShowBalloonTip(5000, "Test App", "Notify icon is working! Right click to access the context menu.", System.Windows.Forms.ToolTipIcon.Info);
Task.Delay(10000);
ShowInTaskbar = true;
}
}

AudioRecord buffer values

Hi I am building an app that will use incoming audio from the MIC and compare it with a stored sound file. At the moment I am trying to get to grips with what the data from the AudioRecord function looks like when saved to a array of bytes. My problem is that the values that are returned are all zero. I don't know if I am maybe not using/setting up the AudioRecord function properly. Here is my code:
import android.app.Activity;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SnoreAlarmActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button start, stop;
TextView display;
Boolean rec = false;
AudioRecord snore;
byte[] arrayOfByte = new byte[16 * 1024 / 8];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.bStart);
stop = (Button) findViewById(R.id.bStop);
display = (TextView) findViewById(R.id.tAnswer);
start.setOnClickListener(this);
stop.setOnClickListener(this);
int i = AudioRecord.getMinBufferSize(44100, 16, 2);
snore = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, 16, 2, i);// From
// MIC,Sample
// Rate
// of
// 44100,
// Channel_IN_MONO,16Bit
// Encoding,buffer
// size
// i
new Record().start();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.bStart:
rec = true;
break;
case R.id.bStop:
rec = false;
snore.stop();
snore.release();
for (int i = 0; i < 100; i++) {
int x = (int) arrayOfByte[i];
Log.w("Tag", "" + x);
}
break;
}
}
class Record extends Thread {
Record() {
}
#Override
public void run() {
// TODO Auto-generated method stub
while (rec) {
snore.startRecording();
snore.read(arrayOfByte, 0, (16 * 1024 / 8));
}
}
}
}
So my question is, why am I getting zero's?
*Also I know I should store the data in a short because of 16Bit encoding, will do that later, just trying to understand the values returned from the AudioRecord function at the moment.
Recording through MIC give me headache :)
Hope this will help because I lost whole day playing with it.
Here are steps which must be satisfied for MIC to work
Maniefst.xml MUST contains:
< uses-permission android:name="android.permission.RECORD_AUDIO" />
AudioRecord buffer should be set with AudioRecord.getMinBufferSize (you did it right)
If MIC wasn't released, you WON'T be able to bind to MIC again!
Restarting your phone will reset MIC.
Here is short example how I did it.
private android.media.AudioRecord aRecorder = null;
private Boolean breakLoop = false;
private byte[] buffer;
public Boolean StartRecording()
int freq = 22050;
try
{
prepareWaveFile(MyRandomAccessFile); //open file and writes WAV header
int bufferSize = android.media.AudioRecord.getMinBufferSize(freq, android.media.AudioFormat.CHANNEL_IN_MONO, android.media.AudioFormat.ENCODING_PCM_16BIT);
buffer = new byte[bufferSize];
if(bufferSize == AudioRecord.ERROR_BAD_VALUE){
Log.e(LOG_TAG, "Min buff size error");
return false;
}
aRecorder = new android.media.AudioRecord(MediaRecorder.AudioSource.MIC, freq, android.media.AudioFormat.CHANNEL_IN_MONO, android.media.AudioFormat.ENCODING_PCM_16BIT, bufferSize);
aRecorder.startRecording();
breakLoop = false;
int TotalSize=0; //koliko je snimljeno podataka
while (TotalSize < freq * 2 * 1 * 30) { //SampleRate * BytesPerSample * NumberOfChannels * seconds
int bufferReadResult = aRecorder.read(buffer, 0, bufferSize);
TotalSize+=bufferReadResult; // filesize failsafe
if (breakLoop) break; //if other thread stops recording
if (bufferReadResult>0) MyRandomAccessFile.write(buffer, 0, bufferReadResult); //write into some file ...
}
aRecorder.stop();
aRecorder.release(); //this is mandatory !
updateWaveFile(MyRandomAccessFile); //updates wave header
MyRandomAccessFile.close();
return true;
} catch (Exception e)
{
Log.e(LOG_TAG, "StartRecording: LOOP " + e);
try
{
aRecorder.stop();
} catch(Exception ex) {}
try
{
aRecorder.release();
} catch(Exception ex) {}
try
{
randomAccessWriter.close();
} catch(Exception ex) {}
return false;
}
are you on the Emulator? I heard that the Mic doesn't work on that.

Resources