How to add data in aChartEngine to X-Axis - java

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

Related

How can i get the specific data from array

My question is when i store the data into array from sqlite database, how can i get it from specific position let say, my database contain "food, drinks,snack" how can i get the string "snack" from array.
String CatNameQuery = "SELECT * FROM Category";
db = new DBController(MainActivity.this);
SQLiteDatabase db3 = db.getReadableDatabase();
final Cursor cursor2 = db3.rawQuery(CatNameQuery, null);
{
List<String> array = new ArrayList<String>();
while(cursor2.moveToNext()){
String uname = cursor2.getString(cursor2.getColumnIndex("CategoryName"));
array.add(uname);
}
You need to iterate through the list in order to find the item you are looking for.
For example:
for (String s : array) {
if (s.equals("snack")) {
System.out.println("Found snack");
}
}
You can also use the contains method to check if the list contains "snack."
if (array.contains("snack")) {
System.out.println("Found snack");
}
Resource: ArrayList
Use the WHERE clause within your SELECT query. For example:
"SELECT * FROM Category WHERE CategoryName='snacks'"
This will fill your array with only items under the category 'snacks'.
List<String> array = new ArrayList<String>();
array.add("food");
array.add("drinks");
array.add("snack");
String result="";
if (array.contains("snack")) // avoid null pointer exception
{
int index =array.indexOf("snack") //find the index of arraylist
result=array.get(index);
}
You can find it by looping the array
List<String> arrobj= new ArrayList<String>();
arrobj.add("food");
arrobj.add("drinks");
arrobj.add("snack");
for (String value : arrobj) {
if (value.equals("snack")) {
System.out.println("Here is the snack");
}
}
if (array.size() > 0) {
int index = 0;
if (array.contains("Snacks")) {
index = array.indexOf("Snacks");
System.out.println(array.get(index));
}
}

How to set Hashmap value using model class

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())

Getting values from multi-dimensional array too slow

Good Day,
I've been working on an update in an android project, and came across an issue. I have to read questions from an SQLite database which i've done successfully by loading it into a multi-dimensional array as shown below in my database helper class:
public String getSome(int s,int t, String Table_Name){
String selectQuery = "SELECT * FROM " + Table_Name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int rows = cursor.getCount();
int num=0;
int col = 0;
String[][] base = new String[rows][13];
if (cursor.moveToFirst()) {
do {
for (col=0;col<13;++col ){
base[num][col] = (cursor.getString(col));}
++num;
} while (cursor.moveToNext());
return base[s][t];
}
return null;
}
With that done, i read the questions as such in my question class:
public void database_calls(){
setCourseTag(courseTag);
myDbHelper = new DataBaseHelper(getActivity());
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
String no= myDbHelper.getSome(ques,0, getCourseTag());
String qu = myDbHelper.getSome(ques,1, getCourseTag());
String a = myDbHelper.getSome(ques,2, getCourseTag());
String b = myDbHelper.getSome(ques,3, getCourseTag());
String c = myDbHelper.getSome(ques,4, getCourseTag());
String d = myDbHelper.getSome(ques,5, getCourseTag());
ans = myDbHelper.getSome(ques,6, getCourseTag());
img = Integer.parseInt(myDbHelper.getSome(ques,8, getCourseTag()));
exp = myDbHelper.getSome(ques,9, getCourseTag());
year = myDbHelper.getSome(ques,10, getCourseTag());
questionImage = myDbHelper.getSome(ques,11, getCourseTag());
length = myDbHelper.getMax(getCourseTag());
}
So recently, i tried to use the year column, (i.e, column 10) to qualify the questions chosen for each quiz session, so that the user may be able to select the questions from any year, he/she wants to attempt. In order to do this, i used a loop at the beginning of the activity to filter out only the required year past questions. Then i transferred the indices of each question to a set, bal , from where it is iterated and so on..
public void countYearQuestions(){
for(int y = 0; y < length; ++y){
//year = myDbHelper.getSome(y,10, getCourseTag());
if (selectedYear.equals(myDbHelper.getSome(y,10, getCourseTag())))
bal.add(y);
}
}
Here, length is the size of the entire question database, for the course, (indicated by getCourseTag()). The code works quite alright. But it takes a whole 8-9secs!! for the activity to load. Any help on how to reduce this loading time would be appreciated.
The way you're doing this is pretty efficient in slowing everything down (and your helper helps you with it a lot):
String no= myDbHelper.getSome(ques,0, getCourseTag());
In each such line you execute a query, create a 2D array holding the whole table and throw nearly everything away. And you fail to close the Cursor.
So you need 12 values from a table and read instead the whole table 12 times.

Passing empty string to db helper

I'm having some real problems passing a single string from my main activity to my db helper class. Here is my main activity method which I am returning a string 'answerSetId':
public String showNextRandomQuestion3() {
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion1();
//Get the question/text/answer Strings
List<String> questionStrings = listList.get(0); //question Strings
List<String> answerSetIds = listList.get(4);
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
//get answer description for randomly selected question
String questionString = questionStrings.get(rand);
String answerSetId = answerSetIds.get(rand);
questionView.setText(questionString);
return answerSetId;
}
I specifically want to use this 'answerSetId' in one method in my db helper class (as part of a query). Here is my current code - but it is capturing an empty string '[]':
public List<List<String>> getAnswers(String answerSetId) {
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
System.out.println(answerSetId);
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{TDESCR, ADESCR};
String selection = ASID+"=?";
String[] selectionArgs = new String[]{String.valueOf(answerSetId)};
Cursor c = db.query(TABLE_ANSWERS, columns, selection, selectionArgs, null, null, null);
if (c.moveToFirst()) {
do {
String textdescr = c.getString(c.getColumnIndex(TDESCR));
String answersdescr = c.getString(c.getColumnIndex(ADESCR));
array1.add(textdescr);
array2.add(answersdescr);
} while (c.moveToNext());
}
List< List<String> > listArray2 = new ArrayList< List<String> >();
listArray2.add(array1);
listArray2.add(array2);
return listArray2;
}
You can see that I want to use this method to retrun some more array data based on the query using the 'answerSetId' string - you'll also see where I have added a system print out which gives the empty value '[]'. But am only bothered about actually capturing the 'answerSetId' value from my main activity at this point.
How best to achieve this?
the arrays of data I will then pass onto my 'showNextAnswer()' method:
public String showNextAnswers() {
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
//get the data from the database
List<List<String>> listList = db.getAnswers(answerSetId);
//Get the question/text/answer Strings
List<String> textDescrs = listList.get(0); //question Strings
// List<String> answerDescrs = listList.get(1); //text strings
// System.out.println(answerSetId);
answerView3.setText(textDescrs.toString());
String textDescriptions = textDescrs.toString();
// String regex = "\\[|\\]";
// textDescriptions = textDescriptions.replaceAll(regex, "");
//Separate out the question/answer of text description associated with the randomly selected question
StringTokenizer textDescr = new StringTokenizer(textDescriptions, ",");
String first = textDescr.nextToken();
// String second = textDescr.nextToken();
// String third = textDescr.nextToken();
// String fourth = textDescr.nextToken();
subQuestionView1.setText(first);
// subQuestionView2.setText(second);
// subQuestionView3.setText(third);
// answerView3.setText(fourth);
// System.out.println(textDescr);
return null;
}
FYI - I call 'showNextRandomQuestion3()' from an onClick method when user clicks to go to a next question - a new random question and the related answers to that new question will appear each click:
NextQuestionButton.setOnClickListener(new OnClickListener(){;
#Override
public void onClick(View v) {
showNextRandomQuestion3();
showNextAnswers();
countQuestions();
}});
It looks like the solution is very simple. You just capture the return value of showNextRandomQuestion3(), since it returns answerSetId.
You will need to add a String parameter to the showNextAnswers() method to take the String that was returned from showNextRandomQuestion3().
So in your click event, you would do this:
NextQuestionButton.setOnClickListener(new OnClickListener(){;
#Override
public void onClick(View v) {
String answerSetId = showNextRandomQuestion3(); //get return value
showNextAnswers(answerSetId); //give the ID here
countQuestions();
}});
Then, just add the parameter to showNextAnswers(), and you're done!
public String showNextAnswers(String answerSetId) {
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
//get the data from the database
List<List<String>> listList = db.getAnswers(answerSetId); //This will work now!
//.................

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.

Categories