2D array in android without specify dimention length - java

public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[][] Array2D = new String[2][10];
Button enter =(Button)findViewById(R.id.Button1);
final EditText valueEditText=(Button)findViewById(R.id.EditText1);
final EditText xEditText=(Button)findViewById(R.id.EditText1);
final EditText yEditText=(Button)findViewById(R.id.EditText1);
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value =valueEditText.getText().toString();
int x=Integer.valueOf(xEditText.getText().toString());
int y=Integer.valueOf(yEditText.getText().toString());
Array2D[x][y]=value;
}
});
}
}
I am working on a project with 2D String array. At every click, I enter new addresses and values to be entered in that address.
The problem is: I want to do that with dynamic array (without defining specific dimensions for long and width)
Could any one can help me please ???

The length of an array is fixed.
You should use a List<List<String>> instead.

Related

how to call the output of a method in another Activity 's textview?

im programming an app to sort numbers and display the sorting process
after the input is sorted , a new button will be showen to display the selection sort steps in a new activity
[SelectionSort activity 1
I want the output of the function SelectionSortMethod in SelectionSortclass to be displayed in a new activity activity_Ssteps
SelectionSort.java :
public class SelectionSort extends AppCompatActivity {
EditText input;
EditText output;
Button Ssteps ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection_sort);
input=findViewById(R.id.input);
output=findViewById(R.id.output);
Ssteps = findViewById(R.id.steps);
Ssteps.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent s = new Intent(SelectionSort.this, com.example.sorted.Ssteps.class);
startActivityForResult(s, 1);
}
});}
public void sortButtonPressed(View view){
String[] numberList = input.getText().toString().split(",");
Integer[] numbers = new Integer[numberList.length];
for (int i = 0; i < numberList.length; i++) {
numbers[i] = Integer.parseInt(numberList[i]);
}
SelectionSortmethod(numbers);
output.setText(Arrays.toString(numbers));
// if button "sort " is pressed , the button "view steps "will be displayed
Ssteps.setVisibility(View.VISIBLE);
}
}
public static void SelectionSortmethod (Integer[] arr)
{
// some code for sorting and showing the steps
}
Ssteps.java :
public class Ssteps extends AppCompatActivity {
TextView steps_text ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ssteps);
setTitle("selection sort steps ");
steps_text =findViewById(R.id.Stepstextview);
}
}
You can just use intent.extras like so:
Intent s = new Intent(SelectionSort.this, com.example.sorted.Ssteps.class);
s.putExtra("AnyID",YOURDATA);
startActivity(s);
And then in your Ssteps.class you can get the data using
the id like this:
String ss = getIntent.getExtra("AnyID"); //the id is the same as the other one above
steps_text.settext(ss);
Working with Intents like Youssof described is the way to go for small applications like yours. However as you progress in Android programming, you should definitely have a look at splitting your application in Fragments rather than Activities. They can use a Viewmodel, which makes sharing lots of data between screens much easier. Also Fragments can be use in androidx Navigation component, whos changing Fragments can be beautifully arranged in a UI. Very convenient for product reviews.

How to make this average of positions?

I have list with multiple choice. Application must calculate the average of whole list's positions.
In first activity
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
Button button_1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_1 = (Button) findViewById(R.id.button_1);
button_1.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_1:
Intent intent = new Intent(this, Main3Activity.class);
startActivity(intent);
break;
}
}
}
In second activity each position must have int variable ( Uruguay - 3444000, Paraguay - 6725000 e.t.c) In result, in third activity must be displayed average of each position.
public class Main3Activity extends AppCompatActivity {
Button button2
\button2 direct to third activity
String[] countries = { "Urugay", "Paraguay", "Jamaica", "Peru", "Mexico"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView countriesList = (ListView) findViewById(R.id.countriesList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_multiple_choice, countries);
countriesList.setAdapter(adapter);
}
}
The countries displayed in second activity without variables. But after picked by user, average displayed in third activity.
Need your advice, Or some code )
Just like this array:
String[] countries = { "Urugay", "Paraguay", "Jamaica", "Peru", "Mexico"};
create another one:
int[] positions = { 3444000, 6725000, 0, 0, 0};
then with a loop you find the average:
int sum = 0;
for (i = 0; i < positions.length; i++) {
sum += positions[i];
}
int average = sum / positions.length;
Is it that you need to calculate the average? You do that by adding all the points an divide them by the number of entries. So in this case, add the points of the two countries an divide them by two.
Keep in mind that dividing mostly has a result with a fraction (something behind the decimal point), so be sure to get a floating point type variable and, if needed, round appropriately to an int afterwards.

Class variable random number... always the same? Android.

I am working through a Udemy course and we're building a basic "Higher or Lower" app. My app essentially works, however the random number it chooses for us to guess is always the same no matter how many times I destroy and relaunch the activity.
My MainActivity.java:
//mad import statements here
public class MainActivity extends AppCompatActivity {
int correctNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int correctNumber = generateNum();
}
protected int generateNum(){
Random rand = new Random();
int randNum = rand.nextInt(100);
return randNum;
}
protected void numberEval(View view) {
EditText enteredNumber = (EditText) findViewById(R.id.numberEntry);
String numberString = enteredNumber.getText().toString();
Button pressMe = (Button) findViewById(R.id.button);
int numToEval = Integer.parseInt(numberString);
String result;
TextView showWinLose = (TextView) findViewById(R.id.winLoseText);
if (numToEval > correctNumber) {
result = "Too high!";
} else if (numToEval < correctNumber) {
result = "Too Low!";
}else {
result = "You guessed it!";
}
showWinLose.setText(result);
}
}
Super super basic, yes? Originally, my numberEval() method called generateNum(), but then I realized it was generating a new number to guess every time I pressed the button. So I set it the way it was here, where onCreate() generates correctNumber only once and correctNumber is now a class variable. Now it doesn't generate a new number every button click, but it won't seem to generate a new number at all. It's stuck at 0 no matter how any times I launch, close, relaunch, etc. the app.
How can I fix this? Thanks in advance.
public class MainActivity extends AppCompatActivity {
int correctNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int correctNumber = generateNum();
}
// ...
}
The last line in onCreate() declares a local variable named correctNumber. This hides the class field with the same name and is only available inside onCreate(). To fix the problem, remove int from this line so that you use the class field instead.

How to get and store multiple genrated edittext value in android?

I am adding multiple Edittext at the click of button. I am also getting the value of these Edittext, but I am unable to store data in array.
EditText textIn;
Button buttonAdd, buttonShow;
LinearLayout container;
List<EditText> allEds = new ArrayList<EditText>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonAdd = (Button)findViewById(R.id.add);
buttonShow = (Button) findViewById(R.id.show);
container = (LinearLayout)findViewById(R.id.container);
buttonAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
EditText editText1 = (EditText) addView.findViewById(R.id.editText1);
EditText editText2 = (EditText) addView.findViewById(R.id.editText2);
allEds.add(editText1);
allEds.add(editText2);
Button buttonRemove = (Button) addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addView.getParent()).removeView(addView);
}
});
container.addView(addView);
}
});
buttonShow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[allEds.size()];
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
Log.e("My data", strings[i]);
}
}
});
Here I am getting all value using strings[i], but I want to store value in array like this. [{"Name": "Smith","Age", "26"},{"Name": "Jhon","Age", "30"}]. Here I will get Smith,26 and Jhon, 30 from multiple generated Edittext. Array will be extended after generating more dynamic fields.
Please help me.
You say you have to get it as an array. As I see it, you're already getting it as a String array. What else do you want? The way you're describing the expected result looks like a half-baked json output. Perhaps you can create a class that represents the Person whose info you want and then create an ArrayList of the Person type. Also to make things easier to stuff in the Person object you can declare a constructor that takes name and age as parameter. In your loop you can create a Person object using that constructor and then add that object to the ArrayList.
This would help :
class Person{
String name;
int age;
Person(String name, int age){
this.name=name;
this.age=age;
}
}
Then before going into your loop, declare an ArrayList of type Person
ArrayList<Person>persons=new ArrayList<Person>();
And finally in your loop :
Person temp = new Person(*get the name, get the age*);
persons.add(temp);
And voila!, you have your person ArrayList ready.

Displaying list values with each button click

How can i display list items on each button click. Lets say there are 4 names in the list. When I press next it displays the first name. Then when you press next it displays the second name and so on.
The only way I think is using the list.get() method. however I dont know how to use the method so that it knows how many values there are in the list and displaying then on each button hit. I think i need to use for method however I hadnt had any luck with it.
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mPlayer;
public TextView mKlausimas;
public Button mNext;
public Button mBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
Intent zaidejuInfo = getIntent();
Bundle extrasBundle = zaidejuInfo.getExtras();
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
//show the first players name
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.setText(players.get(1));
}
});
mBack = (Button)findViewById(R.id.GryztiMeniuBtn);
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gryztiMeniu = new Intent(ZaidimasActivity.this, ZaidejaiActivity.class);
startActivity(gryztiMeniu);
}
});
}
Here you go, maintain a variable for storing the global array index and increment it every time the button is clicked.
private int count = 0; // Global array index. Make it as class field
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
mPlayer.setText(players.get((count)%players.size())); //Incrementing global count and making sure it never exceeds the players list size
}
});

Categories

Resources