How can I make the maximum value of two arrays - java

The app has 2 arrays. They are related among themselves. The user may choose
a few item of array "countries", then maximum position of choosed items are displayed on second activity. For example user choose "Urugay", "Paraguay", "Jamaica", and then
the maximum position (6770000) displayed on second activity. How to make this ?
package com.example.1.2;
import android.content.Intent;
import android.media.browse.MediaBrowser;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Main1Activity extends AppCompatActivity implements
View.OnClickListener {
public static final String KEY_AVERAGE = "average";
String[] countries = {"Urugay", "Paraguay", "Jamaica", "Peru", "Mexico"};
int[] population = {6770000, 2300000, 500000, 6310000, 7000000};
Button btnSubmit;
int sum;
ListView countriesList;
int average;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
Map<String, Integer> countryData = new HashMap<>(countries.length);
for (int i = 0; i < countries.length; i++) {
countryData.put(countries[i], population[i]);
}
countriesList = findViewById(R.id.countriesList);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, countries);
countriesList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
countriesList.setAdapter(adapter);
btnSubmit = findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray checked =
countriesList.getCheckedItemPositions();
int max = 0;
for (int i = 0; i < checked.size(); i++) {
if (checked.valueAt(i))
// The code that make the maximum position of user choosing may be here
Intent intent = new Intent(this, Main3Activity.class);
intent.putExtra(KEY_AVERAGE, average);
startActivity(intent);
}
}
public class Main2Activity extends Main1Activity {
TextView tvView;
int average;
#RequiresApi(api = Build.VERSION_CODES.N)
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tvView = (TextView) findViewById(R.id.tvView);
Intent mIntent = getIntent();
maximum = mIntent.getExtras().getInt(Main1Activity.KEY_MAXIMUM,
maximum);
tvView.setText("Maximum: " + maximum);
}
}

Firstly, you have to store the indexes of matched countries. Lets say, countries that user submitted are stored in and Array userChoice and indexes of these countries in Array countries are stored in `Array matchedIndexes. Following code do this:
Stores the index of user's submitted countries.
Compare the population on those indexes and return maximum population
Code:
public static void main(String[] args)
{
String[] countries = {"Urugay", "Paraguay", "Jamaica", "Peru", "Mexico"};
int[] population = {6770000, 2300000, 500000, 6310000, 7000000};
// suppose user selected these countries
String[] userChoise = {"Urugay", "Paraguay", "Jamaica"};
int maxPopulation = findMaxPopulation(countries, population, userChoise);
System.out.println(maxPopulation);
}
public static int findMaxPopulation(String[] con,int[] pop,String[] choice)
{
// indexes of countries in "Countries array" that submitted by user
int[] matchedIndexes = new int[choice.length];
int j=0; // for incrementing Array matchedIndexes
int max = 0; // will return the maximum population
for(int i =0;i<choice.length;i++){
if(con[i].equals(choice[i])){
matchedIndexes[j] = i;
j++;
}
}
// making comparision of population of submitted countries
max= pop[matchedIndexes[0]];
for(int i=0;i<matchedIndexes.length -1;i++){
if(max<pop[matchedIndexes[i+1]])
max = pop[matchedIndexes[i+1]];
}
return max;
}

Related

Adding array-lists content to a Text View giving empty text

I am trying to display the phone numbers of each card inserted in a phone via an app that I am creating as follows
mSubscriptionManager = SubscriptionManager.from(context);
GetCarriorsInformation();
number = findViewById(R.id.phone_numbers);
for (int i=0; i < Numbers.size(); i++){
number.append(number.getText() + Numbers.get(i) + " , ");
}
This is after getting the phone numbers and adding each to the arraylist as shown bellow
private void GetCarriorsInformation() {
Numbers = new ArrayList<>();
subInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subInfoList.size() > 1) {
isMultiSimEnabled = true;
}
for (SubscriptionInfo subscriptionInfo : subInfoList) {
Numbers.add(subscriptionInfo.getNumber());
}
}
This runs without errors but and the textView only shows ''
What could I be doing wrong?
Here is the enttire MainActivity.java code
package com.otemainc.securesoccialmedia;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Context context;
private SubscriptionManager mSubscriptionManager;
public static boolean isMultiSimEnabled = false;
public static String defaultSimName;
public static List<SubscriptionInfo> subInfoList;
public static ArrayList<String> Numbers;
TextView number;
#TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
mSubscriptionManager = SubscriptionManager.from(context);
GetCarriorsInformation();
number = findViewById(R.id.phone_numbers);
for(int i=0; i < Numbers.size(); i++) {
number.append(number.getText() + Numbers.get(i) + " , ");
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private void GetCarriorsInformation() {
Numbers = new ArrayList<>();
subInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subInfoList.size() > 1) {
isMultiSimEnabled = true;
}
for (SubscriptionInfo subscriptionInfo : subInfoList) {
Numbers.add(subscriptionInfo.getNumber());
}
}
}
I have also added this line to the manifest file
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Try putting a breakpoint there to check if there are any values in subscriptionInfo. Otherwise try using:
Numbers.add(String.valueOf(subscriptionInfo.getNumber()));

Why the arraylist empties itself when it is called optionPressed method?

Making a simple BrainTrain app, the updateAnswer method gives out random answers to the question but the issue comes up whenever i call the optionsPressed method and try getting any of the object, the arrayList gives out IndexOutOfBoundsException.
package com.example.nishantsaini.braintrain;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
import static android.R.color.black;
import static android.R.color.holo_blue_bright;
import static android.R.color.holo_blue_dark;
import static android.R.color.holo_blue_light;
import static android.R.color.holo_green_light;
public class MainActivity extends AppCompatActivity {
Random rnd = new Random();
boolean gameisActive = false;
int count = 0;
CountDownTimer cd;
int var1,var2;
ArrayList<Button> options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long l) {
Log.i("Time Left:", Long.toString(l / 1000));
TextView timer = (TextView) findViewById(R.id.timer);
timer.setText("0:" + String.format("%02d", (l / 1000)));
}
#Override
public void onFinish() {
TextView score = (TextView) findViewById(R.id.Score);
LinearLayout onFinishLayout = (LinearLayout) findViewById(R.id.onFinishLayout);
/*score.setText( "You got " + getScore() + "right!");
*/
}
};
options = new ArrayList<>();
options.add((Button) findViewById(R.id.option2));
options.add((Button) findViewById(R.id.option1));
options.add((Button) findViewById(R.id.option3));
options.add((Button) findViewById(R.id.option4));
}
public void start(View view) {
cd.start();
Button start = (Button) findViewById(R.id.start);
updateQuestion();
updateAnswers(options);
start.setText("Replay");
}
public void optionPressed(View view){
ColorDrawable blue_d = new ColorDrawable(getResources().getColor(R.color.blue_b));
ColorDrawable blue_l = new ColorDrawable(getResources().getColor(R.color.blue_l));
ColorDrawable blue_b = new ColorDrawable(getResources().getColor(R.color.blue_b));
ColorDrawable green = new ColorDrawable(getResources().getColor(R.color.green));
Drawable color = blue_b;
while(options.size() > 0) {
int index = rnd.nextInt(options.size());
Button b = options.get(index);
if (color == blue_b){
color = blue_d;
b.setBackground(color);
}
else if (color == blue_d){
color = green;
b.setBackground(color);
}
else if (color == green){
color = blue_l;
b.setBackground(color);
}
else if (color == blue_l)
{
color = blue_b;
b.setBackground(color);
}
options.remove(index);
}
updateQuestion();
updateScore();
updateAnswers(options);
}
public void updateQuestion(){
var1 = 5 + (int)(Math.random()*20);
var2 = 5 + (int)(Math.random()*20);
TextView question = (TextView) findViewById(R.id.question);
question.setText(Integer.toString(var1) +" + " + Integer.toString(var2) + " = ");
question.setPadding(0,50,0,0);
}
public void updateScore(){
count++;
int correct = 0;
TextView score = (TextView) findViewById(R.id.points);
score.setText(Integer.toString(correct) + "/" + Integer.toString(count));
}
public void updateAnswers(ArrayList<Button> arrayList ){
Button b;
int answer = var1 + var2;
int indexAtWhichRealAnswerGoes = 1+ (int) (Math.random()*3);
int id ;
Log.i("arraylist size",Integer.toString(options.size()));
b = arrayList.get(indexAtWhichRealAnswerGoes);
b.setText(Integer.toString(answer));
id = b.getId();
arrayList.remove(indexAtWhichRealAnswerGoes);
for (int i = 0; i < arrayList.size(); i++) {
int randomanswer = (answer-7) + (int)(Math.random()*(answer+7));
b = arrayList.get(i);
b.setText(Integer.toString(randomanswer));
}
arrayList.add((Button) findViewById(id));
Log.i("arraylist size",Integer.toString(arrayList.size()));
}
}
So, you call updateAnswers(options); using the list that you previously emptied
while(options.size() > 0) {
int index = rnd.nextInt(options.size());
...
options.remove(index);
}
...
updateAnswers(options);
At that point, the list is empty.
In the method, you safely used for (int i = 0; i < arrayList.size(); i++) { to prevent any error but before that we see
int indexAtWhichRealAnswerGoes = 1+ (int) (Math.random()*3);
...
b = arrayList.get(indexAtWhichRealAnswerGoes);
You get that random index without checking the size of the list. (List that is empty at that point).
If you want to keep the list with its value, but the logic can't be change so the remove is necessary, you need to do a copy of the list to work on that one, and pass the original to the method updateAnswers.
List<Button> copyOptions = new ArrayList<>(options);
It will share the same instance, but you can update the list copyOptions without having any impact on options

I need to sort my random numbers generated and add them to the second editText2

package com.example.sai.generatinrandomnumbers;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
// I need to sort my random numbers generated and add them to the second editText2 in my application i tried using collections but i couldn't figure it out plz help me and I'm attaching my code below.should i use a arraylist again??
public class MainActivity extends AppCompatActivity {
EditText editText, editText2;
Button button, button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText.setEnabled(false);
editText2 = (EditText) findViewById(R.id.editText2);
editText2.setEnabled(false);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random r = new Random();
ArrayList<Integer> num = new ArrayList<Integer>();
for (int i = 0; i < 6; i++) {
int answer = r.nextInt(10) + 1;
num.add(answer);
editText.setText(String.valueOf(num));
}
}
});
}
}
You need to read all the Integers into your data structure and then print them back sorted to a 2nd EditText Widget. Alright, let's do something like this:
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random r = new Random();
ArrayList<Integer> num = getRandomNums(6);
editText.setText(getStringNum(num));
Collections.sort(num);
editText2.setText(getStringNum(num));
});
private List<Integer> getRandomNums(final int theNumDigits) {
Random r = new Random();
ArrayList<Integer> num = new ArrayList<>();
for (int i = 0; i < theNumDigits; i++) {
int answer = r.nextInt(10) + 1;
num.add(answer);
}
return num;
}
private String getStringNum(final List<Integer> theNumbers) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < theNumbers.size(); i++) {
sb.append(num.get(i));
}
String toReturn = sb.toString();
sb.setLength(0);
return toReturn;
}
I reformatted the code for you to help you understand exactly what is going on. You're getting all the randomly generated numbers and adding them to an ArrayList. Then creating a String using a StringBuilder You were overwriting your previously set value in the EditText each time your loop iterated
Then you call Collections.sort() and do the whole thing over again.

List isn't populating

I'm making an app that will list addresses nearby in a listview, but for some reason the addresses aren't going into the list. Am I missing something with the address collection or?...
It happens within the for loop. I want it to read the list of addresses I get and trim the information I want to only necessary bits, like street numbers and zip codes instead of the big mess of numbers.
Every time I run the app however, the list remains blank.
package com.atonea.ps;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class PSActivity extends Activity {
protected static final Location Location = null;
/** Called when the activity is first created. */
String location_text="";
String here="";
final ArrayList<String> addressbook = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button goButton = (Button) findViewById(R.id.beginButton);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void updateWithNewLocation(Location location) {
String latLong;
TextView uhoh = (TextView) findViewById(R.id.texty);
ListView listview = (ListView) findViewById(R.id.listview1);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, addressbook);
listview.setAdapter(arrayAdapter);
String addressString = "no address found";
Address fulladdress;
String street;
String zip;
String addresstogether;
if(location!=null) {
double lat = location.getLatitude();
double lon = location.getLongitude();
latLong = "Lat:" + lat + "\nLong:" + lon;
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this,Locale.getDefault());
try {
List addresses= gc.getFromLocation(lattitude, longitude, 1);
if(addresses.size()>0) {
for (int a = 0; a > 6; a++) {
fulladdress = ((Address) addresses.get(a));
street = fulladdress.getAddressLine(a);
zip = fulladdress.getPostalCode();
addresstogether = street+" "+zip;
addressbook.add(a, addresstogether);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),addresstogether, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
}
} else {
latLong = " NO Location Found ";
}
uhoh.setText("your Current Position is :\n" +latLong + "\n " + addressString );
}
}
for (int a = 0; a > 6; a++) {
You are never going to enter this loop. You start with 0 which is always smaller than 6.
This condition for (int a = 0; a > 6; a++) is not correct.
As you have initialized a with 0 and then checking a > 6 it will always be false and your program will never get in the loop.
It must be for (int a = 0; a < 6; a++).

Randomly pick an index from an array, display in TextView

I'm new to Android development and I'm wondering why my code crashes the Android Emulator. What I'm doing is creating an array of strings, then picking an index from the array at random and displaying the value inside a TextView. But it always seems to crash my emu.
package com.test.randomTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class randomTestActivity extends Activity {
private Button button;
private TextView helloTextView;
private String[] hellos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloTextView = (TextView)findViewById(R.id.helloText);
button = (Button)findViewById(R.id.button);
hellos = new String[7];
hellos[0] = "Hello";
hellos[1] = "G'days";
hellos[2] = "Yo!";
hellos[3] = "Hi";
hellos[4] = "Hay";
hellos[5] = "Bonjour";
hellos[6] = "Hay there!";
hellos[7] = "Hallo";
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
String helloText = hellos[x];
helloTextView.setText(helloText);
}
};
}
Any help/advice would be great!
Thanks.
You created a String[] of size 7.
hellos = new String[7];
Therefore the indices range from 0 to 6. Trying to access hellos[7] will cause an IndexOutOfBoundsException.
I assume your getting a nullpointerexecption. Try generating your random number like this instead:
Random rando = new Random();
int x = rando.nextInt(hellos.lenght);
package com.test.randomTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class randomTestActivity extends Activity {
private Button button;
private TextView helloTextView;
private String[] hellos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloTextView = (TextView)findViewById(R.id.helloText);
button = (Button)findViewById(R.id.button);
hellos = new String[8];
hellos[0] = "Hello";
hellos[1] = "G'days";
hellos[2] = "Yo!";
hellos[3] = "Hi";
hellos[4] = "Hay";
hellos[5] = "Bonjour";
hellos[6] = "Hay there!";
hellos[7] = "Hallo";
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
String helloText = hellos[x];
helloTextView.setText(helloText);
}
};
}
Increase string array size you gave 7 as size, but you are passing 8 values to string.
so it throws indexoutofbounds exception.
Thats probably because of array IndexOutOfBoundException... since sometimes your x will have value 8 but array length is just 7..

Categories

Resources