ORMLite get Could not get next result for class Error - android

i'm using ORMlite library in android and i get this error random and i dont know whats that and how to modrate:
Caused by: java.lang.IllegalStateException: Could not get next result for class [Ljava.lang.String;
at com.j256.ormlite.stmt.SelectIterator.next
i get this error when i'm using this method to get single column :
public static List getSingleColumn(String query) {
List<String> columnes = null;
try {
columnes = G.CATEGORY.queryRaw(query, new RawRowMapper<String>() {
#Override
public String mapRow(String[] columnNames, String[] resultColumns) throws android.database.SQLException {
return resultColumns[0];
}
}).getResults();
} catch (SQLException e) {
e.printStackTrace();
}
return columnes;
}
or this code:
List unread_messages = G.DBHELPER.getSingleColumn("SELECT SUM(read_status) FROM messageslist");

Try change method to this:
public static String getSingleColumn(String query) {
String columnes = null;
try {
columnes = G.CATEGORY.queryRaw(query, new RawRowMapper<String>() {
#Override
public String mapRow(String[] columnNames, String[] resultColumns) throws android.database.SQLException {
return resultColumns[0];
}
}).getFirstResult();
} catch (SQLException e) {
e.printStackTrace();
}
return columnes;
}

Related

Android Database in AsyncTask in Fragment

I have a DbHelper Class which extends SQLiteOpenHelper.
I do Some Download and update the Database inside an Asynctask.
Inside an activity i got no problem and code works fine,
but when i use the ASynctask class inside a fragment problems occurs.
usually wherever i use a context an Exception happened, Especially with dbHelper.ClearDB()
Error:
DB Read ERROR:java.lang.NullPointerException:
Attempt to invoke virtual method 'java.util.ArrayList x.database.DBHelper.getAllItems()' on a null object reference
Here's the code :
public class StaggeredFragment extends Fragment
{
private DBHelper dbHelper;
private SharedPreferences preferences;
private ArrayList<DisItem> savedData;
private final String LINK1 = "myLink";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbHelper = new DBHelper(getActivity().getApplicationContext());
preferences = getActivity().getSharedPreferences("pid", Context.MODE_PRIVATE);
new LoaderAsyncTask("ALL").execute();
}
class LoaderAsyncTask extends AsyncTask<Void, Void, Boolean> {
String brand;
LoaderAsyncTask(String brand) {
this.brand = brand;
}
#Override
protected Boolean doInBackground(Void... params) {
Log.d(TAG,"RUnning");
String fetched;
InputStream is = null;
//Store Current Data before Sync
try {
savedData = dbHelper.getAllItems();
}catch (Exception e)
{
Log.d(TAG,"DB Read ERROR:"+e.toString());
return false;
}
try {
dbHelper.ClearDB();
}catch (Exception e)
{
Log.d(TAG,"DB Clear ERROR:"+e.toString());
return false;
}
// Open connection to server for html
try {
is = urlStream(LINK1);
} catch (Exception e) {
Log.e(TAG, "HTTP Error " + e.toString());
return false;
}
// Fetch HTML Data
try {
fetched = readIt(is);
// Log.d("fetched", fetched);
} catch (Exception e) {
Log.e(TAG, "Buffer Error " + e.toString());
return false;
}
// Parsing JSON
try {
if (!fetched.isEmpty())
InitialsJson(fetched);
}catch (JSONException e) {
Log.e(TAG, "JSON Error " + e.toString());
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(!aBoolean)
RestoreData();
}
}
private void InitialsJson(String fetched) throws JSONException
{
JSONObject jsonObject = new JSONObject(fetched);
if (jsonObject.getInt("success") == 1) {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i<array.length() ; i++) {
JSONObject object = array.getJSONObject(i);
DisItem disItem = new DisItem();
disItem.setPid(object.getString("pid"));
disItem.setLiked(preferences.getBoolean(String.valueOf(disItem.getPid()), false));
Log.d(TAG, disItem.toString());
dbHelper.insert(disItem);
}
}
}
This is Databace getallItems function
public ArrayList<DisItem> getAllItems()
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + DIS_TABLE_NAME + "", null);
ArrayList<DisItem> arrayList = new ArrayList<>();
cursor.moveToFirst();
while (! cursor.isAfterLast())
{
DisItem disItem = new DisItem(cursor);
arrayList.add(disItem);
cursor.moveToNext();
}
return arrayList;
}
I tried your code with same scenario in a small JUnit Test and it shows me that you have not initialized your ArrayList<DisItem> correctely in getAllItems() method may be thats why you are getting nullPointerException that is
Replace
ArrayList<DisItem> arrayList = new ArrayList<>();
With
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();'
I corrected this thing and run the test again with some dummy values and it showed me correct result like:
public class Test
{
private ArrayList<DisItem> savedData;
#org.junit.Test
public void test() throws Exception
{
savedData = getAllData();
for(int a = 0; a < savedData.size(); a++){
System.out.println("ArrayList Data A= " + savedData.get(a).getA() + " B = " + savedData.get(a).getB());
}
}
}
private ArrayList<DisItem> getAllData()
{
ArrayList<DisItem> arrayList = new ArrayList<DisItem>();
DisItem disItem = new DisItem();
disItem.setA("AAAAAA");
disItem.setB("BBBB");
arrayList.add(disItem);
return arrayList;
}
private class DisItem
{
String a, b;
public void setA(String a)
{
this.a = a;
}
public void setB(String b)
{
this.b = b;
}
public String getA()
{
return this.a;
}
public String getB()
{
return this.b;
}
}
Output:
ArrayList Data A= AAAAAA B = BBBB
you cant access more than one SharedPreferences or SQLiteOpenHelper in Parallel.

Throw exception and getting e null

I throw a exception with some message like:
public static ILSResponseEmailLookUPBO getILSUserAccounts(Resources res,
String email) throws TripLoggerCustomException,
TripLoggerUnexpectedErrorException {
String resp = null;
String lookupURL;
try {
lookupURL = TripLoggerConstants.ServerConstants.ILS_LOOKUP_URL
+ URLEncoder.encode(email, "UTF-8");
} catch (UnsupportedEncodingException e1) {
throw new TripLoggerCustomException(
res.getString(R.string.error_try_again));
}
try {
resp = ConnectionManager.getInstance().httpRequest(lookupURL,
TripLoggerConstants.RequestMethods.GET);
} catch (IOException e) {
if (e.getMessage().equals(
res.getString(R.string.network_unreachable))
|| e.getMessage().equals(
res.getString(R.string.host_unresolved))) {
throw new TripLoggerCustomException(
res.getString(R.string.network_not_reachable));
} else {
throw new TripLoggerCustomException(
res.getString(R.string.email_notfound_ils));
}
}
here my else part execute.
And my exception class is:
public class TripLoggerCustomException extends Exception {
private String customMessage;
private static final long serialVersionUID = 1L;
public TripLoggerCustomException() {
super();
}
public TripLoggerCustomException(String message) {
super(message);
this.customMessage = (message == null ? "" : message);
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
}
And here i catch this exception:
private void manageLookUpActions(final String emailID) {
new Thread() {
public void run() {
try {
listILSAccounts = ILSLookupEmailBL.getILSUserAccounts(
getResources(), emailID);
} catch (TripLoggerCustomException e) {
dismissProgressBar();
handleException(e.getMessage());
return;
} catch (TripLoggerUnexpectedErrorException e) {
dismissProgressBar();
handleException(e.getMessage());
return;
}
}
}.start();
}
but here in catch of TripLoggerCustomException e is null.why?Can anyone help me?
After looking into multiple reports on StackOverflow, it seems like this is not an actual issue. Multiple people have been saying that it is a problem in the combination of the Eclipse debugger and the Android Emulator. That is why you don't get a NullPointerException, which you would definitely get if e was null.
So this is probably not an issue you have to worry about.

ResultSet to Android Cursor

I my connecting to a MySQL database that is on PC from my android application.
I am using java.sql.jdb for that. Now I want my result set to get in android.database.cursor??
How can I do that..??
Thats my code I am using in android application its getting the results for database but can't cast to Cursor:
Connection connect = null;
ResultSet resultSet = null;
Statement statement = null;
try {
connect = DriverManager.getConnection("jdbc:mysql://"+DbHelper.DB_Path+"/"+DbHelper.DB_Name+"?"
+ "user="+ DbHelper.DB_UserName+ "&password="+ DbHelper.DB_Pass);
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("Select * from btag_store "+
"Where "+
"guid='"+filterArgs+"'");
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Cursor cc;
cc = (Cursor) resultSet; // error in type casr
I know that type casting will give me error, but is there any other way for that..??
Thanks
To put it simply, you cannot. Unless you are willing to do all the work to define an object that implements the Cursor interface and uses a ResultSet to fulfil Cursor's implementation details. That would be somewhat silly, though, as the ResultSet object is already designed to iterate over results returned from the database. The cleanest approach is to use the ResultSet object as it was intended.
What Dave said is correct. My database items were constructed upon Cursor (Sqlite) but I need the same entrypoint wiht MySQL. So I tried this:
I created a base class
AbstractCursorGen.java:
import android.database.Cursor;
import java.sql.ResultSet;
public abstract class AbstractCursorGen {
protected Cursor c;
protected ResultSet rs;
public abstract int getColumnIndex(String iName);
public abstract String getString(String iName);
public abstract int getInt(String iName);
public abstract long getLong(String iName);
public abstract boolean moveToNext();
public abstract void close();
}
Then the one using Cursor will hold the instance of cursor. There is an additional benefit by getting result giving directly the column string. My code uses this for SQLite.
CursonGen.Java:
import android.database.Cursor;
public class CursorGen extends AbstractCursorGen{
public CursorGen(Cursor c)
{
this.c = c;
}
public int getColumnIndex(String iName)
{
return c.getColumnIndex(iName);
}
public String getString(String iName){
return c.getString(getColumnIndex(iName));
}
public int getInt(String iName){
return c.getInt(getColumnIndex(iName));
}
public long getLong(String iName){
return c.getLong(getColumnIndex(iName));
}
public boolean moveToNext()
{
return c.moveToNext();
}
public void close()
{
c.close();
}
}
And one built upon the resultset. This is used for MySQL results
ResultSetGen.java
import android.util.Log;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ResultSetGen extends AbstractCursorGen{
public ResultSetGen(ResultSet rs)
{
this.rs = rs;
}
public int getColumnIndex(String iName)
{
try {
return rs.findColumn(iName);
} catch (SQLException ex)
{
Log.e("PROX","Column not found");
return -1;
}
}
public String getString(String iName){
try {
return rs.getString(getColumnIndex(iName));
} catch (SQLException ex)
{
Log.e("PROX","Column not found");
return null;
}
}
public int getInt(String iName){
try {
return rs.getInt(getColumnIndex(iName));
} catch (SQLException ex)
{
Log.e("PROX","Column not found");
return -1;
}
}
public long getLong(String iName){
try {
return rs.getLong(getColumnIndex(iName));
} catch (SQLException ex)
{
Log.e("PROX","Column not found");
return -1;
}
}
public boolean moveToNext()
{
try {
return rs.next();
} catch (SQLException ex)
{
Log.e("PROX","Column not found");
return false;
}
}
public void close()
{
try {
rs.close();
} catch (SQLException ex)
{
Log.e("PROX","Column not found");
}
}
}
The trick is providing implementation only for the methods I'm actually using.
This is finally called by (one example)
public Person(AbstractCursorGen cursor)
{
setFromCursor(cursor);
}
protected void setFromCursor(AbstractCursorGen cursor)
{
PersonID = cursor.getLong ( COLUMN_PERSON_ID);
ClusterID = cursor.getInt ( COLUMN_CLUSTER_ID);
Name = cursor.getString ( COLUMN_NAME);
.....
}
Hope this helps.

Android ORMLite - ForeignCollection child has null foreign field

I'm currently stuck with the following situation;
Basically I've got a Work class, which has a ForeignCollection of WorkTasks.
I'd like to simply receive all WorkTasks, linked to Work object.
If I query for all WorkTasks, I do get a list of results but with 'work = null'. So it can't make any link to the correct Work object.
Resulting in no results with querying for the work_id and an empty list in Work itself.
I've seen examples and questions about this countless of times but apparently im missing out on something.
Below is the code that im using which is relevant;
The DatabaseHelper;
#Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
applicantDao = DaoManager.createDao(connectionSource, Applicant.class);
educationDao = DaoManager.createDao(connectionSource, Education.class);
workDao = DaoManager.createDao(connectionSource, Work.class);
workTaskDao = DaoManager.createDao(getConnectionSource(), WorkTask.class);
onlinePersonDao = DaoManager.createDao(connectionSource, OnlinePerson.class);
institutionDao = DaoManager.createDao(connectionSource, Institution.class);
lessonDao = DaoManager.createDao(connectionSource, Lesson.class);
TableUtils.createTable(connectionSource, Applicant.class);
TableUtils.createTable(connectionSource, Education.class);
TableUtils.createTable(connectionSource, Work.class);
TableUtils.createTable(connectionSource, Institution.class);
TableUtils.createTable(connectionSource, Lesson.class);
TableUtils.createTable(connectionSource, OnlinePerson.class);
TableUtils.createTable(connectionSource, Reference.class);
TableUtils.createTable(connectionSource, WorkTask.class);
[....]
public Dao<WorkTask, Integer> getWorkTaskDao() {
if (null == workTaskDao) {
try {
workTaskDao = getDao(WorkTask.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return workTaskDao;
}
The database manager:
public List<Experience> getAllWork() {
List<Experience> exp = null;
try {
exp = getHelper().getWorkDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return exp;
}
public List<WorkTask> getAllWorkTask() {
List<WorkTask> workTask = null;
try {
workTask = getHelper().getWorkTaskDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return workTask;
}
public List<WorkTask> getWorkTaskByWorkId(int workId) {
List<WorkTask> workTasks = null;
try {
workTasks = getHelper().getWorkTaskDao().queryForEq("work_id", workId);
} catch (SQLException e) {
e.printStackTrace();
}
return workTasks;
}
public void addWork(Collection<Work> jobs) {
try {
for (Experience work : jobs) {
Work w = (Work) work;
// Add nested child first
this.addInstitution(w.institution);
this.addWorkTask(w.tasks);
getHelper().getWorkDao().createOrUpdate(w);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addWorkTask(Collection<WorkTask> worktasks) {
try {
for (WorkTask wt : worktasks) {
getHelper().getWorkTaskDao().createOrUpdate(wt);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
The list from the work model (gets a pre-filled id from an abstract parent):
#ForeignCollectionField(eager = true)
#SerializedName("tasks")
public Collection<WorkTask> tasks;
public ArrayList<WorkTask> getTasks(){
ArrayList<WorkTask> taskList = new ArrayList<WorkTask>();
Iterator iterator = tasks.iterator();
while(iterator.hasNext()){
WorkTask task = (WorkTask) iterator.next();
taskList.add(task);
}
return taskList;
}
The WorkTask :
public class WorkTask {
/**
* Auto-incremented id for the ORMLite-SQLite database
*/
#DatabaseField(generatedId = true)
public int id;
/**
* Foreign field id for the ORMLite-SQLite database
*/
#DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, columnName = "work_id")
public Work work;
And finally all the things that are failing me:
ArrayList<WorkTask> tasks_iterated = work.getTasks();
ArrayList<WorkTask> tasks_id = (ArrayList<WorkTask>) DatabaseManager.getInstance()
.getWorkTaskByWorkId(work.id);
ArrayList<WorkTask> tasks = (ArrayList<WorkTask>) DatabaseManager.getInstance().getAllWorkTask();
This eventually leaves me with:
tasks_iterated = empty
tasks_id = empty
tasks = a full list of my tasks but all with the attribute 'work = null' so I can't place them to the correct Work object.
Fixed it by changing my adding method to:
public void addWorkTask(Collection<WorkTask> worktasks, Work work) {
try {
for (WorkTask wt : worktasks) {
wt.work = work;
getHelper().getWorkTaskDao().createOrUpdate(wt);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Not sure if it's the only way to do this though. Seems a bit weird i'd have to do this manually.

testing a class with out activity and services

this is my actual class I am writing test class below.
public class ReadFile {
private Scanner rx, tx;
public void openFile() {
try {
rx = new Scanner(new File("/sys/class/net/eth0/statistics/rx_bytes"));
tx = new Scanner(new File("/sys/class/net/eth0/statistics/tx_bytes"));
} catch (Exception e) {
e.printStackTrace();
}
}
public String readRxFile() {
String rxData = "";
while (rx.hasNext()) {
rxData = rx.next();
}
return rxData;
}
public String readTxFile() {
String txData = "";
while (tx.hasNext()) {
txData = tx.next();
}
return txData;
}
public void closeFile() {
rx.close();
tx.close();
}
}
this is test class. to test the read data.
public class Testreadrxfile extends TestCase {
public Testreadrxfile() {
super();
}
protected void setUp() throws Exception {
try {
super.setUp();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ReadFile rf;
public void testappdata() {
String str1 = rf.readRxFile();
Assert.assertEquals("14081",str1 );
}
}
this is the error I am getting.
java.lang.NullPointerException
atcom.android.deviceintelligence1. test.Testreadrxfile.testappdata(Testreadrxfile.java:26)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
this is not activity or service test to use getactivity() or getservice() so what I should do to get out of this error . thanks for help in advance.
see your code.. rf is not initialised..
ReadFile rf; // not intialisd
public void testappdata() {
String str1 = rf.readRxFile(); // equivalent to null.readRxFile();
Assert.assertEquals("14081",str1 );
}
yeah, rf is not initialised. In this kind of situation first thing to do is attach the debugger on the line you are getting error, and in most cases answer becomes obvious.
UPDATE
first your code didn't work because you didn't initialised rx, now your code doesn't work becasue you never called following function. In the function you are initialising your scanner objects. call this function from your readRxFile function and you should be good to go.
public void openFile() {
try {
rx = new Scanner(new File("/sys/class/net/eth0/statistics/rx_bytes"));
tx = new Scanner(new File("/sys/class/net/eth0/statistics/tx_bytes"));
} catch (Exception e) {
e.printStackTrace();
}
}
public String readRxFile() {
String rxData = "";
while (rx.hasNext()) { //eq. to null.haxNext()
rxData = rx.next();
}
return rxData;
}

Categories

Resources