Okay here's the thing:
I have an assignment in Java class that's due in 1.5 hours and figured that this would be the best place to ask since you guys are (hopefully) good at this kind of stuff.
Here's the code:
/**
* Exercise 3.
*
* Complete the setBalances method below to set all accounts in an array to the specified value.
*
* The test methods should pass.
*
*/
public class AccountMethods {
public static void main(String[] args) {
Account[] accounts = {new Account(100, "joe"),
new Account(200, "jane"),
new Account(300, "jerry")};
testSetBalances(accounts, 50);
testBalanceNonNegative();
}
public static void setBalances(Account[] accounts, double value) {
double balance = 0;
for (int i = 0; i < accounts.length; i++) {
balance += accounts.getBalance();
}
}
public static boolean testSetBalances(Account[] accounts, double value) {
setBalances(accounts, value);
for (int i = 0; i < accounts.length; i++) {
if (accounts.getBalance() != value) {
System.out.println("testSetBalances fails on element " + i);
return false;
}
}
System.out.println("testSetBalances passes.");
return true;
}
public static boolean testBalanceNonNegative() {
Account a = new Account(100, "jim");
a.setBalance(-100);
if (a.getBalance() < 0) {
System.out.println("testBalanceNonNegtaive fails");
return false;
} else {
System.out.println("testBalanceNonNegative passes.");
return true;
}
}
}
The bold part is what I'm suppose to be working with, but I can't get it to pass in the testSetBalances method. I don't know if I'm explaining this right, but when I'm compiling the code, it's suppose to say:
testSetBalances passes
But instead, it's saying: testSetBalances fails on element 0
Don't worry about the other parts of the code because the assignment for that is done already.
Hello everyone,
I have a quick question.
Can someone help me with an algorithm that will:
1. Sort incoming data from Arduino transfered via Bluetooth to the Android App.
2. Sort for example, if i have 1000 data but i only want the important ones that I use to compare with my file.
Thank you guys in advance,
Cookie
cookiey89 said:
Hello everyone,
I have a quick question.
Can someone help me with an algorithm that will:
1. Sort incoming data from Arduino transfered via Bluetooth to the Android App.
2. Sort for example, if i have 1000 data but i only want the important ones that I use to compare with my file.
Thank you guys in advance,
Cookie
Click to expand...
Click to collapse
You'll need a script for that, so keep asking for help because I am unable to
Envoyé de mon SM-G928F en utilisant Tapatalk
You're probably not looking for a specific algorithm, but rather for some technical guidance? How far along are you? Did you get the Bluetooth connection between the two to work? Are you building your own app?
cookiey89 said:
Hello everyone,
I have a quick question.
Can someone help me with an algorithm that will:
1. Sort incoming data from Arduino transfered via Bluetooth to the Android App.
2. Sort for example, if i have 1000 data but i only want the important ones that I use to compare with my file.
Thank you guys in advance,
Cookie
Click to expand...
Click to collapse
Assuming your data is simply some numbers, you can put them in ArrayList and then sort them using Collections.sort() function. For example if you want to get 3 greatest numbers , you can do something like that:
Code:
List<Integer> data = new ArrayList<>();
data.add(5);
data.add(10);
data.add(3);
data.add(20);
data.add(1);
data.add(6);
Collections.sort(data, Comparator.reverseOrder());
List<Integer> topNumbers = data.subList(0, 3);
System.out.println("Top 3 numbers: " + topNumbers);
If you need something more complex, please provide some more information about your data and what you mean by "important"
Hi Everyone,
thank you for the fast responses.
This is my initial plan:
I want to gather data from Arduino via bluetooth to the android app.
From there, I want to "sort" the data in such a way to minimize and specify the data I want to compare to a library.
The data will be analog values from various sensors on the Arduino.
Thanks
Cookie
cookiey89 said:
Hello everyone,
I have a quick question.
Can someone help me with an algorithm that will:
1. Sort incoming data from Arduino transfered via Bluetooth to the Android App.
2. Sort for example, if i have 1000 data but i only want the important ones that I use to compare with my file.
Thank you guys in advance,
Cookie
Click to expand...
Click to collapse
i think , to make that solutions works, you need to insert the datas to database first..
cmiiw
It's Java code of main activity:
package com.example.bluetooth1;
import java.io.IOException;
import java.iutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.bluetooth1.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth1";
Button btnOn, btnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:15:FF:F2:19:5F";
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
@override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
MihaelYank said:
It's Java code of main activity:
package com.example.bluetooth1;
import java.io.IOException;
import java.iutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.bluetooth1.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth1";
Button btnOn, btnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:15:FF:F2:19:5F";
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
@override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
Click to expand...
Click to collapse
Thank you, I will try it out
andihong said:
i think , to make that solutions works, you need to insert the datas to database first..
cmiiw
Click to expand...
Click to collapse
Can I place the incoming data values into an array? I will referesh the array everytime the array finishes with the code
maddoc42 said:
You're probably not looking for a specific algorithm, but rather for some technical guidance? How far along are you? Did you get the Bluetooth connection between the two to work? Are you building your own app?
Click to expand...
Click to collapse
Hi,
Yes i'm building my own app. We have split the work. Im responsible for the app development side.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
I've drafted a state diagram of how I want my app to function.
Can anyone give me a hand on starting to implement this? I am fairly new to coding-just self learning.
Thanks,
Cookie :fingers-crossed:
When i run my script below everything works fine. When i want to go back to the previous activity i get a black screen on the emulator and then the app shuts down, i also get a black screen when i exit the application and try to resume it.
The script:
Code:
package com.example.bono.as3;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.io.InputStream;
public class Main extends Activity {
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
setContentView(drawView);
}
@Override public void onResume(){
super.onResume();
drawView.resume();
}
@Override public void onPause(){
super.onPause();
drawView.pause();
}
public class DrawView extends SurfaceView implements Runnable{
Thread gameloop = new Thread();
SurfaceHolder surface;
volatile boolean running = false;
AssetManager assets = null;
BitmapFactory.Options options = null;
Bitmap incect[];
int frame = 0;
public DrawView(Context context){
super(context);
surface = getHolder();
assets = context.getAssets();
options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
incect = new Bitmap[2];
try {
for (int n = 0; n < incect.length; n++){
String filename = "incect"+Integer.toString(n+1)+".png";
InputStream istream = assets.open(filename);
incect[n] = BitmapFactory.decodeStream(istream,null,options);
istream.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
public void resume(){
running = true;
gameloop = new Thread(this);
gameloop.start();
}
public void pause(){
running = false;
while (true){
try {
gameloop.join();
}
catch (InterruptedException e){}
}
}
@Override public void run (){
while (running){
if (!surface.getSurface().isValid())
continue;
Canvas canvas = surface.lockCanvas();
canvas.drawColor(Color.rgb(85, 107, 47));
canvas.drawBitmap(incect[frame], 0, 0, null);
surface.unlockCanvasAndPost(canvas);
frame++;
if (frame > 1) frame = 0;
try {
Thread.sleep(500);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
I dont get any error message in the log, what i do get is about 13 messages saying "suspending all threads took: X ms" so it has something to the with my gameloop Thread i think. Unfortunately i dont see what the problem is in my code... Can anyone help me with this?
I need help for filtering a listview and open a new activity from the filtered list view onItemClick. The problem is I get the filtered view right but I do not know how to store the ID from JSON for each post.
Problem I am facing: When I click the list item when it is not yet filtered it passes the correct ID for the selected list item. But when I try to filter it, it is showing wrong data (data of another item) in the next activity.
What I am trying to achieve: to show a list of titles in a listview which can be filtered with an edit text box. when I click on any list item (if it is filtered or not) it will pass the ID of that respective item to the next activity.
The Main Fragment - From where I am fetching JSON data and listing it in a listview and filtering the data with edit text.
Code:
public class EnglishHomeSearchFragment extends Fragment {
String url = "MYJSONURL/posts?categories=4&fields=id,title";
List list;
Gson gson;
ProgressBar progressBar;
ListView postList;
Map < String, Object > mapPost;
Map < String, Object > mapTitle;
int postID;
String postTitle[];
EditText editText;
private ArrayAdapter adapter;
private View rootView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.search_englishhome, container, false);
if (!isConnected(getActivity())) buildDialog(getActivity()).show();
else {
postList = (ListView) rootView.findViewById(R.id.postList);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
initlist();
editText = (EditText) rootView.findViewById(R.id.inputsearchenglishhome);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence cs, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text[" + s + "]");
adapter.getFilter().filter(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
return rootView;
}
private void initlist() {
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener < String > () {
@Override
public void onResponse(String s) {
gson = new Gson();
list = (List) gson.fromJson(s, List.class);
postTitle = new String[list.size()];
for (int i = 0; i < list.size(); ++i) {
mapPost = (Map < String, Object > ) list.get(i);
mapTitle = (Map < String, Object > ) mapPost.get("title");
postTitle[i] = (String) mapTitle.get("rendered");
}
adapter = new ArrayAdapter < > (Objects.requireNonNull(getActivity()), android.R.layout.simple_list_item_1, postTitle);
postList.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getActivity(), "Error! Check your Internet Connection.", Toast.LENGTH_LONG).show();
}
});
RequestQueue rQueue = Volley.newRequestQueue(rootView.getContext());
rQueue.add(request);
postList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
mapPost = (Map < String, Object > ) list.get(position);
postID = ((Double) mapPost.get("id")).intValue();
Intent intent = new Intent(getActivity(), EnglishPost.class);
intent.putExtra("id", "" + postID);
startActivity(intent);
}
});
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = Objects.requireNonNull(cm).getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return (mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting());
} else return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet connection.");
builder.setMessage("You are not connected to the Internet.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder;
}
}
I have asked for help in several help forums. But no one helped me yet. I am new to Android app development. Please help me to resolve this issue without changing the whole code. Thank you in advance.
My JSON data looks like this:
Code:
[
{
id: 543,
title: {
rendered: "We are chopped down"
}
},
{
id: 535,
title: {
rendered: "Recover"
}
},
{
id: 528,
title: {
rendered: "Teacher said : Explain the law of gravitation."
}
},
{
id: 517,
title: {
rendered: "Person who ordered Swami to dress up and go to school __________?"
}
},
{
id: 514,
title: {
rendered: "Time when Swami complained of a headache _________?"
}
},
{
id: 512,
title: {
rendered: "When Swami ought to have been in the school prayer hall, he was lying on the?"
}
},
{
id: 510,
title: {
rendered: "Put out"
}
},
{
id: 505,
title: {
rendered: "Make out"
}
},
{
id: 502,
title: {
rendered: "Why did not Swami go to School?"
}
},
{
id: 484,
title: {
rendered: "With a shudder Swami realized that it was?"
}
}
]