Why am I getting NullPointerException here? - java

I have this code in one of my activity's onCreate Method
GetNews newsReporter = new GetNews(getApplicationContext());
try{
News[] allNews = newsReporter.getAllNews();
Log.d("News Count", String.valueOf(allNews.length));
String[] timestamps = new String[allNews.length];
String[] texts = new String[allNews.length];
for(int i=0;i<allNews.length;i++)
{
// timestamps[i] = allNews[i].getNewsTime();
texts[i] = allNews[i].getNewsText();
// Log.d("TimeStamp", timestamps[i]);
Log.d("Text", texts[i]);
}
}catch(Exception e){
Log.e("Error News", e.toString());
}
News Count Displays 6 in Logcat, which means News[] is not null.
But I receive NullPointerException on Line texts[i] = allNews[i].getNewsTime();
this is my News Class
public class News {
private int id;
private String timestamp;
private String text;
public News(int i,String t, String ti)
{
this.id=i;
this.text = t;
this.timestamp = ti;
}
public String getNewsTime()
{
return this.timestamp;
}
public String getNewsText()
{
return this.text;
}
}
P.S. News is stored in a SQLitedatabase, when i pulled the database from my DDMS, it contains all 6 rows with valid values none of them is null.
Edit:
This is my GetAllNews Method
public News[] getAllNews(){
SQLiteDatabase db = ConMan.OpenDBConnection();
try{
Cursor cursor = db.query(News_Table, Columns, null, null, null, null, null);
if(cursor!=null)
{
cursor.moveToFirst();
}
News[] allNews = new News[cursor.getCount()];
int i =0;
while(cursor.isLast()){
allNews[i] = new News(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2));
cursor.moveToNext();
i++;
}
db.close();
ConMan.close();
return allNews;
}catch(Exception e)
{
Log.e("News DB Errors", e.getMessage());
}
return null;
}

The problem is in the newsReporter.getAllNews() method. Looks like it is returning the array without the value initialized.
News[] allNews = newsReporter.getAllNews();
Meaning,
allNews.length might get you some value. But at each index, you are missing the value or at least one or more of the indexes are missing the value in the array.
Do the printing like below to see if you have values
for (News news : allNews)
System.out.println(news);
Looks like it is not going into the following block at all.
while(cursor.isLast()){
allNews[i] = new News(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2));
cursor.moveToNext();
i++;
}
Check whether cursor.isLast() method is returning true to get into this loop.

texts[i] = allNews[i].getNewsText();
Most possibly, allNews[someIndex] is null. when called getnewsText() on null throws NPE.
best test is to output allNews[i] or check if it isnull.
System.out.println(allNews[i]==null)

An array of size 6 can have 6 null references. Print each of your News objects in allNews, I bet 10 Obamas that at least one position in the array is null.

You are saying that allNews[] is not null, so it must be that News[] contains a null, so that allNews[i].getNewsText() throws the exception.

Related

Array becoming empty after getting out of a for loop

I'm learning to program in Java for Android Studio. I'm working with a Parse.com query downloading information. I store the information inside an array of a costume object called MyData. When I'm storing the information I can log the content of the array and it has the correct info. But latter when I try to use the same array, if I use the .length function it says it's null. And if I try to retrieve any of the information, it's empty.
This I my object:
public class MyData {
Integer gluc;
Integer insulinaV;
Date fec;
Integer alimento;
String comentarios;
public MyData(Integer gluc, Integer insulinaV, Date fec, Integer alimento, String comentarios) {
this.gluc = gluc;
this.insulinaV = insulinaV;
this.fec = fec;
this.alimento = alimento;
this.comentarios = comentarios;
}
public Integer getGluc() {
return gluc;
}
public Integer getInsulinaV() {
return insulinaV;
}
public Date getFec() {
return fec;
}
public Integer getAlimento() {
return alimento;
}
public String getComentarios() {
return comentarios;
}
}
So, to retrieve the information I use array[I].getWhatever(), this is how I store the information:
public void downloadInformation() {
user = ParseUser.getCurrentUser();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Glucosa");
query.whereEqualTo("usuario", user);
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null && objects.size() > 0) {
Log.d("score!", "Objects Retrived");
Log.d("size", String.valueOf(objects.size()));
int i = 0;
indexsize = 0;
for (ParseObject object : objects) {
dataArray = new MyData[objects.size()];
dataArray[i] = new MyData(object.getInt("glucosa"), object.getInt("insulina"), object.getDate("fecha"), object.getInt("Alimentos"), object.getString("Comentarios"));
String alimentosexiste = dataArray[i].getAlimento().toString();
Log.i("Is Empty or Not=", alimentosexiste);
indexsize = indexsize+1;
i++;
}
} else {
Log.d("failed", "error");
}
}
});
}
In my logcat I'm getting "Score! Objects retrieved" and "Size: 22", also I get a list with all 22 elements of the "Is Empty or Not" Log. So far so good.
Then, In my attempt to move from this activity to another, I try to save the dataArray with:
public void saveInformation() {
int j = indexsize;
Log.i("size of index?", String.valueOf(indexsize));
for (int i=0; i<=j; i++) {
Log.i("index", String.valueOf(i));
alimentosVal = dataArray[i].getAlimento();
comentariosVal = dataArray[i].getComentarios();
glucVal = dataArray[i].getGluc();
insulinaVal = dataArray[i].getInsulinaV();
fecVal = dataArray[i].getFec();
}
SQLiteDatabase myGlucosebase = this.openOrCreateDatabase("GlucoseEvents", MODE_PRIVATE, null);
myGlucosebase.execSQL("CREATE TABLE IF NOT EXISTS glucoseevents (alimentos INT(2), comentarios VARCHAR, gluc INT(4), insulinv INT(4), fec DATETIME)");
myGlucosebase.execSQL("INSERT INTO glucoseevents (alimentos, comentarios, gluc, insulinv, fec) VALUES (alimentosVal, comentariosVal, glucVal, insulinaVal, fecVal) ");
}
And even do I printed before the content of the array with index [0] (so I'm sure the information got stored in the array), I get the following error:
Attempt to invoke virtual method 'java.lang.Integer com.parse.starter.MyData.getAlimento()' on a null object reference
I've seen that the problem is that I'm pointing to an empty element, but it was working before, how can I do this?
(Data array is declared at the beginning, below the class name as: MyData[] dataArray;)
Thanks!
dataArray = new MyData[objects.size()]; should be outside the for loop
Your class MyData does not have a "dataArray". At least not in the example code you give above.

While loop stops, but doesn't continue with the next statements [duplicate]

This question already has answers here:
Iterate through rows from Sqlite-query
(7 answers)
Closed 6 years ago.
I used a While Loop to add the values of an SQL table into an ArrayList using the Cursor class, but at the moment of adding all the values, the While Loop stop giving values but, at the same time, it doesn't continue with the next statements. I used the condition that: if inside the While Loop the Cursor has null value, it needs to stop (c != null), it stops but doesn't continue. I used Log.i to see if I receive values after the While Loop, but I don't get any value. Here is the code I am using:
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
try{
SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("Notes",MODE_PRIVATE, null);
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS notes (name VARCHAR)");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('LUIS GA')");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('LUIS')");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('GA')");
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);
int nameIndex = c.getColumnIndex("name");
notes.add("example note");
c.moveToFirst();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
int i = 0;
Log.i("Bucefalo", Integer.toString(i));
while(c != null){
Log.i("Dato",c.getString(nameIndex));
notes.add(c.getString(nameIndex));
c.moveToNext();
i++;
Log.i("Luis", Integer.toString(i));
};
i = 2;
Log.i("Napoleon", Integer.toString(i));
String Hercules = "Hercules";
Log.i("Hercules",Hercules);
}
catch (Exception e){
e.printStackTrace();
}
The values that I receive in the Logcat using Log.i, are "Bucefalo" and "Luis" (the one inside the While Loop), but I don't receive the value "Napoleon" and "Hercules", Why? How I can fix this? Thank you
This is the best way to iterate through the cursor
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
...
}
} finally {
cursor.close();
}
Aside the wrong usage of the cursor, this code
while(c != null){
...
c.moveToNext();
}
should actually never stop looping.
You see: you have a local reference c there. It is not null. Calling a method on a reference absolutely can not turn the reference itself to be null. Only an assignment like c = null would you get there.
In other words: your claims about observed behavior are not supported by the code you are posting.
moveToNext returns a boolean value, but at the same time it goes ahead and moves the cursor.
Use like this,
Cursor c = sqLiteDatabase.rawQuery(....);
while (c.moveToNext()) {
}
or
do {
} while (c.moveToNext());
There is a syntax error in your while Loop.it should be below
while (expression)
{
statemets(s)
}
and moreover you are using cursor badly.
you can use
cur.moveToFirst();
while (cur.isAfterLast() == false) {
.............
............
cur.moveToNext();
}
cur.close();
or
Cursor cursor = db.rawQuery(...);
if (cursor.moveToFirst()) {
do {
...
} while (cursor.moveToNext());
}
or
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
...
}
} finally {
cursor.close();
}

How can i insert one array list of data to another array list which some fields are same?

I am stuck with small problem.I have two ArrayLists and I want to compare some values in the ArrayLists.
List<TriangleInfo> arrayList = dataGridTable.selectLastvalueNoAverage(equipid);
if fire this query i have get one arraylist.
public List<TriangleInfo> selectLastvalueNoAverage(int equipid)
{
List<TriangleInfo> list = new ArrayList<TriangleInfo>();
cursor = database.query(DatabaseHelper.DGADATATABLE, columns, "equipid = '"+equipid+"' ", null, null,null, "dateadded DESC");
while(cursor.moveToNext())
{
triangleInfo = new TriangleInfo();
triangleInfo.setDgaid(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.DGAID)));
triangleInfo.setDateadded(cursor.getString(cursor.getColumnIndex(DatabaseHelper.DATEADDED)));
triangleInfo.setCh4(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.CH4)));
triangleInfo.setC2h2(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.C2H2)));
triangleInfo.setC2h4(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.C2H4)));
list.add(triangleInfo);
}
cursor.close();
return list;
}
In the same way the second query is
List<ThresholdsInfo> Threshold = thresholdsTable.selectAllRecords();
Here also I get one ArrayList.
public List<ThresholdsInfo> selectAllRecords()
{
List<ThresholdsInfo> list = new ArrayList<ThresholdsInfo>();
cursor = database.query(DatabaseHelper.THRESHOLDS, columns, null, null, null, null, null);
while(cursor.moveToNext())
{
info = new ThresholdsInfo();
info.setThresholdid(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.THRESHOLDID)));
info.setH2(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.H2)));
info.setCh4(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.CH4)));
info.setC2h2(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.C2H2)));
info.setC2h4(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.C2H4)));
info.setC2h6(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.C2H6)));
info.setCo(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.CO)));
info.setCo2(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.CO2)));
info.setO2(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.O2)));
info.setN2(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.N2)));
info.setTdcg(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.TDCG)));
list.add(info);
}
cursor.close();
return list;
}
So my problem is I have to compare the ch4,c2h2,c2h6 values in both ArrayList. So I did like
public String ThresholdCheck(List<TriangleInfo> arrayList)
{
thresholdsTable = new ThresholdsTable(context);
int ch4=0,tch4=0;
String color = "Black";
List<ThresholdsInfo> Threshold = thresholdsTable.selectAllRecords();
for(TriangleInfo info : arrayList)
{
info.getC2h2();
}
for(ThresholdsInfo info : Threshold)
{
tch4 = info.getCh4();
}
if(ch4>=tch4)
{
}
return color;
}
I wrote like that but that is long procedure. Please tell me is there any simple solution.

Strange NullPointerException error in android when using custom suggestions provider

I am trying to make custom search suggestions in my app. I’ve started from documentation and Searchable dictionary example. However, this example isn’t so good for me so I’ve started with some tests to find out exactly how to make it, because there is not much tutorials in the Internet also.
Generally my app has right now 2 databases – one normal and second with less number of columns – FTS3. What I would like to achieve is to connect suggestions provider to this FTS3 table.
What I was trying to do was to now was, using simple function, return in suggestions whole DB (around 200 records) after typing any letter in search box. I know about limit 50 records, but I don’t think it is the problem.
This are fragments from Provider’s code. What I found out, that when you type in text, provider goes to option SEARCH_SUGGEST:
// UriMatcher stuff
private static final int SEARCH_WORDS = 0;
private static final int GET_WORD = 1;
private static final int SEARCH_SUGGEST = 2;
private static final int REFRESH_SHORTCUT = 3;
private static final UriMatcher mUriMatcher = buildUriMatcher();
/**
* Builds up a UriMatcher for search suggestion and shortcut refresh queries.
*/
private static UriMatcher buildUriMatcher() {
Log.d(TAG,"urimatcher");
UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
// to get definitions...
matcher.addURI(AUTHORITY, "mydb", SEARCH_WORDS);
matcher.addURI(AUTHORITY, "mydb/#", GET_WORD);
// to get suggestions...
matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);
return matcher;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch (mUriMatcher.match(uri)) {
case SEARCH_SUGGEST:
Log.d(TAG,"SEARCH_SUGGEST");
if (selectionArgs == null) {
throw new IllegalArgumentException(
"selectionArgs must be provided for the Uri: " + uri);
}
return getSuggestions(selectionArgs[0]);
case SEARCH_WORDS:
Log.d(TAG,"SEARCH_WORDS");
if (selectionArgs == null) {
throw new IllegalArgumentException(
"selectionArgs must be provided for the Uri: " + uri);
}
return search(selectionArgs[0]);
case GET_WORD:
Log.d(TAG,"GET_WORD");
return null;
default:
Log.d(TAG,"default");
throw new IllegalArgumentException("Unknown Uri: " + uri);
}
}
private Cursor getSuggestions(String query) {
String[] columns = { MyDBAdapter.KEY_TITLE,MyDBAdapter.KEY_ID};
Log.d(TAG,"query1: " + query);
try{
Cursor tmp = MyDB.getAllEntriesFTS(false, columns,
null, null, null, null, MyDBAdapter.KEY_TITLE, null, query);
Log.d(TAG,"cursor: " + Integer.toString(tmp.getCount()));
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
return tmp;
}
In getSuggestions I put code that should generally work, but it doesn’t. Doesn’t work only when used here. When I used it in other activity to get cursor for listview everything was fine. Here it returns my NullPointerException.
So getting deeper I put also some Log tags in getAllEntriesFTS method and this method looks like this:
public Cursor getAllEntriesFTS(boolean distinct, String[] result_columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit, String query) {
Log.d(TAG,"query db: " + query);
String[] columns = { MyDBAdapter.KEY_TITLE, MyDBAdapter.KEY_ID};
Log.d(TAG,"columns: " + Integer.toString(result_columns.length));
Cursor allRows = null;
try{
allRows = db.query(distinct, DATABASE_TABLE_FTS, columns,
null, null, null, null, MyDBAdapter.KEY_TITLE, null);
Log.d(TAG,"OK");
}
catch(Exception e)
{
Log.d(TAG, e.toString());//it always goes there with NullPointerExceptionwhen used in provider
}
Log.d(TAG,Integer.toString(allRows.getCount()));
return allRows;
}
So, generalny speaking it should return cursor to whole DB, but instead it throws In place where it shouldn’t NullPointerException.
Can someone please tell me what am I doing wrong and how it should be done?
Thank's to JB Nizet I was able to find my mistake. I was thinking I've studied Google's example good, but I was wrong.
The problem was lack of database open before cursor call. It should look like this:
private Cursor getSuggestions(String query) {
String[] columns = { MyDBAdapter.KEY_TITLE,MyDBAdapter.KEY_ID};
Log.d(TAG,"query1: " + query);
try{
MyDB.open();
Cursor tmp = MyDB.getAllEntriesFTS(false, columns,
null, null, null, null, MyDBAdapter.KEY_TITLE, null, query);
MyDB.close();
Log.d(TAG,"cursor: " + Integer.toString(tmp.getCount()));
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
return tmp;
}
Thank you all for showing me it.

how to show random data from the data base file .i am getting confusion as i am getting errors

i am new to android programming.i looking to make a question and answer application.in this application i fetch the data from the data base file as follows
public String makeatext(String My_database_table, int i) {
SQLiteDatabase myDB = getDatabase();
String results = new String();
Cursor cur = null;
try {
String firstColumn = "questions";
cur = myDB.query(true, My_database_table,
new String[] { firstColumn }, null, null, null, null, null,
null);
int iquestion = cur.getColumnIndex(firstColumn);
if (cur.moveToPosition(i)) {
results = results + cur.getString(iquestion) + "\n";
}
return results;
}
catch (Exception e) {e.printStackTrace();
Log.e("ERROR", "ERROR in Make test file :" + e.toString());
e.printStackTrace();
// TODO: handle exception
}finally{
cur.close();
}
return results;
}
and in my main activity class i am initializing random value as
Random questions;
questions = new Random();
int Rnumber;Rnumber=0;
Rnumber=questions.nextInt(3);
and after setting the random value i am calling the function as
String shoow = myDb.makeatext(levels, Rnumber);
now i am getting a question but .what i want is as every time user opens application i want to show random questions.how to do this any suggestions will be very good to me
thanks,
maddy
move line
questions = new Random();
to onCreate()
and
Rnumber=questions.nextInt(3); //Rnumber can get 0, 1, 2 values
to onResume
Do You have only 3 questions????

Categories