Unable to collect values on int array in java/android - java

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.

Related

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;
}
}
}

Passing String variables to Java method not working, but hard-coded string working?

I'm having a strange issue. I'm trying to pass a number of String variables denoting a user's dislikes to a predefined Java method that works by comparing these dislikes to the key ingredients stored as a String array in a Recipe object array.
The method works fine when I hard-code a dislike, such as "Beef", but when I assign the dislikes to an instance String variable kw1 using user1.getDislikes(0), the method does not perform correctly - it returns recipes that have "Beef" as a keyword, when it shouldn't.
I know the String is being passed and assigned correctly as I used a Toast to display kw1 upon returning valid results.
I've tried adding toString() in numerous places as IntelliJ was being picky about it earlier, despite claiming it is redundant, but it hasn't worked here.
Here's the section I'm having difficulty with:
if ((SetRecipes.recipes[index].searchkeywords2(kw1, kw2, kw3))) //Not working unless words (e.g. "Beef") are hardcoded for some reason. kw1 variable being assigned correctly, as shown by Toast.
{
temp[validRecipe] = index;
validRecipe++;
} //if
The full code can be found below. Any help is greatly appreciated!
public class SuggestResult extends Activity
{
String kw1, kw2, kw3;
static TextView [] recipeText = new TextView[8];
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.suggest_results);
User user1 = (User)getIntent().getSerializableExtra("user1");
kw1 = user1.getDislikes(0).toString();
kw2 = user1.getDislikes(1).toString();
kw3 = user1.getDislikes(2).toString();
/*
kw1 = "null";
kw2 = "null";
kw3 = "null";
*/
recipeText[0] = (TextView)findViewById(R.id.recipeSuggestText1);
recipeText[1] = (TextView)findViewById(R.id.recipeSuggestText2);
recipeText[2] = (TextView)findViewById(R.id.recipeSuggestText3);
recipeText[3] = (TextView)findViewById(R.id.recipeSuggestText4);
recipeText[4] = (TextView)findViewById(R.id.recipeSuggestText5);
recipeText[5] = (TextView)findViewById(R.id.recipeSuggestText6);
final int MAXRECIPES = 7;
final int MAXTEXTFIELDS = 6;
int[] temp = new int[MAXRECIPES];
int validRecipe = 0;
SetRecipes.setArray();
for (int index = 0; index < MAXRECIPES; index++)
{
if ((SetRecipes.recipes[index].searchkeywords2(kw1, kw2, kw3))) //Not working unless words (e.g. "Beef") are hardcoded for some reason. kw1 variable being assigned correctly, as shown by Toast.
{
temp[validRecipe] = index;
validRecipe++;
} //if
}
if (validRecipe == 0)
{
Context context = getApplicationContext();
CharSequence text = "No valid recipes found!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
for (int index3 = 0; (index3 < validRecipe) && (index3 < MAXTEXTFIELDS); index3++)
{
recipeText[index3].setText((SetRecipes.recipes[temp[index3]].getName()).toString());
}
Context context = getApplicationContext();
CharSequence text2 = kw1;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text2, duration);
toast.show();
}
}
searchkeywords2 method:
public boolean searchkeywords2(String choice1,String choice2, String choice3)
{
int ingredientsPresent = 0;
for (int index = 0; index < keywords.length; index++)
{
if ((keywords[index] == choice1) || (keywords[index] == choice2) || (keywords[index] == choice3))
{
ingredientsPresent++;
}
}
if (ingredientsPresent == 0)
{
return true;
} else
{
return false;
}
}
keywords[index] == choice1 ...
This is the problem. Use .equals() function to compare strings, not ==
keywords[index].equals(choice1) etc.
Always use .equals to compare strings because == operator only compares references rather than data
When we use == operator, it checks if the objects point to the same location on the memory but the .equals on the other hand apart from checking if the objects point to the same location also checks for the equality of the object content in the memory location, thus providing double check. You can also override the equals class to perform other checks.
So, always use the .equals to check equality of 2 objects.

Wifi scanner with 20 scanning purpose

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.

TextView variable name + string combining

question with either easy or impossible answer, dunno. I'm new and I want to create new TextView's within a loop, but I'm having problem with TextView's variable name. I need it to be unique.. Thanks.
int i = 1;
while (i<=10) {
String asd = String.valueOf(i);
TextView textView+asd = new TextView(this);
//new textView+asd.setText("asdd");
i++;
}
You can't do it like you posted. You need to create array of TextView's. TextView textViews[] = new TextView[10]; for(int i=0; i<textViews.length; i++) { textViews[i] = new TextView(this); }
You will need to use your layout and do something like this
final int x = 5; // # of TextViews you want
int i = 0;
final TextView[] textViews = new TextView[x];
while (i < x) {
TextView newTextView = new TextView(this); // this needs to be the proper context
newTextView.setText("Whatever");
layout.addView(newTextView); // Need to bring in your layout before this
textViews[i] = newTextView;
i++;
}

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