Android aChartEngine Bar Chart is not working - java

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nextstatschart);
myDataset = new XYMultipleSeriesDataset ();
statsRenderer = new DefaultRenderer();
myRenderer.setLabelsColor(Color.BLUE);
myRenderer.setLabelsTextSize(12);
myRenderer.setAxesColor(Color.BLACK);
myRenderer.setBackgroundColor(Color.WHITE);
myRenderer.setAntialiasing(true);
myRenderer.setShowLabels(true);
myRenderer.setShowGrid(true);
myRenderer.setChartTitle("Next Three Months Statistical Analysis");
myRenderer.setChartTitleTextSize(16);
myRenderer.setZoomEnabled(true);
myRenderer.setChartTitle(heading);
myRenderer.setLabelsColor(Color.BLACK);
myRenderer.setXAxisMin(0);
myRenderer.setXAxisMax(100);
myRenderer.setYAxisMin(0);
myRenderer.setYAxisMax(100);
myRenderer.setYLabelsAlign(Align.RIGHT);
myRenderer.setXTitle ("Case Type");
myRenderer.setYTitle ("Count");
myRenderer.setMargins(new int[] { 30, 40, 10, 40 });
Bundle b = getIntent().getExtras();
typ = b.getStringArray("typ");
nums = b.getStringArray("counts");
percentages = b.getDoubleArray("percs");
stat_count = b.getInt("stat_count");
X_Axis = b.getDoubleArray("typp");
Y_Axis = b.getDoubleArray("contt");
}
#Override
protected void onResume() {
super.onResume();
try {
refreshChart();
if (statsChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.statschart);
// statsChartView = ChartFactory.getPieChartView(getApplicationContext(), statsSeries, statsRenderer);
// statsChartView = ChartFactory.getLineChartView(getApplicationContext(), xyDataset, xyRender);
// statsChartView = ChartFactory.getBarChartView(context, dataset, renderer, type)
statsChartView = ChartFactory.getBarChartView(getApplicationContext(), myDataset, myRenderer,Type.DEFAULT);
layout.addView(statsChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout.addView(statsChartView);
statsChartView.refreshDrawableState();
statsChartView.setBackgroundColor(Color.WHITE);
} else {
statsChartView.repaint();
}
// refreshChart();
}catch(Exception e){
e.printStackTrace();
}
}
void refreshChart() {
try {
mySeries = new XYSeries (series);
int[] colorpool = new int[] { 0xff000099, 0xff009900, 0xffff0000,
0xffffff00, 0xff990099, 0xffff9900, 0xff996600, 0xffcccccc,
0xff990000, 0xff66cccc, 0xff99ccff, 0xffccffcc };
int[] colors = new int[stat_count];
DecimalFormat Currency = new DecimalFormat("#0.00");
for (int i = 0; i < stat_count; i++) {
mySeries.add(Double.parseDouble(typ[i]),Double.parseDouble(nums[i]));
if (i > 11) {
colors[i] = 0xff333333;
} else {
colors[i] = colorpool[i];
}
}
myDataset.addSeries (mySeries);
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
// statsRenderer.addSeriesRenderer(r);
xyRender.addSeriesRenderer(r);
}
mySeriesRenderer = new XYSeriesRenderer ();
if (series.equals("Weight")) {
mySeriesRenderer.setColor (0xff009900);
mySeriesRenderer.setPointStyle(PointStyle.POINT);
} else {
mySeriesRenderer.setColor (0xff990099);
}
myRenderer.addSeriesRenderer (mySeriesRenderer);
int length = myRenderer.getSeriesRendererCount();
for (int i = 0; i < length; i++) {
((XYSeriesRenderer) myRenderer.getSeriesRendererAt(i)).setFillPoints(true);
}
// Draw the chart
statsChartView.repaint ();
} catch (Exception e) {
e.printStackTrace();
//Exception Code
}
}
}
E/AndroidRuntime(910): FATAL EXCEPTION: main
E/AndroidRuntime(910): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.courts.action/com.courts.action.NextStatsChart}: java.lang.NullPointerException

It can be because of this,
<activity android:name="com.courts.action.NextStatsChart" android:label="#string/app_name" />

Related

Null Pointer Exceptions on a non null List Float Object by calling get method

I am using Java programming to approach Android Studio (Android API 32). The scenario is that some data received from an external device through WiFi are repeatedly stored in an array which will be converted in a Float List Object pitch_2, and at some point, this list will be averaged in next function.
This function is called in this loop:
private class Thread2 implements Runnable {
#Override
public void run() {
while (true) {
try {
byte[] buffX_2 = new byte[BUFFER_LENGTH*2-8];
if (btn_client_2.isEnabled()) {
int k_2 = inputStream_2.read(buffX_2);
byte[] c_2 = new byte[buffX_2.length + client2.length];
System.arraycopy(buffX_2, 0, c_2, 0, buffX_2.length);
System.arraycopy(client2, 0, c_2, buffX_2.length, client2.length);
fou.write(c_2);
float pitch_2 = from_bytes_to_float(buffX_2,18);
pitch_buff_2.add(pitch_2);
int [] data_2 = unpack(buffX_2);
if (message != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (x%plot_freq==0) {
float value_2 = average_list(pitch_buff_2, plot_freq);
if (y>=4000) {
series_2.resetData(new DataPoint[] {new DataPoint(x, value_2)});
y = 0;
} else {
series_2.appendData(new DataPoint(x, value_2),true,500);
}
pitch_buff_2.clear();
Log.v("Plot Update","OK");
}
x += 1;
y += 1;
Log.v("Plot Update",String.valueOf(x));
}
});
} else {
Thread1 = new Thread(new MainActivity.Thread1());
Thread1.start();
return;
}
Thread.sleep(1);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
Here my function which is called average_list simply intends to take as input a List Object and do the average:
if (list == null) {
return 100/n_elements;
} else {
float value = 0;
for(int j = 0; j < list.size(); j++) {
value = value + list.get(j);
}
return value/n_elements;
}
}
In a totally randomic way, this function might generate the following error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication.smart_crutches_app, PID: 25434
java.lang.NullPointerException: Attempt to invoke virtual method 'float java.lang.Float.floatValue()' on a null object reference
at com.example.myapplication.smart_crutches_app.MainActivity.average_list
I have put a not-null control (following this suggestion What is a NullPointerException, and how do I fix it?) in the average_list function in order to avoid this error but still happens.
As far as I understand I call get method in a null object, but how is it possible if I have put an if statement?
I am hundred per cent sure I am forgetting something, but I cannot figure out what yet.
What do you think?
Your help would be really appreciated.
Thanks.
You're calling .floatValue() on an expression whose type is Float (SOURCE: Just read the error message you get!), but the expression resolves to null. Your if(list == null) check checks if the list is null which is therefore irrelevant to this problem: It's not about list being null. It's about some expression of type Float being null.
You don't appear to have any Float values anywhere; however, that's not quite true: Your list is filled with Float objects, and you are auto-unboxing it on your value = value + list.get(j) line. Java only supports numeric math on primitives (float - primitives are the direct value and cannot be null - null is a reference, as in, this variable can point at an object, but currently it points at nothing).
And lists can only contain objects.
So, seemingly, value = value + list.get(j) is impossible: list.get(j) returns objects (Floats to be specific, which aren't the same as floats), and objects don't do math.
However, what's happening here is auto-unboxing: Anytime the code doesn't make sense, but it would make sense if you 'unbox' the primitive wrapper type (Float is the wrapper type for float), then java assumes you meant to invoke .floatValue() on your Float object.
So java just inserts that for you. And like all instance method invocations, if the receiver (the thing to the left of the dot) is null, you get a NullPointerException - and that's where its coming from. list.get(j) is returning null and that causes an NPE.
So, the real question is, how did nulls end up in your list?
There's no way to answer that question; you did not include the relevant code. In general, when asking SO questions, try to paste a complete snippet that anybody can just paste into a terminal and run.
Here the entire code #rzwitserloot
//Some import
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
#SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {
ServerSocket serverSocket;
ServerSocket serverSocket_2;
ServerSocket serverSocket_3;
Thread Thread1 = null;
Thread Thread11 = null;
Thread Thread111 = null;
TextView tvMessages;
Button btnStart, btnEnd, btnConnect;
GraphView graph;
GraphView graph2;
LineGraphSeries<DataPoint> series;
LineGraphSeries<DataPoint> series_2;
LineGraphSeries<DataPoint> series_3;
LineGraphSeries<DataPoint> lc;
LineGraphSeries<DataPoint> lc2;
LineGraphSeries<DataPoint> lc3;
String message,current_time;
public static String SERVER_IP = "";
public static final int SERVER_PORT = 8080;
public static final int SERVER_PORT_2 = 50000;
public static final int SERVER_PORT_3 = 40000;
public static final int BUFFER_LENGTH = 20;
int x, y, client_connected;
int plot_freq;
private PrintWriter output;
private PrintWriter output_2;
private PrintWriter output_3;
private DataInputStream inputStream;
private DataInputStream inputStream_2;
private DataInputStream inputStream_3;
FileOutputStream fou;
OutputStreamWriter saveStream;
RadioButton btn_client_1,btn_client_2,btn_client_3;
byte [] client1 = {0,0};
byte [] client2 = {1,1};
byte [] client3 = {2,2};
Socket socket_3;
Socket socket_2;
Socket socket;
List<Float> pitch_buff_1 = new ArrayList<>();
List<Float> pitch_buff_2 = new ArrayList<>();
List<Float> pitch_buff_3 = new ArrayList<>();
List<Integer> lc_buff_1 = new ArrayList<>();
List<Integer> lc_buff_2 = new ArrayList<>();
List<Integer> lc_buff_3 = new ArrayList<>();
Map<Integer, String> data;
Map<Integer, Integer> sounds;
public int ID_audio;
public int flag_Acq = 1;
public int flag_Acq_1 = 1;
public int flag_Acq_2 = 1;
public int flag_Acq_3 = 1;
ColorStateList colorStateList = new ColorStateList(
new int[][]
{
new int[]{-android.R.attr.state_enabled}, // Disabled
new int[]{android.R.attr.state_enabled} // Enabled
},
new int[]
{
Color.GRAY, // disabled
Color.GREEN // enabled
}
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMessages = findViewById(R.id.tvMessages);
tvMessages.setMovementMethod(new ScrollingMovementMethod());
btnStart = findViewById(R.id.btnStart);
btnEnd = findViewById(R.id.btnEnd);
btnConnect = findViewById(R.id.btnConnect);
Spinner mySpinner_ID = findViewById(R.id.spinner);
graph = findViewById(R.id.graph);
graph2 = findViewById(R.id.graph2);
series = new LineGraphSeries<>();
series_2 = new LineGraphSeries<>();
series_3 = new LineGraphSeries<>();
lc = new LineGraphSeries<>();
lc2 = new LineGraphSeries<>();
lc3 = new LineGraphSeries<>();
series_2.setColor(Color.RED);
series_3.setColor(Color.DKGRAY);
lc2.setColor(Color.RED);
lc3.setColor((Color.DKGRAY));
graph.addSeries((series));
graph.addSeries(series_2);
graph.addSeries(series_3);
graph.getViewport().setScalable(true); // activate horizontal zooming and scrolling
graph.getViewport().setScrollable(true); // activate horizontal scrolling
graph.getViewport().setMinY(-201);
graph.getViewport().setMaxY(201);
graph.getViewport().setMaxX(2001);
graph.getViewport().setMinX(0);
graph.getViewport().setYAxisBoundsManual(true);
graph.setTitle("Pitch [°]");
graph2.addSeries((lc));
graph2.addSeries(lc2);
graph2.addSeries(lc3);
graph2.getViewport().setScalable(true); // activate horizontal zooming and scrolling
graph2.getViewport().setScrollable(true); // activate horizontal scrolling
graph2.getViewport().setMinY(400);
graph2.getViewport().setMaxY(2000);
graph2.getViewport().setMaxX(2001);
graph2.getViewport().setMinX(0);
graph2.getViewport().setYAxisBoundsManual(true);
graph2.setTitle("Applied Weight [N]");
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_HHmmss", Locale.getDefault());
current_time = sdf.format(new Date());
File folder = getExternalFilesDir("Data_Server_ClientS");
File output = new File(folder,current_time+".txt");
btn_client_1 = findViewById(R.id.btn_client_1);
btn_client_2 = findViewById(R.id.btn_client_2);
btn_client_3 = findViewById(R.id.btn_trunk);
btn_client_1.setButtonTintList(colorStateList); // set the color tint list
btn_client_1.invalidate(); // Could not be necessary
btn_client_2.setButtonTintList(colorStateList); // set the color tint list
btn_client_2.invalidate(); // Could not be necessary
btn_client_3.setButtonTintList(colorStateList); // set the color tint list
btn_client_3.invalidate(); // Could not be necessary
btn_client_1.setEnabled(false);
btn_client_2.setEnabled(false);
btn_client_3.setEnabled(false);
data = new HashMap<>();
data.put(1, "Vibration");
data.put(2, "Audio");
data.put(3, "Both");
sounds = new HashMap<>();
sounds.put(1, R.raw.crutch_left);
sounds.put(2, R.raw.crutch_right);
sounds.put(3, R.raw.trunk_down);
sounds.put(4, R.raw.trunk_up);
sounds.put(5,R.raw.sampling_sx);
sounds.put(6,R.raw.sampling_dx);
sounds.put(7,R.raw.sampling_trunk);
sounds.put(8,R.raw.start);
sounds.put(9,R.raw.end);
tvMessages.setText("Not yet connected crutches\n");
btnConnect.setOnClickListener(v -> {
try {
fou = new FileOutputStream(output);
saveStream = new OutputStreamWriter(fou);
Toast.makeText(MainActivity.this, "Done" + folder.getAbsolutePath(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
SERVER_IP = getLocalIpAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Thread1 = new Thread(new Thread1());
Thread1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread11 = new Thread(new Thread11());
Thread11.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread111 = new Thread(new Thread111());
Thread111.start();
});
try {
fou = new FileOutputStream(output);
saveStream = new OutputStreamWriter(fou);
Toast.makeText(this, "Done" + folder.getAbsolutePath(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
SERVER_IP = getLocalIpAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Thread1 = new Thread(new MainActivity.Thread1());
Thread1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread11 = new Thread(new MainActivity.Thread11());
Thread11.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread111 = new Thread(new MainActivity.Thread111());
Thread111.start();
/*
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = etMessage.getText().toString().trim();
if (!message.isEmpty()) {
new Thread(new MainActivity.Thread3(message)).start();
}
}
});
*/
btnStart.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
message = "S";
new Thread(new MainActivity.Thread3(message)).start();
plot_freq= 10;
ID_audio = Integer.parseInt(mySpinner_ID.getSelectedItem().toString());
if (btn_client_1.isEnabled()) {
pitch_buff_1.clear();
lc_buff_1.clear();
}
if (btn_client_2.isEnabled()) {
pitch_buff_2.clear();
lc_buff_2.clear();
}
if (btn_client_3.isEnabled()) {
pitch_buff_3.clear();
lc_buff_3.clear();
}
new Thread(new MainActivity.Thread2()).start();
new Thread(new MainActivity.Thread_BioFeedback(8,2)).start();
}
});
btnEnd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "E";
new Thread(new MainActivity.Thread3(message)).start();
try {
new Thread(new MainActivity.Thread_BioFeedback(9,2)).start();
saveStream.close();
Thread.sleep(2000);
finishAndRemoveTask();
if (btn_client_1.isEnabled()) {
serverSocket.close();
socket.close();
}
if (btn_client_2.isEnabled()) {
serverSocket_2.close();
socket_2.close();
}
if (btn_client_3.isEnabled()) {
serverSocket_3.close();
socket_3.close();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
});
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void Vibrate(int time) {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(time,VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
vibrator.vibrate(time);
}
// vibrator.vibrate(VibrationEffect.createOneShot(time,VibrationEffect.DEFAULT_AMPLITUDE));
}
public void Sound(int action) {
int so_sound = sounds.get(action);
final MediaPlayer audio = MediaPlayer.create(this,so_sound);
audio.start();
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void run_feedback(int sound_ID, int time_vibration, int ID){
switch (ID){
case 1:
Vibrate(time_vibration);
break;
case 2:
Sound(sound_ID);
break;
case 3:
Vibrate(time_vibration);
Sound(sound_ID);
break;
default:
Vibrate(time_vibration);
Sound(sound_ID);
break;
}
}
private String getLocalIpAddress() throws UnknownHostException {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
assert wifiManager != null;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipInt = wifiInfo.getIpAddress();
return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress();
}
public static int[] unpack(final byte[] byte_array) {
final int[] integerReadings = new int[byte_array.length / 2];
for(int counter = 0, integerCounter = 0; counter < byte_array.length;) {
integerReadings[integerCounter] = convertTwoBytesToInteger(byte_array[counter], byte_array[counter + 1]);
counter += 2;
integerCounter++;
}
return integerReadings;
}
private static int convertTwoBytesToInteger(final byte byte1, final byte byte2) {
final int unsignedInteger1 = getUnsignedInteger(byte2);
final int unsignedInteger2 = getUnsignedInteger(byte1);
int unsignedInteger = unsignedInteger1 * 256 + unsignedInteger2;
if ((unsignedInteger)>32768) {
unsignedInteger = unsignedInteger - 65536;
}
return unsignedInteger;
}
private static int getUnsignedInteger(final byte b) {
int unsignedInteger = b;
if(b < 0) {
unsignedInteger = b + 256;
}
return unsignedInteger;
}
public static float from_bytes_to_float (byte [] array, int index) {
byte [] bytes = new byte [4];
for(int j = 0; j < bytes.length; j++) {
bytes[j] = array[index+j];
}
int asInt = (bytes[0] & 0xFF)
| ((bytes[1] & 0xFF) << 8)
| ((bytes[2] & 0xFF) << 16)
| ((bytes[3] & 0xFF) << 24);
return Float.intBitsToFloat(asInt);
}
public static float average_list (List<Float> list, int n_elements) {
if (list == null) {
return 100/n_elements;
} else {
float value = 0;
for(int j = 0; j < list.size(); j++) {
value = value + list.get(j);
}
return value/n_elements;
}
}
public static float average_listInt (List<Integer> list, int n_elements) {
if (list == null) {
return 100/n_elements;
}
else {
float value = 0;
for(int j = 0; j < list.size(); j++) {
value += list.get(j);
}
return value/n_elements;
}
}
class Thread1 implements Runnable {
#Override
public void run() {
// Socket socket;
try {
serverSocket = new ServerSocket(SERVER_PORT);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
try {
socket = serverSocket.accept();
client_connected++ ;
output = new PrintWriter(socket.getOutputStream());
inputStream = new DataInputStream(socket.getInputStream());
runOnUiThread(new Runnable() {
#Override
public void run() {
tvMessages.append("Client 1 Connected\n");
btn_client_1.setEnabled(true);
if(client_connected == 3) {
// new Thread(new MainActivity.Thread2()).start();
tvMessages.append("You can start your recording...\n");
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Thread11 implements Runnable {
#Override
public void run() {
try {
serverSocket_2 = new ServerSocket(SERVER_PORT_2);
runOnUiThread(new Runnable() {
#Override
public void run(){
}
});
try {
socket_2 = serverSocket_2.accept();
client_connected++ ;
output_2 = new PrintWriter(socket_2.getOutputStream());
inputStream_2 = new DataInputStream(socket_2.getInputStream());
runOnUiThread(new Runnable() {
#Override
public void run() {
tvMessages.append("Client 2 Connected\n");
btn_client_2.setEnabled(true);
if(client_connected == 3) {
tvMessages.append("You can start your recording...\n");
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Thread111 implements Runnable {
#Override
public void run() {
try {
serverSocket_3 = new ServerSocket(SERVER_PORT_3);
runOnUiThread(new Runnable() {
#Override
public void run(){
}
});
try {
socket_3 = serverSocket_3.accept();
client_connected++ ;
output_3 = new PrintWriter(socket_3.getOutputStream());
inputStream_3 = new DataInputStream(socket_3.getInputStream());
runOnUiThread(new Runnable() {
#Override
public void run() {
tvMessages.append("Client 3 Connected\n");
btn_client_3.setEnabled(true);
if(client_connected == 3) {
tvMessages.append("You can start your recording...\n");
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Thread_BioFeedback implements Runnable {
private int case_audio;
private int ID;
Thread_BioFeedback(int case_audio, int ID) {
this.case_audio = case_audio;
this.ID = ID;
}
#Override
#RequiresApi(api = Build.VERSION_CODES.O)
public void run() {
int time_vibration = 2000;
run_feedback(case_audio,time_vibration, ID);
}
}
public class TimeStamp {
int prevSample1;
int prevSample2;
int prevSample3;
int currSample1;
int currSample2;
int currSample3;
}
public void checkSampleTime(TimeStamp timeStamp) {
if (btn_client_1.isEnabled()) {
int diff_1 = timeStamp.currSample1 - timeStamp.prevSample1;
if (diff_1 != 10) {
tvMessages.append("sampleTime1 Failure\n");
new Thread(new MainActivity.Thread_BioFeedback(5,3)).start();
}
}
if (btn_client_2.isEnabled()) {
int diff_2 = timeStamp.currSample2 - timeStamp.prevSample2;
if (diff_2 != 10) {
tvMessages.append("sampleTime2 Failure\n");
new Thread(new MainActivity.Thread_BioFeedback(6,3)).start();
}
}
if (btn_client_3.isEnabled()) {
int diff_3 = timeStamp.currSample3 - timeStamp.prevSample3;
if (diff_3 != 10) {
tvMessages.append("sampleTime3 Failure\n");
new Thread(new MainActivity.Thread_BioFeedback(7,3)).start();
}
}
}
private class Thread2 implements Runnable {
#Override
public void run() {
TimeStamp timeStamp = new TimeStamp();
while (true) {
try {
byte[] buffX = new byte[BUFFER_LENGTH*2-8];
byte[] buffX_2 = new byte[BUFFER_LENGTH*2-8];
byte[] buffX_3 = new byte[BUFFER_LENGTH*2-8];
if (btn_client_1.isEnabled()) {
int k = inputStream.read(buffX);
byte[] c = new byte[buffX.length + client1.length];
System.arraycopy(buffX, 0, c, 0, buffX.length);
System.arraycopy(client1, 0, c, buffX.length, client1.length);
fou.write(c);
float pitch_1 = from_bytes_to_float(buffX,18);
pitch_buff_1.add(pitch_1);
int [] data = unpack(buffX);
lc_buff_1.add(data[13]);
if (flag_Acq_1 == 1){
// timeStamp.currSample1 = (data[16]<<16) | (data[15] & 0xFFFF);
timeStamp.currSample1 = (data[15]<<16) | (data[14] & 0xFFFF);
flag_Acq_1 = 0;
} else {
timeStamp.prevSample1 = timeStamp.currSample1;
timeStamp.currSample1 = (data[15]<<16) | (data[14] & 0xFFFF);
}
}
if (btn_client_2.isEnabled()) {
int k_2 = inputStream_2.read(buffX_2);
byte[] c_2 = new byte[buffX_2.length + client2.length];
System.arraycopy(buffX_2, 0, c_2, 0, buffX_2.length);
System.arraycopy(client2, 0, c_2, buffX_2.length, client2.length);
fou.write(c_2);
float pitch_2 = from_bytes_to_float(buffX_2,18);
pitch_buff_2.add(pitch_2);
int [] data_2 = unpack(buffX_2);
lc_buff_2.add(data_2[13]);
if (flag_Acq_2 == 1){
timeStamp.currSample2 = (data_2[15]<<16) | (data_2[14] & 0xFFFF);
flag_Acq_2 = 0;
} else {
timeStamp.prevSample2 = timeStamp.currSample2;
timeStamp.currSample2 = (data_2[15]<<16) | (data_2[14] & 0xFFFF);
}
}
if (btn_client_3.isEnabled()) {
int k_3 = inputStream_3.read(buffX_3);
byte[] c_3 = new byte[buffX_3.length + client3.length];
System.arraycopy(buffX_3, 0, c_3, 0, buffX_3.length);
System.arraycopy(client3, 0, c_3, buffX_3.length, client3.length);
fou.write(c_3);
float pitch_3 = from_bytes_to_float(buffX_3,18);
pitch_buff_3.add(pitch_3);
int [] data_3 = unpack(buffX_3);
lc_buff_3.add(data_3[13]);
if (flag_Acq_3 == 1){
timeStamp.currSample3 = (data_3[15]<<16) | (data_3[14] & 0xFFFF);
flag_Acq_3 = 0;
} else {
timeStamp.prevSample3 = timeStamp.currSample3;
timeStamp.currSample3 = (data_3[15]<<16) | (data_3[14] & 0xFFFF);
}
}
if (flag_Acq == 1) {
flag_Acq = 0;
} else {
checkSampleTime(timeStamp);
}
if (message != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (x%plot_freq==0) {
float value = average_list(pitch_buff_1, plot_freq);
float value_2 = average_list(pitch_buff_2, plot_freq);
float value_3 = average_list(pitch_buff_3, plot_freq);
float lc_avg = average_listInt(lc_buff_1, plot_freq);
float lc_avg_2 = average_listInt(lc_buff_2, plot_freq);
float lc_avg_3 = average_listInt(lc_buff_3, plot_freq);
if (y>=4000) {
series.resetData(new DataPoint[] {new DataPoint(x, value)});
series_2.resetData(new DataPoint[] {new DataPoint(x, value_2)});
series_3.resetData(new DataPoint[] {new DataPoint(x, value_3)});
lc.resetData(new DataPoint[] {new DataPoint(x, lc_avg)});
lc2.resetData(new DataPoint[] {new DataPoint(x, lc_avg_2)});
lc3.resetData(new DataPoint[] {new DataPoint(x, lc_avg_3)});
y = 0;
} else {
series.appendData(new DataPoint(x, value),true,500);
series_2.appendData(new DataPoint(x, value_2),true,500);
series_3.appendData(new DataPoint(x, value_3),true,500);
lc.appendData(new DataPoint(x, lc_avg),true,500);
lc2.appendData(new DataPoint(x, lc_avg_2),true,500);
lc3.appendData(new DataPoint(x, lc_avg_3),true,500);
}
pitch_buff_1.clear();
pitch_buff_2.clear();
pitch_buff_3.clear();
lc_buff_1.clear();
lc_buff_2.clear();
lc_buff_3.clear();
Log.v("Plot Update","OK");
}
x += 1;
y += 1;
Log.v("Plot Update",String.valueOf(x));
}
});
} else {
Thread1 = new Thread(new MainActivity.Thread1());
Thread1.start();
return;
}
Thread.sleep(1);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Thread3 implements Runnable {
private String message;
Thread3(String message) {
this.message = message;
}
#Override
public void run() {
if (btn_client_1.isEnabled()) {
output.write(message);
output.flush();
}
if (btn_client_2.isEnabled()) {
output_2.write(message);
output_2.flush();
}
if (btn_client_3.isEnabled()) {
output_3.write(message);
output_3.flush();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
tvMessages.append("server: " + message + "\n");
// etMessage.setText("");
}
});
}
}
}

After I capture an image the labels are not return, Is my code right?

private class InferenceThread extends AsyncTask <Bitmap , Integer , FirebaseModelInputs> {
String labels;
#Override
protected FirebaseModelInputs doInBackground(Bitmap... bitmaps) {
try {
inputOutputOptions =
new FirebaseModelInputOutputOptions.Builder()
.setInputFormat(0, FirebaseModelDataType.FLOAT32, new int[]{1, 1152, 896, 1})
.setOutputFormat(0, FirebaseModelDataType.FLOAT32, new int[]{1, 2})
.build();
} catch (FirebaseMLException e) {
e.printStackTrace();
}
imageBitmap = Bitmap.createScaledBitmap(imageBitmap , 1152 ,896 , true);
int batchNum = 0 ;
float[][][][] input = new float[1][1152][896][1];
for (int x = 0; x < 1152; x++) {
for (int y = 0; y < 896; y++) {
int pixel = imageBitmap.getPixel(x, y);
// Normalize channel values to [-1.0, 1.0]. This requirement varies by
// model. For example, some models might require values to be normalized
// to the range [0.0, 1.0] instead.
input[batchNum][x][y][0] = (Color.red(pixel) - 127) / 128.0f;
// input[batchNum][x][y][1] = (Color.green(pixel) - 127) / 128.0f;
// input[batchNum][x][y][2] = (Color.blue(pixel) - 127) / 128.0f;
}
}
FirebaseModelInputs inputs = null;
try {
inputs = new FirebaseModelInputs.Builder()
.add(input) // add() as many input arrays as your model requires
.build();
} catch (FirebaseMLException e) {
e.printStackTrace();
}
return inputs;
}
#Override
protected void onPostExecute(FirebaseModelInputs inputs) {
super.onPostExecute(inputs);
interpreter.run(inputs, inputOutputOptions).addOnSuccessListener(
new OnSuccessListener<FirebaseModelOutputs>() {
#Override
public void onSuccess(FirebaseModelOutputs result) {
d("Hellow", "Success");
float[][] output = result.getOutput(0);
float[] probabilities = output[0];
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("labels.txt")));
} catch (IOException e) {
e("Label file not read" , "file not buffered" , e);
}
for (int i = 0; i < probabilities.length; i++) {
String label = null;
try {
label = reader.readLine();
d("Labels", label);
} catch (IOException e) {
e("line not read" , "labels not identified" ,e);
}
i("MLKit", String.format("%s: %1.4f", label, probabilities[i]));
labels = label;
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
d("Hellow", "Failure");
}
});
//resulttextbox.setText(labels);
}
}
What I am trying to do here is , getting the model instance and doing and inference on it . The model is located on the firebase custom model. I am doing inference in a Async class . What I knew is that , my code is not running and inference.
What I am trying to achieve in my application is basically a camera application takes a picture and run on the model located remotely on the firebase custom model.
If anybody can help please answer .

How to get value from CandleStick and add to LineChart -> MPANDROIDCHART

I face a problem with getting data from CandleStickChart and adding this into LineChart.
Ok, so look at this method. I got data from CandleStick and configure data to LineChart. Everything work perfectly. I have generated 2 chars like you guys see on Image:
But the problem is when i trying to add dynamicData to chars. My method only add data to CandleStickChart.
Here is method to setData on LineChart, here CandleEntry lastEntry = set1.getEntryForIndex(i); i know what value is on bars.
private void setData() {
int prog = 50;
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(i);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(i, lastOpenCloseMax));
}
XAxis xAxis = lineChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setTextColor(Color.TRANSPARENT);
xAxis.setDrawGridLines(false);
YAxis leftAxis = lineChart.getAxisLeft();
leftAxis.setLabelCount(12, false);
leftAxis.setDrawGridLines(false);
leftAxis.setAxisMaximum(1.6f);
leftAxis.setAxisMinimum(0.4f);
leftAxis.setDrawAxisLine(true);
leftAxis.setTextColor(Color.TRANSPARENT);
YAxis rightAxis = lineChart.getAxisRight();
rightAxis.setEnabled(false);
Collections.sort(entries, new EntryXComparator());
lineDataSet = new LineDataSet(entries, "# of Calls");
lineData = new LineData(lineDataSet);
lineDataSet.setColor(Color.GRAY);
lineDataSet.setDrawCircles(false);
// dataset.setDrawFilled(true);
lineData.setValueTextColor(Color.TRANSPARENT);
lineChart.getLegend().setEnabled(false);
lineChart.getDescription().setEnabled(false);
lineChart.setBackgroundColor(Color.TRANSPARENT);
lineChart.setData(lineData);
lineChart.animateX(4000);
}
Here i addLineEntry, but this not work and i dont know why, do you guys have any idea?
private void addLineEntry() {
lineData = lineChart.getData();
if (lineDataSet == null) {
lineDataSet = createLineSet();
lineData.addDataSet(lineDataSet);
}
int prog = 1;
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(yVals1.size() - 1);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(lineDataSet.getXMax() +1, lastOpenCloseMax));
}
lineDataSet.notifyDataSetChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
mChart.moveViewTo(mChart.getXChartMax(), 2f, YAxis.AxisDependency.RIGHT);
}
And the last is similar method from CandleStickChart to addEntry.
private void addEntry(boolean start) {
data = mChart.getData();
if (set1 == null) {
set1 = createSet();
data.addDataSet(set1);
}
float highmax = 1.0700f;
float highlow = 1.1700f;
float lowmax = 0.5700f;
float lowlow = 0.63000f;
int prog = 1;
int xMax = (int) set1.getXMax();
CandleEntry lastEntry = set1.getEntryForIndex(yVals1.size() - 1);
for (int i = 0; i < prog; i++) {
float open = highlow + new Random().nextFloat() * (highmax - highlow);
float close = lowlow + new Random().nextFloat() * (lowmax - lowlow);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
float currentOpenCloseMax = Math.max(open, close);
float currentOpenCloseMin = Math.min(open, close);
float high = open + 0.3f;
float low = close - 0.3f;
if (currentOpenCloseMax < lastOpenCloseMax) {
yVals1.add(new CandleEntry(xMax + 1, high, low, currentOpenCloseMax, currentOpenCloseMin));
} else {
yVals1.add(new CandleEntry(xMax + 1, high, low, currentOpenCloseMin, currentOpenCloseMax));
}
mChart.notifyDataSetChanged();
mChart.invalidate();
mChart.moveViewTo(mChart.getXChartMax(), 2f, YAxis.AxisDependency.RIGHT);
}
}
And here is method to remove Entry from CandleStickChart and LineChart, and this work good.
private void removeLastEntry() {
CandleData data = mChart.getData();
if (data != null) {
ICandleDataSet set = data.getDataSetByIndex(0);
if (set != null) {
set.removeFirst();
data.notifyDataChanged();
mChart.notifyDataSetChanged();
mChart.invalidate();
}
}
LineData lineData = lineChart.getData();
if (lineData != null) {
ILineDataSet set = lineData.getDataSetByIndex(0);
if (set != null) {
set.removeFirst();
data.notifyDataChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
}
}
Do you guys have any idea whats wrong?
I started a bounty:
Here isfull class:
public class MainGameFragment extends Fragment {
#BindView(R.id.spinner_money)
Spinner spinnerData;
#BindView(R.id.text_profit_ill)
TextView text_profit;
#BindView(R.id.button_cash)
Button btnCashCurrency;
#BindView(R.id.restart_game)
Button restartGame;
#BindView(R.id.butonCurrency)
Button buttonCurrency;
#BindView(R.id.chart)
CandleStickChart mChart;
#BindView(R.id.progress_bar)
ProgressBar progress;
#BindView(R.id.btn_buy)
Button btnBuy;
#BindView(R.id.btn_sell)
Button btnSell;
#BindView(R.id.drawer_settings)
ImageButton openDrawerSettings;
#BindView(R.id.chartLine)
LineChart lineChart;
public static ArrayList<String> HISTORYTRANSACTION = new ArrayList<>();
public static ArrayList<String> LEADERBOARDUSER = new ArrayList<>();
public static String userNameAndScore;
private Handler handler;
private Handler handlerLast;
private String buttonPosition;
int pos = 0;
LostDialogFragment lostFragment = LostDialogFragment.newInstance(1);
WinDialogFragment winFragment = WinDialogFragment.newInstance(1);
SettingsFragment settingsFragment = SettingsFragment.newInstance(1);
String DIALOG_WIN = "WinDialogFragment";
String DIALOG_LOST = "LostDialogFragment";
String DIALOG_SETTINGS = "settingsFragment";
private CandleData data;
private LineData lineData;
private LineDataSet lineDataSet;
private CandleDataSet set1;
private Drawer result;
public static StorageReference storageReference;
private Runnable r;
private Runnable rLast;
ArrayList<CandleEntry> yVals1 = new ArrayList<>();
ArrayList<Entry> entries = new ArrayList<>();
public MainGameFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
buttonPosition = getArguments().getString("button_position", "value");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_game, container, false);
ButterKnife.bind(this, view);
setText();
configureSpinnerDataAndLogic();
configureChart();
configureColorProgresBar();
openDrawer();
configureDrawer();
welcomeMessage();
configureHandler(5000);
storageReference = FirebaseStorage.getInstance().getReference();
setData();
return view;
}
private void setData() {
int prog = 50;
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(i);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(i, lastOpenCloseMax));
}
XAxis xAxis = lineChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setTextColor(Color.TRANSPARENT);
xAxis.setDrawGridLines(false);
YAxis leftAxis = lineChart.getAxisLeft();
leftAxis.setLabelCount(12, false);
leftAxis.setDrawGridLines(false);
leftAxis.setAxisMaximum(1.6f);
leftAxis.setAxisMinimum(0.4f);
leftAxis.setDrawAxisLine(true);
leftAxis.setTextColor(Color.TRANSPARENT);
YAxis rightAxis = lineChart.getAxisRight();
rightAxis.setEnabled(false);
Collections.sort(entries, new EntryXComparator());
lineDataSet = new LineDataSet(entries, "# of Calls");
lineData = new LineData(lineDataSet);
lineDataSet.setColor(Color.GRAY);
lineDataSet.setDrawCircles(false);
// dataset.setDrawFilled(true);
lineData.setValueTextColor(Color.TRANSPARENT);
lineChart.getLegend().setEnabled(false);
lineChart.getDescription().setEnabled(false);
lineChart.setBackgroundColor(Color.TRANSPARENT);
lineChart.setData(lineData);
lineChart.animateX(4000);
}
private void welcomeMessage() {
Toast.makeText(getContext(), "Welcome " + MainActivity.getUsername(getContext()).trim() + "!"
+ " Getting data from last hour..",
Toast.LENGTH_LONG).show();
}
private void configureDrawer() {
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(getActivity())
.withProfileImagesClickable(false)
.withHeaderBackground(R.drawable.logo_white)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
result = new DrawerBuilder()
.withSliderBackgroundColor(Color.GRAY)
.withAccountHeader(headerResult)
.withActivity(getActivity())
.withDisplayBelowStatusBar(false)
.withDrawerGravity(Gravity.LEFT)
.withHeaderPadding(true)
.addDrawerItems(
new SectionDrawerItem().withName("Options"),
new PrimaryDrawerItem().withName("Trading History").withIcon(R.drawable.trading_history).withIdentifier(2),
new PrimaryDrawerItem().withName("Leader Board").withIcon(R.drawable.leade_board).withIdentifier(3),
new PrimaryDrawerItem().withName("Special offer").withIcon(R.drawable.special_icon).withIdentifier(4),
new PrimaryDrawerItem().withName("Video tutorials").withIcon(R.drawable.video_tutorials).withIdentifier(5),
new PrimaryDrawerItem().withName("FAQ").withIcon(R.drawable.faq_icon).withIdentifier(6),
new PrimaryDrawerItem().withName("CONTACT").withIcon(R.drawable.contact_icon).withIdentifier(7)
)
.buildForFragment();
result.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.addToBackStack(null);
SettingsFragment.POSITION = position;
result.closeDrawer();
if (settingsFragment != null) {
settingsFragment.show(ft, DIALOG_SETTINGS);
}
return true;
}
});
result.getDrawerLayout().setFitsSystemWindows(false);
result.getSlider().setFitsSystemWindows(false);
}
private CandleDataSet createSet() {
set1 = new CandleDataSet(null, "DataSet 1");
set1.setColor(Color.rgb(240, 99, 99));
set1.setHighLightColor(Color.rgb(190, 190, 190));
set1.setAxisDependency(YAxis.AxisDependency.LEFT);
set1.setValueTextSize(10f);
return set1;
}
private LineDataSet createLineSet() {
lineDataSet = new LineDataSet(null, "DataSet 1");
lineDataSet.setColor(Color.rgb(240, 99, 99));
lineDataSet.setHighLightColor(Color.rgb(190, 190, 190));
lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
lineDataSet.setValueTextSize(10f);
return lineDataSet;
}
public void openDrawer() {
openDrawerSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.openDrawer();
}
});
}
private void addLineEntry() {
lineData = lineChart.getData();
if (lineDataSet == null) {
lineDataSet = createLineSet();
lineData.addDataSet(lineDataSet);
}
int prog = 1;
int xMax = (int) set1.getXMax();
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(xMax -1);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(lineData.getDataSetCount() +1, lastOpenCloseMax));
}
lineDataSet.notifyDataSetChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
lineChart.moveViewTo(lineChart.getXChartMax(), 2f, YAxis.AxisDependency.RIGHT);
}
private void addEntry(boolean start) {
data = mChart.getData();
if (set1 == null) {
set1 = createSet();
data.addDataSet(set1);
}
float highmax = 1.0700f;
float highlow = 1.1700f;
float lowmax = 0.5700f;
float lowlow = 0.63000f;
int prog = 1;
int xMax = (int) set1.getXMax();
CandleEntry lastEntry = set1.getEntryForIndex(yVals1.size() - 1);
for (int i = 0; i < prog; i++) {
float open = highlow + new Random().nextFloat() * (highmax - highlow);
float close = lowlow + new Random().nextFloat() * (lowmax - lowlow);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
float currentOpenCloseMax = Math.max(open, close);
float currentOpenCloseMin = Math.min(open, close);
float high = open + 0.3f;
float low = close - 0.3f;
if (currentOpenCloseMax < lastOpenCloseMax) {
yVals1.add(new CandleEntry(xMax + 1, high, low, currentOpenCloseMax, currentOpenCloseMin));
} else {
yVals1.add(new CandleEntry(xMax + 1, high, low, currentOpenCloseMin, currentOpenCloseMax));
}
mChart.notifyDataSetChanged();
mChart.invalidate();
mChart.moveViewTo(mChart.getXChartMax(), 2f, YAxis.AxisDependency.RIGHT);
}
}
private void removeLastEntry() {
CandleData data = mChart.getData();
if (data != null) {
ICandleDataSet set = data.getDataSetByIndex(0);
if (set != null) {
set.removeFirst();
data.notifyDataChanged();
mChart.notifyDataSetChanged();
mChart.invalidate();
}
}
LineData lineData = lineChart.getData();
if (lineData != null) {
ILineDataSet set = lineData.getDataSetByIndex(0);
if (set != null) {
set.removeFirst();
data.notifyDataChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
}
}
}
public String getUserInfoAndSave() {
userNameAndScore = MainActivity.getUsername(getContext()).trim() + ": "
+ btnCashCurrency.getText().toString().trim();
return userNameAndScore;
}
private void configureHandlerWithoutRemoveLastEntry(final int time) {
handlerLast = new Handler();
rLast = new Runnable() {
public void run() {
// removeLastEntry();
addEntry(true);
handler.postDelayed(this, time);
}
};
handlerLast.postDelayed(rLast, time);
}
private void configureHandler(final int time) {
handler = new Handler();
r = new Runnable() {
public void run() {
removeLastEntry();
addEntry(true);
addLineEntry();
handler.postDelayed(this, time);
}
};
handler.postDelayed(r, time);
}
public void stopLast() {
handlerLast.removeCallbacks(rLast);
}
public void stop() {
handler.removeCallbacks(r);
}
private void configureChart() {
mChart.getDescription().setEnabled(false);
mChart.getLegend().setTextColor(Color.WHITE);
mChart.setMaxVisibleValueCount(50);
XAxis xAxis = mChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setTextColor(Color.WHITE);
xAxis.setDrawGridLines(false);
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setLabelCount(12, false);
leftAxis.setDrawGridLines(false);
leftAxis.setDrawAxisLine(true);
leftAxis.setTextColor(Color.WHITE);
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setEnabled(false);
float highmax = 1.0700f;
float highlow = 1.1700f;
float lowmax = 0.5700f;
float lowlow = 0.63000f;
int prog = 50;
float last = Float.NEGATIVE_INFINITY;
String date = String.valueOf(android.text.format.DateFormat.format("yyyy-MM-dd", new java.util.Date()));
for (int i = 0; i < prog; i++) {
float open = highlow + new Random().nextFloat() * (highmax - highlow);
float close = lowlow + new Random().nextFloat() * (lowmax - lowlow);
float max = Math.max(open, close);
if (last < max) {
float tmp = open;
open = close;
close = tmp;
}
last = max;
float high = open + 0.3f;
float low = close - 0.3f;
yVals1.add(new CandleEntry(i, high, low, open, close));
}
set1 = new CandleDataSet(yVals1, date);
data = new CandleData(set1);
mChart.setData(data);
set1.setAxisDependency(YAxis.AxisDependency.LEFT);
set1.setColor(Color.rgb(80, 80, 80));
set1.setIncreasingColor(Color.GREEN);
set1.setIncreasingPaintStyle(Paint.Style.FILL);
set1.setDecreasingColor(Color.RED);
set1.setDecreasingPaintStyle(Paint.Style.FILL);
set1.setNeutralColor(Color.BLUE);
set1.setBarSpace(0.2f);
set1.setValueTextColor(Color.TRANSPARENT);
mChart.notifyDataSetChanged();
mChart.animateX(4000);
}
private void setText() {
buttonCurrency.setText("Assets: \n" + buttonPosition);
}
private void configureColorProgresBar() {
progress.getIndeterminateDrawable().setColorFilter(
getResources().getColor(R.color.white),
android.graphics.PorterDuff.Mode.SRC_IN);
}
#OnClick(R.id.invest_text)
public void invest() {
float highmax = 1.0700f;
float highlow = 1.1700f;
float lowmax = 0.5700f;
float lowlow = 0.63000f;
float open = highlow + new Random().nextFloat() * (highmax - highlow);
float close = lowlow + new Random().nextFloat() * (lowmax - lowlow);
float high = open + 0.3f;
float low = close - 0.3f;
if (pos == 0) {
yVals1.add(new CandleEntry(50, high, low, open, close));
pos++;
} else if (pos == 1) {
yVals1.add(new CandleEntry(51, high, low, open, close));
pos++;
} else if (pos == 2) {
yVals1.add(new CandleEntry(52, high, low, open, close));
pos++;
} else if (pos == 3) {
yVals1.add(new CandleEntry(53, high, low, open, close));
pos++;
} else if (pos == 4) {
yVals1.add(new CandleEntry(54, high, low, open, close));
pos++;
}
mChart.invalidate();
}
#OnClick({R.id.btn_buy, R.id.btn_sell})
public void onGameButtonsClicked() {
final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.addToBackStack(null);
String cashText = btnCashCurrency.getText().toString();
final int[] cash = {Integer.valueOf(cashText)};
if (cash[0] <= 0) {
restartGame.setVisibility(View.VISIBLE);
Toast.makeText(getContext(), "Your cash is on -, u cant play. Please restart game.", Toast.LENGTH_SHORT).show();
} else if (Integer.valueOf(spinnerData.getSelectedItem().toString()) >= Integer.valueOf(btnCashCurrency.getText().toString())) {
Toast.makeText(getContext(), "You not have available cash, change the money in Invest Section.", Toast.LENGTH_SHORT).show();
} else {
int min = 0;
int max = 2;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
String text = spinnerData.getSelectedItem().toString();
final int temp = Integer.parseInt(text);
final int temp2 = temp * 2;
disableAndEnableButtons(false);
if (i1 == 0 || i1 == 1) {
progress.setVisibility(View.VISIBLE);
stop();
configureHandler(900);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
lostFragment.show(ft, DIALOG_LOST);
cash[0] -= temp2;
btnCashCurrency.setText(cash[0] + "");
progress.setVisibility(View.GONE);
disableAndEnableButtons(true);
String score = "LOSE " + MainActivity.getUsername(getContext()).trim() + ": "
+ btnCashCurrency.getText().toString().trim() + " -" + temp2;
HISTORYTRANSACTION.add(score);
getUserInfoAndSave();
stop();
configureHandler(5000);
}
}, 5000);
} else {
progress.setVisibility(View.VISIBLE);
stop();
configureHandler(900);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
winFragment.show(ft, DIALOG_WIN);
cash[0] += temp2;
btnCashCurrency.setText(cash[0] + "");
progress.setVisibility(View.GONE);
disableAndEnableButtons(true);
String score = "WIN " + MainActivity.getUsername(getContext()).trim()
+ ": " + btnCashCurrency.getText().toString().trim() + " +" + temp2;
HISTORYTRANSACTION.add(score);
getUserInfoAndSave();
stop();
configureHandler(5000);
}
}, 5000);
}
}
}
private void disableAndEnableButtons(boolean on) {
btnBuy.setEnabled(on);
btnSell.setEnabled(on);
}
#OnClick(R.id.restart_game)
public void restartGame() {
Intent intent = new Intent(getContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
MainGameFragment.LEADERBOARDUSER.add(MainGameFragment.userNameAndScore);
((CurrencySelectActivity) getContext()).hideGameFragment();
((CurrencySelectActivity) getContext()).closeCurrencyActivity();
SharedPreferences prefs = getContext().getSharedPreferences("app.forex", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
Set<String> set = new HashSet<>();
set.add(String.valueOf(MainGameFragment.LEADERBOARDUSER));
edit.putStringSet("user_and_score", set);
HISTORYTRANSACTION.clear();
edit.apply();
}
private void configureSpinnerDataAndLogic() {
String[] arraySpinner = new String[]{
"50", "100", "150", "200", "250", "300", "400", "500"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
android.R.layout.simple_list_item_1, arraySpinner);
spinnerData.setAdapter(adapter);
spinnerData.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
String text = spinnerData.getSelectedItem().toString();
int temp = Integer.parseInt(text);
text_profit.setText((temp * 2) + " $ " + "100%");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
AAnd here is xml files
<com.github.mikephil.charting.charts.CandleStickChart
android:id="#+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/butonCurrency"
android:layout_margin="30dp" />
<com.github.mikephil.charting.charts.LineChart
android:id="#+id/chartLine"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/butonCurrency"
android:layout_margin="30dp" />
And thiswork like:
Highly help needed
Instead of adding the new entry to your entries array.. you could try using the method lineData.addEntry().
Something like this :
private void addEntry() {
LineData data = mChart.getData();
ILineDataSet set = data.getDataSetByIndex(0);
if (set == null) {
set = createSet();
data.addDataSet(set);
}
data.addEntry(new Entry(data.getDataSetByIndex(dataSetIndex).getEntryCount(), yValue), dataSetIndex);
data.notifyDataChanged();
mChart.notifyDataSetChanged();
}
your "dataSetIndex" will always be 0 if you only have a single dataset in your linechart.
For more information, you can check this class
Problem is here, after i change, everything work good
private void addLineEntry() {
lineData = lineChart.getData();
if (lineDataSet == null) {
lineDataSet = createLineSet();
lineData.addDataSet(lineDataSet);
}
int prog = 1;
int xMax = (int) lineDataSet.getXMax();
for (int i = 0; i < prog; i++) {
CandleEntry lastEntry = set1.getEntryForIndex(yVals1.size() - 1);
float lastOpenCloseMax = Math.max(lastEntry.getOpen(), lastEntry.getClose());
entries.add(new Entry(xMax + 1, lastOpenCloseMax));
}
lineDataSet.notifyDataSetChanged();
lineChart.notifyDataSetChanged();
lineChart.invalidate();
lineChart.moveViewTo(xMax, 2f, YAxis.AxisDependency.RIGHT);
}

Practicing IO with a highscore example

This is what I came up with after tinkering for a couple hours. Sadly it leaves me with an empty highscore scene.
public HighScoresPresenter(HighScoresModel model, HighScoresView view) {
this.model = model;
this.view = view;
addEventHandlers();
updateView();
}
private void updateView() {
Label[] namen = new Label[9];
Label[] scores = new Label[9];
String[] strings;
try {
Scanner scanner = new Scanner(new File(HighScoresModel.getBESTANDSNAAM()));
scanner.useDelimiter(System.lineSeparator());
for (int i = 0;i<9;i++){
strings = scanner.nextLine().split(",");
namen[i] = new Label(strings[1]);
scores[i] = new Label(strings[0]);
}
view.setNamen(namen);
view.setScores(scores);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
This is what the .txt file looks like.
2500,Peter
2400,Elisabeth
2200,Josje
1900,Sebastiaan
1500,Petra
1500,Jozef
1500,Dave
1400,Karen
1200,Kristel
1000,Jules
Highscores are separated by \n. Score and name are separated by ",".
public class HighScoresView extends GridPane {
private Label naamKop;
private Label scoreKop;
private Label[] namen;
private Label[] scores;
public HighScoresView() {
initialiseNodes();
layoutNodes();
}
private void initialiseNodes() {
naamKop = new Label("Naam");
scoreKop = new Label("Score");
namen = new Label[HighScores.AANTAL_HIGHSCORES];
scores = new Label[HighScores.AANTAL_HIGHSCORES];
for (int i = 0; i < HighScores.AANTAL_HIGHSCORES; i++) {
namen[i] = new Label("");
scores[i] = new Label("");
}
}
private void layoutNodes() {
setGridLinesVisible(true);
naamKop.setPadding(new Insets(2, 10, 8, 10));
naamKop.setPrefWidth(120);
scoreKop.setPadding(new Insets(2, 10, 8, 10));
scoreKop.setPrefWidth(120);
add(naamKop, 0, 0);
add(scoreKop, 1, 0);
for (int i = 0; i < HighScores.AANTAL_HIGHSCORES; i++) {
add(namen[i], 0, (i + 1));
add(scores[i], 1, (i + 1));
namen[i].setPadding(new Insets(5, 0, 5, 10));
scores[i].setPadding(new Insets(5, 0, 5, 10));
}
}
Label[] getNaamLabels() {
return namen;
}
Label[] getScoreLabels() {
return scores;
}
public void setNamen(Label[] namen) {
this.namen = namen;
}
public void setScores(Label[] scores) {
this.scores = scores;
}
}
Got updateView() working by changing the following things. (presenter class)
private void updateView() {
String[] namen = new String[10];
String[] scores = new String[10];
String[] strings;
try {
Scanner scanner = new Scanner(new File(HighScoresModel.getBESTANDSNAAM()));
scanner.useDelimiter(System.lineSeparator());
for (int i = 0;i<10;i++){
strings = scanner.nextLine().split(",");
namen[i] = strings[1];
scores[i] = strings[0];
}
view.setNaamText(namen);
view.setScoresText(scores);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Added different setters, although the assignment said this class was complete. (view class)
public void setNaamText(String[] namen) {
for (int i=0;i<namen.length;i++) {
this.namen[i].setText(namen[i]);
}
}
public void setScoresText(String[] scores) {
for (int i=0;i<scores.length;i++) {
this.scores[i].setText(scores[i]);
}
}

Why is my simple java2d Space Invaders game lagging?

I'm currently making a space invaders-esque game for my software engineering course. I've already got everything working that satisfies the requirements, so this isn't a 'solve my homework' kind of question. My problem is that the game will lag (at what seems like random times & intervals) to the point where it becomes too frustrating to play. Some things I think might be causing this - though I'm not positive - are as follows:
Problem with timer event every 10 ms (I doubt this because of the very limited resources required for this game).
Problem with collision detection (checking for collision with every visible enemy every 10 ms seems like it would take up a large chunk of resources)
Problem with repainting? This seems unlikely to me however...
#SuppressWarnings("serial")
public class SIpanel extends JPanel {
private SIpanel panel;
private Timer timer;
private int score, invaderPace, pulseRate, mysteryCount, distanceToEdge;
private ArrayList<SIthing> cast;
private ArrayList<SIinvader> invaders, dead;
private ArrayList<SImissile> missileBase, missileInvader;
private SIinvader[] bottomRow;
private SIbase base;
private Dimension panelDimension;
private SImystery mysteryShip;
private boolean gameOver, left, right, mysteryDirection, space, waveDirection;
private boolean runningTimer;
private Music sound;
private void pulse() {
pace();
processInputs();
if (gameOver) gameOver();
repaint();
}
private void pace() {
// IF invaders still live
if (!invaders.isEmpty()) {
invaderPace++;
// Switch back manager
if (distanceToEdge <= 10) {
switchBack();
pulseRate = (pulseRate >= 16) ? (int) (pulseRate*(0.8)) : pulseRate;
waveDirection = !waveDirection;
distanceToEdge = calculateDistanceToEdge();
}
// Move invaders left/right
else if (invaderPace >= pulseRate) {
invaderPace = 0;
distanceToEdge = calculateDistanceToEdge();
moveAI();
invadersFire();
if (!dead.isEmpty()) removeDead();
if (mysteryCount < 1) tryInitMysteryShip();
}
// All invaders are kill, create new wave
} else if (missileBase.isEmpty() && missileInvader.isEmpty() && !cast.contains(mysteryShip)) {
// System.out.println("New Wave!");
newWave();
}
// Every pace
if (!missileBase.isEmpty()) moveMissileBase();
// Every two paces
if (invaderPace % 2 == 0) {
if (!missileInvader.isEmpty()) moveMissileInvader();
if (mysteryCount > 0) moveMysteryShip();
}
}
private void processInputs() {
if (left) move(left);
if (right) move(!right);
if (space) fireMissile(base, true);
}
protected void fireMissile(SIship ship, boolean isBase) {
if(isBase && missileBase.isEmpty()) {
base.playSound();
SImissile m = new SImissile(ship.getX()+(ship.getWidth()/2), ship.getY()-(ship.getHeight()/4));
missileBase.add(m);
cast.add(m);
} else if (!isBase && missileInvader.size()<3) {
base.playSound();
SImissile m = new SImissile(ship.getX()+(ship.getWidth()/2), ship.getY()+(ship.getHeight()/4));
missileInvader.add(m);
cast.add(m);
}
}
private void newWave() {
pulseRate = 50;
int defaultY=60, defaultX=120, defaultWidth=30, defaultHeight=24;
for(int i=0; i<5; i++) {
for(int j=0; j<10; j++) {
if (i<1) invaders.add(new SItop((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
else if (i<3) invaders.add(new SImiddle((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
else if (i<5) invaders.add(new SIbottom((j*defaultWidth)+defaultX, (i*defaultHeight)+defaultY, defaultWidth, defaultHeight));
}
}
for (SIinvader s: invaders) {
cast.add(s);
}
if (!cast.contains(base)) {
cast.add(base);
}
bottomRow = getBottomRow();
}
private void tryInitMysteryShip() {
Random rand = new Random();
int x=rand.nextInt(1000);
if (x<=3) {
mysteryCount = 1;
if (rand.nextBoolean()) {
mysteryDirection = true;
}
if (mysteryDirection) {
mysteryShip = new SImystery(0, 60, 36, 18);
} else {
mysteryShip = new SImystery(480, 60, 36, 18);
}
cast.add(mysteryShip);
}
}
private void moveMysteryShip() {
int distance = 0;
if (mysteryDirection) {
mysteryShip.moveRight(5);
distance = getWidth() - mysteryShip.getX();
} else {
mysteryShip.moveLeft(5);
distance = 30+mysteryShip.getX()-mysteryShip.getWidth();
}
if (distance <= 5) {
dead.add(mysteryShip);
mysteryShip = null;
mysteryCount = 0;
}
}
private void removeDead() {
#SuppressWarnings("unchecked")
ArrayList<SIinvader> temp = (ArrayList<SIinvader>) dead.clone();
dead.clear();
for (SIinvader s : temp) {
invaders.remove(s);
cast.remove(s);
}
bottomRow = getBottomRow();
}
private void invadersFire() {
int[] p = new int[bottomRow.length];
for (int i=0; i<p.length; i++) {
for (int j=0; j<p.length; j++) {
p[j] = j;
}
Random rand = new Random();
int a=rand.nextInt(101);
if (a>=20) {
int b=rand.nextInt(p.length);
fireMissile(bottomRow[b], false);
}
}
}
private int calculateDistanceToEdge() {
int distance = 0;
SIinvader[] outliers = getOutliers();
if (waveDirection) {
distance = getWidth() - outliers[0].getX()-outliers[0].getWidth();
} else {
distance = outliers[1].getX();
}
return distance;
}
private SIinvader[] getOutliers() {
SIinvader leftMost = invaders.get(0), rightMost = invaders.get(0);
for (SIinvader s : invaders) {
if (s.getX() < leftMost.getX()) {
leftMost = s;
}
if (s.getX() > rightMost.getX()) {
rightMost = s;
}
}
return new SIinvader[] { rightMost, leftMost };
}
private SIinvader[] getBottomRow() {
SIinvader[] x = new SIinvader[(invaders.size()>10)?10:invaders.size()];
for (int i=0; i<x.length; i++) {
x[i] = invaders.get(i);
for (SIinvader s:invaders) {
if (s.getX() == x[i].getX()) {
if (s.getY() > x[i].getY()) {
x[i] = s;
}
}
}
}
return x;
}
private void move(boolean b) {
int defaultX = 5;
if (b) base.moveLeft(defaultX);
else base.moveRight(defaultX);
}
private void moveAI() {
for(SIinvader s : invaders) {
s.changeImage();
int defaultX = 5;
if (waveDirection) s.moveRight(defaultX);
else s.moveLeft(defaultX);
}
}
private void moveMissileBase() {
if (invaders.isEmpty()) return;
int movement = -5, bound = 0;
SImissile missile = missileBase.get(0);
missile.moveDown(movement);
SIinvader lowestInvader = getLowestInvader();
if (missile.getY() < (lowestInvader.getY() + lowestInvader.getHeight())) {
for (SIinvader s:bottomRow) {
if (checkCollision(missile, s)) {
s.setHit();
dead.add(s);
cast.remove(missile);
missileBase.clear();
score += s.value;
return;
}
}
if (mysteryCount > 0) {
if (checkCollision(missile, mysteryShip)) {
mysteryShip.setHit();
dead.add(mysteryShip);
cast.remove(missile);
missileBase.clear();
score += mysteryShip.value;
return;
}
}
if (missile.getY() < bound) {
missileBase.remove(missile);
cast.remove(missile);
}
}
}
private SIinvader getLowestInvader() {
SIinvader lowest = bottomRow[0];
for (SIinvader invader : bottomRow) {
if (invader.getY() > lowest.getY()) {
lowest = invader;
}
}
return lowest;
}
private void moveMissileInvader() {
int movement = 5, bound = (int) panelDimension.getHeight();
for (SImissile missile : missileInvader) {
missile.moveDown(movement);
if(missile.getY() >= base.getY()) {
if (checkCollision(missile, base)) {
base.setHit();
gameOver = true;;
missileInvader.remove(missile);
cast.remove(missile);
return;
} else if (missile.getY() >= bound-25) {
missileInvader.remove(missile);
cast.remove(missile);
return;
}
}
}
}
private boolean checkCollision(SIthing missile, SIthing ship) {
Rectangle2D rect1 = new Rectangle2D.Double(
missile.getX(),
missile.getY(),
missile.getWidth(),
missile.getHeight()
);
Rectangle2D rect2 = new Rectangle2D.Double(
ship.getX(),
ship.getY(),
ship.getWidth(),
ship.getHeight()
);
return rect1.intersects(rect2);
}
private void switchBack() {
int defaultY = 12;
for (SIinvader s : invaders) {
if (s.getY() > getHeight()) {
gameOver = true;
return;
}
s.moveDown(defaultY);
}
}
private void gameOver() {
pause(true);
SI.setGameOverLabelVisibile(true);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.GREEN);
Font font = new Font("Arial", 0, 20);
setFont(font);
String score = "Score: "+this.score;
Rectangle2D rect = font.getStringBounds(score, g2.getFontRenderContext());
int screenWidth = 0;
try { screenWidth = (int) panelDimension.getWidth(); }
catch (NullPointerException e) {}
g2.setColor(Color.GREEN);
g2.drawString(score, (int) (screenWidth - (10 + rect.getWidth())), 20);
for(SIthing a:cast) {
a.paint(g);
}
}
public SIpanel() {
super();
setBackground(Color.BLACK);
cast = new ArrayList<SIthing>();
missileBase = new ArrayList<SImissile>();
score = invaderPace = mysteryCount = pulseRate = 0;
sound = new Music("AmbientMusic.wav");
panel = this;
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : left = true; break;
case KeyEvent.VK_RIGHT : right = true; break;
case KeyEvent.VK_SPACE : space = true; break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : left = false; break;
case KeyEvent.VK_RIGHT : right = false; break;
case KeyEvent.VK_SPACE : space = false; break;
}
}
});
setFocusable(true);
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pulse();
}
});
}
public void reset() {
SI.setGameOverLabelVisibile(false);
score = invaderPace = mysteryCount = 0;
pulseRate = 50;
cast = new ArrayList<SIthing>();
invaders = new ArrayList<SIinvader>();
dead = new ArrayList<SIinvader>();
missileBase = new ArrayList<SImissile>();
missileInvader = new ArrayList<SImissile>();
base = new SIbase(230, 370, 26, 20);
waveDirection = true;
gameOver = false;
sound.stop();
sound.loop();
panelDimension = SI.getFrameDimensions();
bottomRow = getBottomRow();
newWave();
timer.start();
runningTimer=true;
}
public SIpanel getPanel() {
return this.panel;
}
public void pause(boolean paused) {
if (paused) timer.stop();
else timer.start();
}
}
I believe that collision detection may be the reason for lagging and you should simply investigate it by trying to increase and decrease count of enemies or missiles drastically to see if that makes a difference.
Consider garbage collector your enemy. In your checkCollision method you are instantiating two (very simple) objects. It may not seem like a lot, but consider that your might be creating them for each collision check, and that at 60fps it adds up until it may reach critical mass when GC says "stop the world" and you see noticeable lag.
If that is the case, possible solution to that would be to not instantiate any objects in a method called so frequently. You may create Rectangle2D once, and then update its position, instead of creating a new one each time, so you will avoid unnecessary memory allocation.

Categories