How to set Hashmap value using model class - java

I want to set Hashmap value using data from database and set it in model class, it doesn't work yet and shows empty data. Here is my code, get Data from database
private ArrayList<Kategori> categories;
private ArrayList<ChatRoom> chatroom_list;
private HashMap<Integer, ArrayList<ChatRoom>> chatrooms;
void getDataList(){
categories = new ArrayList<>();
chatrooms = new HashMap<>();
chatroom_list = new ArrayList<>();
try{
categories.clear();
cursor = db.rawQuery("SELECT * FROM kategori ORDER BY id ASC", null);
//cursor2 = db.rawQuery("SELECT * FROM chatroom ORDER BY id ASC LIMIT ", null);
Kategori kategori;
while (cursor.moveToNext()){
kategori = new Kategori();
kategori.setId(cursor.getInt(cursor.getColumnIndex("id")));
kategori.setNama(cursor.getString(cursor.getColumnIndex("nama")));
categories.add(kategori);
}
listAdapter.notifyDataSetChanged();
}catch(Exception e){
e.printStackTrace();
}
try{
chatroom_list.clear();
chatrooms.clear();
ChatRoom chatRoom;
for (int i=0;i<categories.size();i++){
cursor2 = db.rawQuery("SELECT * FROM chatroom WHERE status = '0' ORDER BY id ASC", null);
while (cursor2.moveToNext()){
chatRoom = new ChatRoom();
chatRoom.setId(cursor2.getInt(cursor2.getColumnIndex("id")));
chatRoom.setNama(cursor2.getString(cursor.getColumnIndex("nama")));
chatRoom.setDosen(cursor2.getString(cursor2.getColumnIndex("dosen")));
chatRoom.setInfo(cursor2.getString(cursor2.getColumnIndex("info")));
chatRoom.setId_kategori(cursor2.getInt(cursor2.getColumnIndex("id_kategori")));
if(categories.get(i).getId()==chatRoom.getId_kategori())
chatroom_list.add(chatRoom);
}
chatrooms.put(categories.get(i).getId(), chatroom_list);
}
}catch(Exception e){
e.printStackTrace();
}
}
when I check it, Hashmap just shows empty data, Thank you!

I suppose your bug is here:
if(categories.get(i).getId()==chatRoom.getId_kategori())
chatroom_list.add(chatRoom);
I guess getId() returns Integer, which is an object. Comparing objects with == fails in most cases. When it comes to Integer, it fails once the value is under -128 or over 127 (though this can be overriden. Also there are other circumstances when comparing integers using == can like magically fail or succed. Just don't do it).
Anyhow. Check if getId() returns Integer or Long. If so, change it to categories.get(i).getId().equals(chatRoom.getId_kategori())

Related

How to add data in aChartEngine to X-Axis

I have managed to obtain the data from the SQLite database and plot the actual values for the cube line chart view. Since the values should be plotted against the date which is also stored in the database in the format (dd-mm-yyyy) and is expected to be plotted on the x, I have difficulties how to actually realize that. Current parts of my code like this:
hapinessdb.class (SQLite database and the code to search for the date entries)
/**
* Return the date as a string and place it to ArrayList
* of strings.
* #return
*/
public ArrayList<String> getDataForDate() {
ArrayList<String> dateValues = new ArrayList<String>();
String[] columns = new String[]{KEY_ROWID, KEY_DATE, KEY_TIME,KEY_HAPPY,
KEY_NORMAL, KEY_SAD };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null,
null, null, null, null); //Read the data from columns with cursor
String result = "";
int iDate= c.getColumnIndex(KEY_DATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = c.getString(iDate);
dateValues.add(result);
}
return dateValues;
}
chart.class (method to obtain the ArrayList of date strings from happinessDb.class)
ArrayList<String> dateList = new ArrayList<String>();
private void dateDataFromDb() {
happinessDb dateInfo = new happinessDb(this);
try {
dateInfo.open();
} catch (SQLException e) {
e.printStackTrace();
}
ArrayList<String> data = dateInfo.getDataForDate();
dateInfo.close();
dateList = data; // Adds the dates to the String arrayList
My question is aimed towards, how to break the ArrayList of Strings and use them as part of the X-Axis series together with the bellow addHappyData method which plots the Integer values from ArralyList of Integers.
private void addHappyData() {
Integer x = 0;
for (Integer happy : happyList) {
mCurrentSeries.add(x += 20, happy);
}
}
Thank you for your time,review, possible review and answer on this post,
brg
Animus

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.

SQLite date query returns no record

I am developing an Android application where I search for records which are created after a given date. My code is some thing like this
public List<NPRMember> IncrementalData(String LastDtTime) {
List<NPRMember> results = new ArrayList<NPRMember>();
SQLiteDatabase db=getMyReadableDatabase();
String lastdt="datetime("+LastDtTime+")";
Cursor cursor = null;
try{
cursor = db.query(TABLE_NAME_NPR, new String[] { KEY_FULLNAME, KEY_FATHERNAME,
KEY_RCRD_SOURCE,KEY_RCRD_CRN_DATE},KEY_RCRD_CRN_DATE + ">? AND "+KEY_RCRD_SOURCE+">?",
new String[]{lastdt, "0"}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
NPRMember nprmem = cursorToMemberDetails(cursor);
results.add(nprmem);
cursor.moveToNext();
}
}catch(Exception e){
Log.e(APP_NAME, "An error occurred while searching for "+LastDtTime+": "+e.toString(), e);
}finally{
if(cursor!=null && !cursor.isClosed()){
cursor.close();
}
}
return results;
}
The query does not return any value, although I have at least one record with KEY_RCRD_CRN_DATE 2013-07-25 18:59:19
The LastDtTime passed as parameter has value 2013-07-25 14:46:03.
One interesting thing is if I run the query at SQLite command prompt it returns the deisred record.
SELECT fullname, fathername, .... rcrdsource, rcrdcrtndate FROM nprmembers WHERE rcrdcrtndate>'2013-07-25
14:46:03' AND rcrdsource>0;
Any help would be appreciated.
Thanks
The parameter value (in lastdt) is wrong.
What you want is the string 2013-07-25 18:59:19, but you are actually using the string datetime(2013-07-25 18:59:19).
The letter d comes after 2, so no record matches.
Change the initialization of lastdt to:
String lastdt=LastDtTime;

Why am I getting NullPointerException here?

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.

display data in TextView

public List<UserDataHelper> getData() {
List<UserDataHelper> list = new ArrayList<UserDataHelper>();
String selectQuery = "SELECT * FROM " + TABLE;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
UserDataHelper quest = new UserDataHelper();
quest.setID(cursor.getInt(0));
quest.setName(cursor.getString(1));
quest.setSent(cursor.getInt(2));
quest.setRecieved(cursor.getInt(3));
quest.setTotal(cursor.getInt(4));
quest.setTimeSpent(cursor.getString(5));
list.add(quest);
} while (cursor.moveToNext());
}
return list;
}
This is for a listView but I want to fetch data individually and display it in textView. How can I achieve that? There are a lot of tutorials for listviews but not for textViews so can someone help me out please.
try this
for (UserDataHelper user:getData())
{
textView.append(user.getID()+" "+user.getName()
+" "+user.getRecieved()+" "+user.getSent()
+" "+user.getTimeSpent()+" "+user.getTotal()+"\n");
}
You could simply use the class object to set/get values, do following for string values:-
textView.setText(quest.getName());
and for the integer values make sure to use one
of the following:-
textView.setText(""+quest.getId());
or
textView.setText(String.valueOf(integer));

Categories