Why 2D array return 'null'? - java

i make a 2D String array in main activity but i make NEW in another activity :
public class MainActivity extends Activity
{
public String[][] arr;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestpayment requestpayment=new requestpayment(getApplicationContext(), 1, 8, "boy");
TextView textView=(TextView)findViewById(R.id.text);
textView.setText(arr[1][1].toString());
}
}
In second Activity i use 2d array in this form :
int i=1;
MainActivity mainActivity=new MainActivity();
mainActivity.arr= new String[5][5];
mainActivity.arr[i][0] = FLName;
mainActivity.arr[i][1] = Old;
mainActivity.arr[i][2] = Image;
mainActivity.arr[i][3] = Gender;
mainActivity.arr[i][4] = Description
to here و Everything work good and i can use array amount in second activity.
but when use 2d-array in mainactivity in this form :
textView.setText(arr[1][1].toString());
return null :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.../....main.MainActivity}: java.lang.NullPointerException
before , i make a ArrayList and New in another activity then i use in main activity and that work right , but for 2d array not work;
Now , how i can use this array that maked new in another activity

public String[][] arr was never initialized.
You need to do something like,
private String[][] arr = null;
public String[][] getArr()
{
if(arr == null)
{
arr = new String[5][6];
}
return arr;
}
Although I personally think you probably wanted to make an array list, or maybe a List of String arrays.
List<String[]> list = new ArrayList<String[]>();
If you wanted to send the array between activities, you should rather make a holder class that holds the array, make it parcellable, and send the holder between activities using Intent Extras. The http://www.parcelabler.com/ helps with making a class Parcelable.

You haven't shown enough code for me to say for sure, but that new call makes it look like your second class is setting up the array on a different instance of your main class; you never show any communication between them.

Okay… To answer your question. MainActivity mainActivity = new MainActivity(); Only creates an object: Instantiates the object. In the second class where you declare the String[][] you are assigning values and that is fine (although not a good design, unless a parent/child class relationship exists). If you were to call textView.setText(arr[1][1].toString()); in the second class you would have the values. But the thing is there is no call back. In other words your main class has no idea what the second class is doing.
I would look at other ways to persist your data. But if your do. You need a way for the first class to know your added values to your array. Which with out some sort of data persistence will be hard.
Why you are doing this in the first place is not clear. The problem is your design. Why are you going back and forth? There is no rhyme or reason. Create your array in the class it will be used and if it will not be used in that class use a data store to persist that data (or pass the data to the next class via an intent; but only primitive types). There are a few ways to data persist in Android. Read the multiple tutorials out there.
Think of OOP principles. Only pass info if it is necessary.. Deal with the info in the class it is created (substantiated). Hope this helps.

As others have said, the NullPointerException should be related to the fact that you are referencing different instances of the MainActivity. Please have a look at the code below, which is working only when arr is declared static AND the array creation is happening before using it in the class where it is actually declared (and not created):
public class Main {
public static void main(String[] args) {
SecondClass sc = new SecondClass();
sc.printArray(1, 1);
FirstClass fc = new FirstClass();
fc.printArray(1, 1);
}
}
class FirstClass {
public static String[][] arr;
public void printArray(int i, int j) {
System.out.println(arr[i][j]);
}
}
class SecondClass {
SecondClass(){}
public void printArray(int i, int j) {
FirstClass fc = new FirstClass();
fc.arr = new String[5][5];
for (int x=0; x<5; x++)
for (int y=0; y<5; y++)
fc.arr[x][y] = Integer.toString(x*y);
System.out.println(fc.arr[i][j]);
}
}

// okay to return empty 2d array..
//simply create one function like below
public static int[][] subsets(int input[],int index) {
if(index==input.length)
{
int arr[][]= {};
return arr;
}

Related

Passing value of arrayList from a void method to arrayList in another class

I have a class named Preprocessing and has a method called Process()
, it has an ArrayList called datatweets that contains my data.
public void Process(){
//the process...
datatweets.add(mydata);
}
then I try to pass the datatweets and the value(my data) to another ArrayList on the different class. I've tried using getter method such as:
public ArrayList getMyList(){
return datatweets;
}
but it still doesn't print any value when I call it. please tell me what is wrong, and what should I do?
here's what i do to call the arrayList:
Preprocessing data = new Preprocessing();
ArrayList<String> dataset = new ArrayList<>();
dataset = data.getMyList();
for(int a=0;a<dataset.size();a++){
System.out.println(dataset.get(a));
}
As i understand you have an class named "Preprocessing". Now you should have "datatweets" as your instance variable of the class.
Now you should create an object of Preprocessing and call the method "Process". In the method process you should fill the arraylist "datatweets". Process method should contain below code.
if(this.dataTweets == null)
this.dataTweets = new ArrayList<>();
this.dataTweets.add(myData);
Once the datatweets is filled by calling the process method. You should have getter method in same class which should return datatweets
public List<String> getDataTweets(){
return this.dataTweets;
}
Now the main function should look like this
public static void main(String[] args){
Preprocessing preprocessor = new Preprocessing();
preprocessor.Process();
List<String> dataTweets = preprocessor.getDataTweets();
//Now iterate over this you will surely get data.
}
You class Preprocessor should be like this
public class Preprocessor{
private List<String> dataTweets;
public void process(){
//processing
this.dataTweets.add(data);
}
public List<String> getDataTweets(){
return this.dataTweets;
}
}

How to convert type Class<?> to int

I am trying to convert this data type to call out the method later on in another class to switch around layouts being made in other methods such as recipe1Layout(); by the index number of a class that has a field of a Class<?> Array.
Here is the getItem() method
public int getItem(){
int index = 0;
for(int i = 0; i < 100; i++) {
try{
index = recipe.getClass().getField("Classes").get(i);
} catch(Exception e){
}
}
return index;
}
Here is the Recipe Class
public class Recipes {
public Class<?>[] Classes = {
ChileConLecheActivity.class,
ArrozActivity.class,
EnchiladasActivity.class,
SopaActivity.class
};
}
The type of Class needs to be here because I have other uses for the recipe class.
For example, making a new instance of all classes to later on be called out to make adjustments to all the classes with one method.
The only thing I can think of is converting the type Class to an int so I can call out the method returning the index number I can do something like recipe.
index = Integer.parseInt(Classes[I].getName().toString());
But this is where I am asking for help I have no idea how to get rid of the error in the logcat.
The error shows up as
IndexOutOfArrayException
First off, stop using reflection. Use a public static array.
public class Recipes {
public static final Class<?>[] CLASSES = {
ChileConLecheActivity.class,
ArrozActivity.class,
EnchiladasActivity.class,
SopaActivity.class
};
}
Then, assuming your recipe instance has a field of what Class<Activity> it is assigned to, then, you would want something like this
public int getItem(){
int index = -1;
for(int i = 0 ; i < Recipe.CLASSES.length; i++) {
if (recipe.getActivityClass().equals(Recipe.CLASSES[i]) {
index = i;
break;
}
}
return index;
}
However, under certain situations, coupling one Activity class to any single Recipe instance, probably isn't a good idea.
I am trying to convert this data type to call out the method later on in another class to switch around layouts being made in other methods
if I understand what you are trying to do, you want a some mapping structure to some classes which have some pre-defined layouts.
Generally, this can be done with enums and OOP patterns
Have some base classes like this
public interface Layoutable {
int getLayout();
}
public enum Recipe {
ChileConLeche(R.layout.chile_con_leche),
Arroz(R.layout.arroz),
Enchiladas(R.layout.enchiladas),
Sopa(R.layout.sopa)
int layout;
Recipe(int layout) { this.layout = layout };
}
Ideally, you would want to use Fragments, but here is an example of an Activity structure
public abstract class RecipeActvity extends AppCompatActivity implements Layoutable {
protected Recipe recipe;
protected int getLayout() { return recipe.layout; }
}
public class ChileConLecheActivity extends RecipeActvity {
public ChileConLecheActivity() {
this.recipe = Recipe.ChileConLeche;
}
#Override
public void onCreate(...) {
setContentView(getLayout());
}
}
You can also combine this with a Map<Recipe, Class<RecipeActivity>>, from which you would use map.get(Recipe.ChileConCarne) to get the respective class element, for which you can startActivity() with

How can I assign instance of a class from an array to a class initializer in java?

In a Android application I am making I have an array of instances of a certain class I made, and later in the program I need to use the getter and setter methods from that class on an instance of the class from the array. Do I need to assign the instance of the class from the array to a new class initializer? Here is some code to clear this up:
Class
public class ProfileInformation {
private String console;
private String gamertag;
public String getConsole() {
return console;
}
public void setConsole(String console) {
this.console = console;
}
public String getGamertag() {
return gamertag;
}
public void setGamertag(String gamertag) {
this.gamertag = gamertag;
}
}
Array
ArrayList<ProfileInformation> ProfTags = new ArrayList<>();
Some instances of ProfileInformation are then added to arraylist, and then I get one of the instances from the arraylist and try to use getGamertag() to set it to a string:
ProfileInformation profNew = ProfTags.get(ProfTags.size()-1);
String example = profNew.getGamertag();
The problem is example will equal null. Why is this?
First, an Arraylist is a List, try not to confuse that with actual arrays.
Do I need to assign the instance of the class from the array to a new class initializer?
You don't need to get an element out of the Arraylist, no. You can chain many methods together
String example = ProfTags.get(ProfTags.size()-1).getGamertag();
example will equal null. Why is this?
For the same reason any object is null... You never set it equal to anything else
This code runs on my laptop:
public static void main(String[] args) {
ArrayList<ProfileInformation> ProfTags = new ArrayList<>();
element = new ProfileInformation();
element.setGamertag("Actual Gamer tag value");
ProfTags.add(element);
ProfileInformation profNew = ProfTags.get(ProfTags.size()-1);
String example = profNew.getGamertag();
}
Output is:
Actual Gamer tag value
I guess you didn't call setGamertag(String).

Java design for multiple values scenario

I have two combo-boxes as below,
whenever i click done button, i get the values from combo-box and store it in a object like below,
public class comboValues{
private String label1ComboString;
private String label2ComboString;
public String setLabel1Combo(String val){
this.label1ComboString = val;
}
public String setLabel2Combo(String val){
this.label2ComboString = val;
}
public void getLabel1Combo(){
return this.label1ComboString;
}
public void getLabel2Combo(){
return this.label2ComboString;
}
}
in a controller class i use,
comboValues obj = new comboValues();
obj.setLabel1Combo(label1ComboBox.getSelectionModel().getSelectedItem());
obj.setLabel2Combo(label2ComboBox.getSelectionModel().getSelectedItem());
For a design with two combo box the code looks simple. My doubt is what if the number of combo-boxes increases? with the above approach code will have
lot of lines. What is the design to overcome this problem and how can i implement that to this scenario?
You can have an array or an ArrayList of ComboBoxes. This way you can reference an arbitrary number of boxes. Your class would change to something like this:
public class ComboValues {
private String[] comboStrings;
...
public void setComboLabel(String label, int comboNum) {
comboStrings[comboNum] = label;
}
public void getComboLabel(int comboNum) {
return comboStrings[comboNum];
}
public void getComboBoxCount() {
return comboStrings.length;
}
}
...
String[] labels = ...
for (int i = 0; i < obj.getComboBoxCount(); i++) {
obj.setComboLabel(labels[i], i);
}
I can see from your approach that you want to add more combo-boxs and against it you want to do less code in java to handle those all.
You have option of implementing Array List collection and store multiple combo boxes inside this. so every time you will not be needed to create new object and it will become dynamic.
Hope it will clear your doubt. If you have not cleared please comment.

How to access ArrayList from another class in Android Java?

I'm new to Android and Java but do have some experience in Objective C and iPhone programming. I'm attempting to recreate an app I've already designed for the iPhone and am getting stuck on what should be a simple concept.
In my ParserHandler class I am parsing an XML from a server and putting the data into three separate ArrayList's. The parsing appears to be working fine. When I log and iterate through the ArrayList within my ParserHandler.java class it all works fine.
(List1.java class has a few string variables and I've declared it like so in the ParserHandler: private List1 theList = new List1(); )
for(int i = 0; i<dogArray.size(); i++){
theList = dogArray.get(i);
Log.i(TAG, "looping " + i + " " + theList.Name);
Log.i(TAG, "looping " + i + " " + theList.PhotoUrl);
Log.i(TAG, "looping " + i + " " + theList.Type);
}//this loops fine and has all the data
The dogArray is declared like so: public ArrayList<List1> dogArray = new ArrayList<List1>();
Now I want to access the dogArray from the class DogListView.java so in the onCreate method I attempt to do the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dog_list_view);
ParserHandler ph = new ParserHandler();
int d = ph.getNumberofDogs();
int m = ph.dogArray.size();
Log.i(TAG, "dog size is:" + d + "and:" + m);}
I've tried two different ways and both always return "0" in the log. However the correct size is always logged and all the data is there when the log comes from the ParserHandler.java class.
This is the accessor method in ParserHandler.java.
public int getNumberofDogs(){
return dogArray.size();
}
I'd prefer to access the dogArray via accessor method (as this seems to be best practice from what I've gathered) however I'm open to all suggestions.
Thanks in advance!!
EDIT 8/23/12
I ended up solving the problem by declaring my ArrayLists Static. I know this (and public) approach my not be ideal for OOP but i'm going with it. In my ParserHandler.java I declared
public static ArrayList<List1> dogArray = null;
public static ArrayList<List1> otherArray = null;
public static ArrayList<List1> catArray = null;
Then begin my SAX parser:
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
if (qName.equalsIgnoreCase("ArrayOfDataFeedAnimal")){
catArray = new ArrayList<List1>();
dogArray = new ArrayList<List1>();
otherArray = new ArrayList<List1>();
}else if(qName.equalsIgnoreCase("DataFeedAnimal")){
theList = new List1();
}
then the rest of my SAX parsing stuff happens. Lastly, from whatever class I want to access the array i simply do that in the static way by ParserHandler.dogArray.size() to get the size of the array. I can now manipulate the array any way i see fit from whatever class i need to get it.
I'm still unclear why creating an instance of the ParserHandler class hasn't worked for me with my parsed ArrayLists because when it worked fine when I tested with a simple int[].
hopefully this can help someone else in the future.
Thanks again for everyones feedback!
Cheers!
you can do it in two ways,
Create a setter/getter class
Make a public static method that returns ArrayList
First Method:
class name : myDataObject.java
private ArrayList myArrayList;
// setting the ArrayList Value
public void setArrayList ( ArrayList myArrayList )
{
this.myArrayList = myArrayList;
}
// getting the ArrayList value
public ArrayList getArrayList()
{
return myArrayList;
}
Second Method:
In ArrayList file, ( suppose class name is class A.java )
private static ArrayList myArrayList = null;
...
// assign arraylist
public static ArrayList getArrayList()
{
return myArrayList;
}
in the calling activity/class you can call it using following code,
private ArrayList newArrayList = null;
newArrayList = A.getArrayList();
You should not make the Methods static.Because that is not an OOP Design then.
There are 2 ways:
1). Either make the properties public. (Not a good practise either)
2). add getters and setters for ParserHandler class
class ParserHandler {
private List<List1> dogArray = new ArrayList<List1>();
public List<List1> getDogArray() {
return this.dogArray;
}
public void setDogArray(List<List1> dogArray) {
this.dogArray = dogArray;
}
}
Now access dogArray Like this
ph.getDogArray();
int m = ph.getDogArray().size();
Initially it will be 0 since it is an empty list. Use the setter method to set the array first
Note that in your oncreate you are doing a file operation in your ParserHandler which parses the xml file as your data. This could potentially block the UI thread if the ParserHandler is not processed in a separate thread. However if you processed in a separate thread then your int d = ph.getNumberofDogs(); may return 0 even if there are data in your xml because of race conditions between UI thread and the separate thread processing the parsing.
The best solution in my opinion is to create a listener when the parsing is done so that you are pretty sure that the processing is done before you access the size of the list.
add this in your ParserHandler class
class ParserHandler {
...... your original codes here
private OnParsingDoneListener mListener;
public void setOnParsingDoneListener (OnParsingDoneListener listener){
mListener = listener;
}
public static interface OnParsingDoneListener {
public void onParsingDone (List dogList);
}
}
make sure to call mListener.onParsingDone when youre done parsing xml data.
In Your onCreate()...
ParserHandler ph = new ParserHandler();
ph.setOnParsingDoneListener (new ParserHandler.OnParsingDoneListener(){
public void onParsingDone(List dogList){
// do whatever you want to the doglist
// at this point all parsing is done and dogList contains the data from xml
}
});

Categories