Wifi scanner with 20 scanning purpose - java

I was trying to built an array of class and was putting some values to the objects but still it is showing null pointer exception.
my code is :
class WifiScanReceiver extends BroadcastReceiver {
#SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent) {
List<ScanResult> wifilist = wifi.getScanResults();
info = wifi.getConnectionInfo();
int k = wifilist.size();
scan_data[] data = new scan_data[k];
for (int i=0;i<20;i++){
wifi.startScan();
List<ScanResult> wifilist1 = wifi.getScanResults();
int l = wifilist1.size();
if (i==0){
for (int j=0;j<l;j++){
data[j].ssid = wifilist1.get(j).SSID.toString();
data[j].bssid = wifilist1.get(j).BSSID.toString();
data[j].lvl = wifilist1.get(j).level;
data[j].count++;
}
If you could tell me why its is showing null pointer exception at
data[j].ssid = wifilist1.get(j).SSID.toString();

Problem is your scan_Data array is not initialized with objects.
scan_data[] data = new scan_data[k];
this is just initializing the array not putting objects in it. you have to do it explicitly
So in your for loop. Create scan_data object and put all the values in it and then put that on data[j].
for (int j=0;j<l;j++){
scan_data sData = new scan_data();
// set all desired values in sData from ScanData
data[j] = sData;
}
Hope this helps.

Related

Using a Method to update a 2D Array by finding a matching value and then updating with a different input variable

Lets say I have a public class called GameBoard that will be a two dimensional array with 4 rows and 5 columns. The spaces in the array are filed with String values from 1 to 20. A card will be drawn that has a name (King of Spades for example) . If the user inputs 15 I will store it in a String variable called userLocation. What would be the most efficient way to create a method that takes the input location and updates the array with the name of the Card? Would a for loop be most efficient?
public GameBoard() {
square = new String[4][5];
square[0][0] = new String("1");
square[0][1] = new String("2");
square[0][2] = new String("3");
square[0][3] = new String("4");
square[0][4] = new String("5");
square[1][0] = new String("6");
square[1][1] = new String("7");
square[1][2] = new String("8");
square[1][3] = new String("9");
square[1][4] = new String("10");
square[2][1] = new String("11");
square[2][2] = new String("12");
square[2][3] = new String("13");
square[3][1] = new String("14");
square[3][2] = new String("15");
square[3][3] = new String("16");
square[2][0] = new String(17);
square[3][0] = new String(18);
square[2][4] = new String(19);
square[3][4] = new String(20);
}
My preferred method as of now would look something like this but it gives me the error code "type mismatch:cannot convert string to boolean" under userLocation = board[i][j]
public String[][] updateBoard(String userLocation, Card card, String[][] board) {
for (int i = 0; i <4; i++)
{
for (int j = 0; j < 5; j++)
{
if(userLocation = board[i][j]) {
board[i][j] = card.name;
}
}
}
return board;
}
So the reason it will not compile is your = does not return a boolean expression. == would, but it's still not what you want, since you want to check if the String contents are the same, not if they're the same object, so use .equals.
But, no, I think you don't want to depend on strings to identify locations. What if you want to replace a card? And why look through everything when you need not?
Rather if i is some number between 1 and 20, identify the corresponding spot in the array by square[(i-1)/5][(i-1)%5]
That should bypass the issue you are having with matching strings.
So for example, your constructor becomes:
public GameBoard() {
square = new String[4][5];
for (int i=1; i<=20;i++){
square[(i-1)/5][(i-1)%5]=""+i;//initialize with 1 to 20 if you like
}
and userLocation is an int.

Java: How to disable a button in java?

I want to automatically disable a few buttons.
I wrote the code:
import javax.swing.*;
public int[] zamrozone = new int[4];
a1 = new JButton("A1");
a2 = new JButton("A2");
a3 = new JButton("A2");
a4 = new JButton("A2");
a5 = new JButton("A2");
private void zamroz()
{
zamrozone[0]=1;
zamrozone[1]=1;
zamrozone[2]=1;
zamrozone[3]=0;
zamrozone[4]=0;
for(int i=0; i<8; i++) //losuje 8 statkow
{
if(zamrozone[i]==1)
"a"+i.setEnabled(false); // here is an error
}
}
Unfortunately this is not working. Anyone know how to do this?
You can put the JButtons in an array and then use their index:
import javax.swing.*;
final int SIZE = 5;
JButton[] buttons = new JButton[SIZE]
for (int i=0; i<SIZE;i++) {
buttons[i] = new JButton("A" + i)
}
public int[] zamrozone = new int[SIZE];
private void zamroz()
{
zamrozone[0]=1;
zamrozone[1]=1;
zamrozone[2]=1;
zamrozone[3]=0;
zamrozone[4]=0;
for (int i=0; i<SIZE; i++) //losuje SIZE statkow
{
if (zamrozone[i]==1) {
buttons[i].setEnabled(false); // here is an error
}
}
:
}
Use defined SIZE rather then constant values all over your code to avoid OutOfBounds exception and make the code easier to change/maintain.
"a"+i.setEnabled(false); cannot work as variables don't work that way. What you are doing right there is trying to call setEnabled on the integer i and then adding the return value (which does not exist as setEnabled returns void) to the String literal "a".
I would suggest storing your buttons in an array as well and then simply calling buttonArray[i].setEnabled(false) inside the loop.

How to retrieve value changes made from a For Loop within it's own method in Android Studio?

I have a for loop within my main activity that is used to randomly shuffle/reassign the values within an array at the beginning of every time the application is opened.
I was told that for loops in Android Studio could only exist within a method (after getting errors when it was placed without one), but by doing so the random shuffling of the array is not carried over to the rest of the click events that are outside of the method and it just continues to output the same originally assigned values of in the array.
int[] money = {1,10,5,2,20,500,50,100,1000000,5000,1000,50000,100000,500000,250000,10000};
int swap1;
int swap2;
int temp;
Random random = new Random();
void what(){
for (int j=0;j<16;j+=1)
{
swap1 = random.nextInt(16);
swap2 = random.nextInt(16);
temp = money[swap1];
money[swap1] = money[swap2];
money[swap2] = temp;
}
}
The click events that are using the values from this array are like this one:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View b) {
one.setVisibility(View.INVISIBLE);
counter++;
money[0] = 0;
Context one = getApplicationContext();
CharSequence message1 = "$1";
int duration = Toast.LENGTH_LONG; //this could also be a number
final Toast one1 = Toast.makeText(one, message1, duration);
one1.show();
for (int x = 0; x < 16; x++) {
sum += money[x];
}
banker = sum / 16;
Context oney = getApplicationContext();
CharSequence message1y = "The Banker offers you $" + banker + " for your case.";
int durationy = Toast.LENGTH_LONG; //this could also be a number
final Toast one1y = Toast.makeText(oney, message1y, durationy);
one1y.show();
}
});
The aim was that if I were to click this button this time the money output was something like $500, and the next time I opened the application it would randomly shuffle and I might get a new value like $1.
You might want to check out Collections.shuffle() instead of implementing it (don't reinvent the wheel etc).
Sounds like what you want to do is call the shuffle method from inside onCreate() and onResume()
You should do the shuffle inside of the "onCreate" method.
public void onCreate(Bundle savedInstanceState){
...
int[] money = {1,10,5,2,20,500,50,100,1000000,5000,1000,50000,100000,500000,250000,10000};
int swap1;
int swap2;
int temp;
Random random = new Random();
void what(){
for (int j=0;j<16;j+=1)
{
swap1 = random.nextInt(16);
swap2 = random.nextInt(16);
temp = money[swap1];
money[swap1] = money[swap2];
money[swap2] = temp;
}
}
}

Unable to collect values on int array in java/android

i am trying to collect some values in int array,which are from the web service by consuming it.Here i am using SOAP method for the consumption.
when i am trying to collect the values in int array, i am unable to run the emulator.
How to overcome this error? Please find my source for reference.
Main_WB.java
public class Main_WB extends Activity
{
EditText edt1,edt2;
TextView txt_1;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt1 = (EditText)findViewById(R.id.editText1);
edt2 = (EditText)findViewById(R.id.editText2);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
getTMSChart(edt1.getText().toString(),edt2.getText().toString());
}
});
}
private void getTMSChart(String FromDate,String ToDate)
{
txt_1 = (TextView)findViewById(R.id.textView1);
System.setProperty("http.keepAlive", "false");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
String NAMESPACE = "http://tempuri.org/";
String URL = "http://54.251.60.177/TMSOrdersService/TMSDetails.asmx";
String METHOD = "GetTMSChart";
SoapObject request = new SoapObject(NAMESPACE, METHOD);
request.addProperty("FromDate", FromDate);
request.addProperty("ToDate", ToDate);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try
{
androidHttpTransport.call(NAMESPACE + METHOD, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject root = (SoapObject) ((SoapObject)(result).getProperty(0)).getProperty("NewDataSet");
int tablesCount = root.getPropertyCount();
for (int i = 0; i < tablesCount; i++)
{
SoapObject table = (SoapObject) root.getProperty(i);
int propertyCount = table.getPropertyCount();
for (int j = 0; j < propertyCount; j++)
{
// String orderNo = table.getPropertyAsString("Order_No");
// String freight = table.getPropertyAsString("Freight_Rate");
// String percent = table.getPropertyAsString("Margin_Percent");
int orderNo = Integer.parseInt(table.getPropertyAsString("Order_No"));
int freightRate = Integer.parseInt(table.getPropertyAsString("Freight_Rate"));
int marginPercent = Integer.parseInt(table.getPropertyAsString("Margin_Percent"));
int[] ord = new int[orderNo];
int[] frei = new int[freightRate];
int[] margin = new int[marginPercent];
// whatever you do with these values
txt_1.setText(ord);
txt_1.setText(frei);
txt_1.setText(margin);
}
}
}
catch (Exception e)
{
}
} }
It's a compilation error, and the error is quite self-explanatory:
The method setText(CharSequence) in the type TextView is not applicable for the arguments (int[])
This means that the argument of the method setText() must be of type CharSequence, but that you are calling it with an argument of type int[], which is not a CharSequence.
Transform the int[] arrays to Strings, and, as String implements CharSequence, pass the resulting String to setText(). For example:
txt_1.setText(Arrays.toString(ord));
Moreover, I don't really see the point of calling setText() with three different arguments on the same text field.
int orderNo = Integer.parseInt(table.getPropertyAsString("Order_No"));
int freightRate = Integer.parseInt(table.getPropertyAsString("Freight_Rate"));
int marginPercent = Integer.parseInt(table.getPropertyAsString("Margin_Percent"));
int[] ord = new int[orderNo];
int[] frei = new int[freightRate];
int[] margin = new int[marginPercent];
// whatever you do with these values
txt_1.setText(ord);
txt_1.setText(frei);
txt_1.setText(margin);
What are you trying to do here? From looking at that piece of (useless) code it seem like you lack basic programming knowledge and should perhaps read some more tutorials.
That said I'm pointing out what you're actually doing there:
int orderNo = Integer.parseInt(table.getPropertyAsString("Order_No"));
Here you request the property "Order_No" as a string value and convert it into an int. So far so good.
int[] ord = new int[orderNo];
Here you create an int-array with an amount of elements equal to orderNo. So if your orderNo is 12345 you create an int-array with 12345 elements. I don't think that is what you intended.
txt_1.setText(ord);
Here you pass that huge (unintialized) int-array as a parameter to the setText method of txt_1. That method obviously wants a string value and not an int-array.
So what are you trying to do?
EDIT:
To answer your question regarding creating the int-array:
int[] ord = new int[propertyCount];
int[] frei = new int[propertyCount];
int[] margin = new int[propertyCount];
for (int j = 0; j < propertyCount; j++)
{
int orderNo = Integer.parseInt(table.getPropertyAsString("Order_No"));
int freightRate = Integer.parseInt(table.getPropertyAsString("Freight_Rate"));
int marginPercent = Integer.parseInt(table.getPropertyAsString("Margin_Percent"));
ord[j] = orderNo;
frei[j] = freightRate;
margin[j] = marginPercent;
}
// process the arrays;
I assume that you want one array per table so I create the arrays outside the inner loop and fill them within the loop.
Afterwards you can process these arrays. Beware that the arrays are recreated for every table in the outer loop.
Hope that helps.

How to convert from an ArrayList of arrays to an array of arrays

//edit: I changed my ArrayList conversion, but I am unable to load the second spinner
What am I doing wrong. I would like to fill a second spinner with an array of w depending on the row selected in the first spinner, but am getting this warning when trying to convert from array list.
***I have this marked in code
Null Pointer Exception
11-06 19:03:34.050: WARN/System.err(5342): at RetrievingAmazonXMLDataActivity.onCreate(RetrievingAmazonXMLDataActivity.java:88)
// edited code
for (int i = 0; i < tokens.length; i++) {
String a = dumpTitles("ProductName", i);
element = a.split("!");
allProducts.add(element);
}
w = (String[][])allProducts.toArray(new String[allProducts.size()][]);
Spinner spinnerProducts = (Spinner) findViewById(R.id.spinner2);
spinnerProducts.setOnItemSelectedListener(this);
// ** error line below
ArrayAdapter<String> productsArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, productArrayToShow);
productsArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProducts.setAdapter(productsArrayAdapter);
public void onItemSelected(AdapterView<?> parent, View v, int position, long id)
{
try {
selected = parent.getItemAtPosition(position).toString();
productArrayToShow = w[position];
} catch (Exception e) {}
}
// original code
ArrayList<String[]>allProducts = new ArrayList<String[]>();
for (int i = 0; i < tokens.length; i++) {
String a = dumpTitles("ProductName", i);
element = a.split("!");
allProducts.add(element);
}
String[][] w; = new String[allProducts.size()][];
for (int a = 0; a<allProducts.size(); a++) {
w[a] = (String[])allProducts.toArray(new String[allProducts.size()]);
}
Why not just
String[][] w = allProducts.toArray(new String[][] {});
It looks like you changed your mind about how you were going to do the conversion half way through. Your code is a bit of this:
String[][] w = new String[allProducts.size()][];
for (int a = 0; a<allProducts.size(); a++) {
w[a] = allProducts.get(a);
}
and a bit of that:
String[][] w = allProducts.toArray(new String[allProducts.size()][]);
Either will work, though the latter is shorter, and possibly more efficient.
I think you can get by with just this:
String[][] w = allProducts.toArray(new String[allProducts.size()]);
Make them of the same datatype an "ArrayList" and a "Array of Strings" they are not of the same datatype, so they wont be compartable with each other. And please comment where the problem is.

Categories

Resources