getString method in android does not work - android

This is our main class to get information from the database. We are trying to get the values of the "name" column in the "barcode" database that we have created. Right now, we are not able to get the desired value but values as "a, b, c, d, ..." (such as; it returns "a" when we ask for the 1st one, it return "b" when we ask for the second one in the "name" column) value with the cursor.getString method
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataBaseHelper myDbHelper = new DataBaseHelper(this);
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDatabase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch(SQLException sqle){
throw sqle;
}
Cursor cursor = myDbHelper.getAllAccounts();
String[] values = new String[6];
int i=0;
//take into the array from the database
while(cursor.moveToNext()){
values[i]= cursor.getString(cursor.getColumnIndex("name"));
i++;
}
cursor.close();
//Write to textview
TextView youtextview = (TextView) findViewById(R.id.textView1);
youtextview .setText(values[2]);
}
}

You are not dealing with the cursor in the right way (also you should not do DB calls in the main UI thread which is what you are doing right now). See: http://developer.android.com/reference/android/database/Cursor.html
static final COL_NAME = "name";
Cursor cursor = myDbHelper.getAllAccounts();
cursor.moveToFirst();
int maxCursorIndex = cursor.getCount();
for(int cursorIndex=0;cursorIndex<maxCursorIndex;cursorIndex+=1){
values[cursorIndex] = cursor.getString(cursor.getColumnIndex(COL_NAME);
}
cursor.close();

Related

i dont know how to declare Cursor and get method at same time and use it Cursor c? what i need too is to return all the names

I have class called unviersityClient and method name `getallstudent,but how to include them in cursor to get results displayed
this is in mainactivity
public class MainActivity extends ActionBarActivity {
private TextView tv;
private Button bt;
private Context mycontext;
Cursor c;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
bt=(Button)findViewById(R.id.button1);
mycontext=this.getApplication();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// universityClient.addStudents(mycontext, "christy");
// universityClient.addStudents(mycontext, "joe");
universityClient.getAllStudents(mycontext);
c.moveToFirst();
while(!c.isAfterLast()){
String dir =c.getString(c.getColumnIndex("name"));
tv.setText("Name : "+dir);
c.moveToNext();
}
and this is in .java created by json. it's already created the db
public static Cursor getAllStudents(Context c) {
ContentResolver cr = c.getContentResolver();
String[] result_columns = new String[]{
universityDB.STUDENTS__ID_COLUMN,
universityDB.STUDENTS_NAME_COLUMN,
};
String where = null;
String whereArgs[] = null;
String order = null;
Cursor resultCursor = cr.query(university.STUDENTS_URI, result_columns, where, whereArgs, order);
return resultCursor;
}
if you have all the students in a database you can use this to get all the names and then send them to a variable
String SELECT_QUERY = "SELECT * FROM Tutores t1 INNER JOIN Tutorados t2 ON t1._id = t2.id_tutor and t1._id = " + ET1.getText().toString().trim();
cursor = db.rawQuery(SELECT_QUERY, null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
C1 = cursor.getString(cursor
.getColumnIndex("_id"));
C2 = cursor.getString(cursor
.getColumnIndex("name"));
Fin += C1 + "-" + C2 + "\n";
} while (cursor.moveToNext());
}
}
cursor.close();
Fin is a String and you can get all the names or whatever you want from the columns with the getColumnIndex("nameOfTheColumn") and send "Fin" to a textview or something like that
hope that helps!, see ya
Cant understand why you want to put json data in cursor while json parsing is the best way to do the same. If your priority is to bring data somewhere else and fetch one by one using loop, you can use arraylist/hashmap like collection objects. If you have many fields in one json object, you can create a class having those fields and make an arraylist of that having type of class and store data in that. Like this:
1. Fetch single json object at a time, fetch values of fields.
2. create class object by passing those values in constructor.
3. Create arraylist of that class type.
4. put class objects in that arraylist one by one and fetch as well.
ArrayList<Person> person = new ArrayList<Person>();
Person newPerson = new Person("balvier", "27", "Male");
person.add(newPerson);
Person newPersonAnother = new Person("Adel", "20", "FeMale");
person.add(newPersonAnother);

Android database does not work properly

I have an android sqlite database in Farsi (Persian) language, and I use the data in that for fill the ListView, but my problem is that I use item name in ListView in my query. For example, I get a name of ListView's text and use it in my query, but some of them does not show me correct answer from DB. I use the Farsi class for queries.
Here is my code:
List<String> getSubjects(String db_name, String name) {
List<String> collection = new ArrayList<String>();
Cursor cursor;
SQLiteDatabase db;
MyDataBaseHelper myDbHelper;
myDbHelper = new MyDataBaseHelper(this, db_name);
try {
cursor = null;
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
myDbHelper.openDataBase();
db = myDbHelper.getReadableDatabase();
cursor = db.rawQuery(
"select distinct type from mydata where group like '%"
+ farsi.ConvertBackToRealFarsi(name) + "%'", null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String uname = cursor.getString(cursor
.getColumnIndex("type"));
collection.add(DariGlyphUtils.reshapeText(uname));
} while (cursor.moveToNext());
}
}
} catch (SQLException sqle) {
throw sqle;
}
db.close();
return collection;
}

Trying to load an sqlite table as an ArrayList<String[]> in android

I'm trying to load an sqlite table as an arraylist so that i can use the data in it. I'm not too sure about the sqlite queries but i already have a class built to manipulate the strings as is, which is what i'm more comfortable with. I can load an individual row but i'm not sure how to get the whole table as an arraylist.
I have the following method in my main method
public void ShowCNData()
{
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
String allData = mDbHelper.getCYData().get(1)[1];
thing.setText(allData);
mDbHelper.close();
}
and the following method in my dbAdapter/Helper class
public ArrayList<String[]> getCYData()
{
ArrayList<String[]> CYData = new ArrayList<String[]>();
try
{
String sql ="SELECT * FROM cnYears ";
Cursor mCur = null;
do
{
mCur = mDb.rawQuery(sql, null);
CYData.add(new String[] {mCur.getString(0),mCur.getString(1),mCur.getString(2),mCur.getString(3),mCur.getString(4)});
}
while (mCur.moveToNext());
return CYData;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
How do i load the data into my ArrayList?
Without actual log information, I'd guess your NullPointerException occurs when you get an empty cursor. Try it this way:
//initialize arraylist, execute query etc.
if (cursor.moveToFirst()) {
do {
String[] entry = new String[dataSize];
//pull your data here
data[0] = cursor.getInt(0);
data[1] = cursor.getString(1);
//...
list.add(entry);
} while (cursor.moveToNext());
}
// return arraylist

Android SQLit Search: NullPointerException?

I need to perform a search operation into my SQLite DB.
In my Activity, I have EditText for entering the keyword and a search Button. Once the user clicks the button, the EditText text will be stored in the keyword and sent to a search(String keyword) method in the DBHelper class.
I have this code in my SearchActivityfor onCreate() and onClick():
//SearchActivity class extends ListActivity and implements OnClickListener
Button search;
DataBaseHelper myDbHelper;
SimpleCursorAdapter ca;
ListView lv;
EditText txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
txt = (EditText) findViewById(R.id.search_term);
search = (Button) findViewById(R.id.search_button);
search.setOnClickListener(this);
}
public void onClick(View v) {
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {}
try {
String keyword= txt.getText().toString();
Cursor cursor = myDbHelper.search(keyword); //A method in my DB
cursor.moveToFirst();
String[] columns = {cursor.getColumnName(1)};
int[] columnsLayouts = {R.id.item_title};
ca = new SimpleCursorAdapter(this.getBaseContext(), R.layout.items_layout, cursor,columns , columnsLayouts);
lv = getListView();
lv.setAdapter(ca);
} catch(Exception e){}
}
However, I got NullPointerException in the LogCat!! I couldn't find where the error is.
Anyone can help ?
The description to the NullPointerException could be a little more informative. But it is very likely that the NullPointerException occurs here:
1: Cursor cursor = myDbHelper.search(keyword); //A method in my DB
2: cursor.moveToFirst();
3: String[] columns = {cursor.getColumnName(1)};
or here:
1: try {
2: myDbHelper.openDataBase();
3: } catch (SQLException sqle) {}
Either in the first part in line 1: or 2: or in the second part in line 2:
You should always check if objects which rely on the existence of data are not null. So you should check if cursor is null. Another thing could be that you never initialize myDbHelper.

rawQuery - CursorAdapter

App gets force closed when going to this activity. I actually noticed that if i remove the cursor part the activity doesn't crash. Help would be appreciated.
public class SearchResults extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresults);
Database myDbHelper = new Database(null);
myDbHelper = new Database(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
}catch(SQLException sqle){
throw sqle;
}
// Get the intent, verify the action and get the query
Intent intent = getIntent();
String query = intent.getStringExtra(SearchManager.QUERY);
SQLiteDatabase myDb = myDbHelper.getReadableDatabase();
String q = "SELECT BookTitle, _ISBN FROM Books WHERE BookTitle LIKE" + query;
Cursor c = myDb.rawQuery(q, null);
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] { "Books._ISBN", "Books.BookTitle" };
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.ISBN_entry, R.id.Title_entry };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.listlayout, c, columns, to);
this.setListAdapter(mAdapter);
}
}
The Cursor requires a column called '_id' - change your query to alias your ISBN column as follows...
String q = "SELECT _ISBN as _id, BookTile FROM Books WHERE BookTitle LIKE" + query;
See my answer and explanation here column '_id' does not exist problem

Categories

Resources