NullPointerException in LogCat? - android

Whenever I introduce the array, i get this error. I tried different array types...but no luck.
public class Classifytestclass2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
int test2[] = null;
for(int i=0;i<50;i++){
test2[0]=1;
}
}
}
edit:
forgot to mention, the entire app crashes (force close.)

It's normal to get a NullPointerException because you didn't initialize the array(). You have to do something like this:
int test2[] = new int[50];
to initialize an array with 50 elements.

what do you want to do with this
enter code here
for(int i=0;i<50;i++){
test2[0]=1;
}
As this code sets the value of test2[0]=1; every time loop moves.
Please let me know, what exactly you want?

Related

ArrayList Length gets 0 in Singleton

I am using a singleton for fetching data from a web service and storing the resulting data object in an ArrayList. It looks like this:
public class DataHelper {
private static DataHelper instance = null;
private List<CustomClass> data = null;
protected DataHelper() {
data = new ArrayList<>();
}
public synchronized static DataHelper getInstance() {
if(instance == null) {
instance = new DataHelper();
}
return instance;
}
public void fetchData(){
BackendlessDataQuery query = new BackendlessDataQuery();
QueryOptions options = new QueryOptions();
options.setSortBy(Arrays.asList("street"));
query.setQueryOptions(options);
CustomClass.findAsync(query, new AsyncCallback<BackendlessCollection<CustomClass>>() {
#Override
public void handleResponse(BackendlessCollection<CustomClass> response) {
int size = response.getCurrentPage().size();
if (size > 0) {
addData(response.getData());
response.nextPage(this);
} else {
EventBus.getDefault().post(new FetchedDataEvent(data));
}
}
#Override
public void handleFault(BackendlessFault fault) {
EventBus.getDefault().post(new BackendlessFaultEvent(fault));
}
});
}
public List<CustomClass> getData(){
return this.data;
}
public void setData(List<CustomClass> data){
this.data = data;
}
public void addData(List<Poster> data){
this.data.addAll(data);
}
public List<CustomClass> getData(FilterEnum filter){
if(filter == FilterEnum.NOFILTER){
return getData();
}else{
// Filtering and returning filtered data
}
return getData();
}
}
The data is fetched correctly and the list actually contains data after it. Also, only one instance is created, as intended. However, whenever I call getData later, the length of this.data is 0. Because of this I also tried it with a subclass of Application holding the DataHelper object, resulting in the same problem.
Is there a good way of debugging this? Is there something like global watches in Android Studio?
Is there something wrong with my approach? Is there a better approach? I am mainly an iOS developer, so Android is pretty new to me. I am showing the data from the ArrayList in different views, thus I want to have it present in an the ArrayList as long as the application runs.
Thanks!
EDIT: Example use in a list view fragment (only relevant parts):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filter = FilterEnum.NOFILTER;
data = DataHelper.getInstance().getData(filter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
customClassListAdapter = new customClassListAdapter(getActivity(), data);}
EDIT2: Added code where I fetch the data from Backendless, changed reference of DataHelper to reference of data in first EDIT
EDIT3: I usa a local EventBus for notifying the list view about the new data. This looks like this and works (initially the data gets populated, but after e.g. applying a filter, the ArrayList I get with getData is empty):
#Subscribe
public void onMessageEvent(FetchedDataEvent event) {
customClassListAdapter.notifyDataSetChanged();
}
Try instead of keeping reference to your DataHelper instance, keeping reference to your list of retrieved items. F.e. when you first fetch the list (and it's ok as you say), assign it to a class member. Or itarate through it and create your own array list of objects for future use.
Okay I finally found the problem. It was not about the object or memory management at all. Since I give the reference on getData to my ArrayAdapter, whenever I call clear (which I do when changing the filter) on the ArrayAdapter, it empties the reference. I basically had to create a copy of the result for the ArrayAdapter:
data = new ArrayList<>(DataHelper.getInstance().getData(filter));
I was not aware of the fact that this is a reference at all. So with this the data always stays in the helper entirely. I only did this because this:
customClassListAdapter.notifyDataSetChanged();
does hot help here, it does not call getData with the new filter again.
Thanks everyone for your contributions, you definitely helped me to debug this.
It is likely that getData does get called before the data is filled.
A simple way to debug this is to add (import android.util.Log) Log.i("MyApp.MyClass.MyMethod", "I am here now"); entries to strategic places in fetchData, addData and getData and then, from the logs displayed by adb logcat ensure the data is filled before getData gets called.

Dynamic Allocation of Array doesn't work for ArrayAdapter while assigning it for Spinner in Android

I am really facing a problem here to create a Spinner widget in Android. The goal is to populate a Spinner with data that i will dynamically retrieve from a source.
Now I am able to create a spinner with a data source that is implicitly declared in the program. But when ever i am trying to fetch the data from a dynamically created array, the apps throws a Force Close.
I will paste some demo examples to explain my problem here!
String[] SSID = new String[15];
String[] Data = {"Captain","America","Hulk","Ironman","Thor"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
addDevDialogue = new Dialog(this);
addDevDialogue.setContentView(R.layout.popup);
concat();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogue();
}
});
}
public void concat()
{
for(int i=0;i<5;i++)
{
SSID[i]=Data[i];
}
}
public void dialogue()
{
addDevDialogue.setTitle("Movies List");
addDevDialogue.setCancelable(true);
addDevDialogue.show();
spinList2 = (Spinner)addDevDialogue.findViewById(R.id.spinner2);
ArrayAdapter<String> listAdapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked, SSID);
spinList2.setAdapter(listAdapter2);
}
The above code throws an error when ever I try to open the dialogue box.
I have tried this same sample with a pre-defined data source in place of "SSID" which yields a error free output!
I cannot understand why 'SSID[]' array doesnt work when I define it to the ArrayAdapter.
Any Insight will help!!!
You are call calling show() before populating adapter so call
addDevDialogue.show();
after
spinList2.setAdapter(listAdapter2);
UPDATE :
Once change size of SSID
String[] SSID = new String[Data.length];
Hope this will helps you.
Your string array String[] Data = {"Captain","America","Hulk","Ironman","Thor"}; is declared with 5 elements (index 0-4)
In your loop you loop 6 times
public void concat()
{
for(int i=0;i<5;i++)
{
SSID[i]=Data[i];
}
}
Which probably causes an Index out of bounds exception. Change your loop to this
public void concat()
{
for(int i=0;i<4;i++)
{
SSID[i]=Data[i];
}
}
#swarna: You are allocating a fixed array of 15 elements, then populating only 5 elements. The array adapter is probably getting tripped with the other 10 elements which have not been initialized. Suggest you make your SSID array to have only 5 elements OR if this is a dynamically determined value, you could keep ArrayList and keep adding to it. Then, when setting up the adapter do this:
YourObjList.add("one")
YourObjList.add("two")
YourObjList.add("three")
String[] SSID = YourObjList.toArray(new YourObjList[YourObjList.size()]);
ArrayAdapter<String> listAdapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked, SSID);
spinList2.setAdapter(listAdapter2);
This will allow variable list sizes.
Hope this helps you

use array as a public array to save random number generation

I want to generate random number without duplicate, and i get this code
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random randomGenerator = new Random();
int random = randomGenerator.nextInt(16)+1;
if (!numbers.contains(random))
{
numbers.add(random);
}
I want to use this code to generate an random id to choose which question to be displayed from database. When i answer the question, it should be generate a new random id. But if I used all the code above, the array becomes a new one, and it will not know what id has been generated before.
If I put the ArrayList<Integer> numbers = new ArrayList<Integer>(); on onCreate and the other codes in a public int random(), the numbers in cannot read the array that i have created on onCreate.
I want to ask, can I create the ArrayList<Integer> as a public array, so i just should declare it once on onCreate method and the whole class can use this array.
You can declare the ArrayList outside the onCreate method and initialize it inside that method.
Then happily use it in your activity.
So, this:
ArrayList<Integer> numbers = new ArrayList<Integer>();
goes UP in your code, after the class declaration (after the first { in your class)
and this:
Random randomGenerator = new Random();
int random = randomGenerator.nextInt(16)+1;
if (!numbers.contains(random))
{
numbers.add(random);
}
Can be put in your onCreate method
Declare your array separately from the handling it, for instance as the global class one.
public class ClassName {
ArrayList<Integer> name;
#Override
public void onCreate(...){
name = new ArrayList<Integer>();
}
public void yourMethod(...){
//your operations
}
}
In that way you can keep your array. I wouldn't create a public array, because if you define it as global and private, you have an access to it from the whole class. If you want to get access from other classes in a package, just create usual method:
public ArrayList<Integer> getArrayList(){
return name;
}
btw, I'd use Set<Integer> (here are docs) to solve that problem, because it doesn't allow you add duplicated items, so you may get rid of redundant if statement.

Cannot restore Object from Instance state: parsing error

I am trying to restore an array of Objects from a savedInstanceState. I added each one to the Bundle individually here: (rhythm is the array of Objects)
#Override
public void onSaveInstanceState(Bundle outState){
outState.putInt("numParts",rhythm.length);
for(int index = 0;index<rhythm.length;++index){
outState.putSerializable(""+index,rhythm[index].beat);
}
super.onSaveInstanceState(outState);
}
When the onRestoreInstanceState() method is called, I try to assign my rhythm array with the Objects from the Instance State here: (it isn't null)
#Override
public void onRestoreInstanceState(Bundle savedInstanceState){
rhythm = new Part[savedInstanceState.getInt("numParts")];
for(int index = 0; index<rhythm.length;++index){
Object middleMan =savedInstanceState.getSerializable(""+index);
if(middleMan==null){
System.out.println("It's null...");
}
rhythm[index]=(Part) middleMan;
}
}
It throws a ClassCastException when I parse to a Part every time. Part implements Serializable. Why is it not allowing me to parse? Will I need to do custom serialization?
Please help!
I am guessing that Part is a type that you have created? So instead of treating Part as an array
rhythm = new Part[savedInstanceState.getInt("numParts")];
You want to instantiate a new Part object like so:
rhythm = new Part(savedInstanceState.getInt("numParts"));
Other assumptions:
rhythm is a member variable
The constructor for Part takes a single integer
Okay I just did it as the whole array and it worked... I don't really know why, but it did. Thanks for giving me the idea to just pass the whole array. #Error 454

random number generator

I m trying to make a random number generator in android. My code has to start generating numbers in sets of 3 after clicking the "generate" button. So far i've coded a generator that can produce finite sets of 3 numbers each. What i want to create is a dynamic generator that keeps generating numbers.CODE:
`
public class Plot2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Random myRandom = new Random();
Button buttonGenerate = (Button)findViewById(R.id.generate);
final TextView textGenerateNumber = (TextView)findViewById(R.id.generatenumber);
buttonGenerate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<Object> Arry1 = new ArrayList<Object>();
for(int i=0;i<5;i++){
ArrayList<Integer> Arry = new ArrayList<Integer>();
for(int k=0;k<3;k++){
Arry.add(myRandom.nextInt(100));
}
Arry1.add(Arry);
}
textGenerateNumber.setText(String.valueOf(Arry1));
}
});
}
}
Do the same process in a loop and update an array from a background thread. For background thread look below link this may help you.
However if you don't want to generate frequently, Put a sleep() in your background thread for a second and than let it update your Array.
http://developer.android.com/reference/android/os/AsyncTask.html
Happy coding,
Krio
Article which may help,
http://www.dailygeek.de/using-asynctask-to-update-a-listactivity/
Above article shows how you can update your ListActivity in similar fashion you may update your Array.
Lets say create an activity which has AsycTask, and create a separate class such as,
public class RandomNumbers{}
Above class will have an Array list of numbers being generated,
And update this class's object from Background which eventually available to your UI Thread too. I hope I and clear enough.

Categories

Resources