SQLite get single datum (*single data)(update post) - android

I'm a beginner in Android. Please help me to solve this simple problem: retrieve a single datum from SQLite.
case 1 :
dbhelper.java
// Getting single part
public lispar Look(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor kr = db.query(TABLE_PART, new String[]{ID,
KODE, NAMA}, ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (kr != null)
kr.moveToFirst();
lispar contact = new lispar(Integer.parseInt(kr.getString(0)),
kr.getString(1), kr.getString(2));
// return contact
kr.close();
db.close();
return contact;
}
main.java
kodcari = (Button) findViewById(R.id.carikod);
kodcari.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ckodin = kodin.getText().toString(); //wrong string?
parin.getText().toString();
//what should i do?
}
});
partnam = (EditText) findViewById(R.id.namepart);
dbHandle = new DbHandle(this);
}
case 2 :
main.java ()
kodin = (EditText) findViewById(R.id.inkod);
kodcari = (Button) findViewById(R.id.carikod);
kodcari.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
FeedEntry._ID,
FeedEntry.KODE,
FeedEntry.NAMPART,
FeedEntry.BELANG
};
// Filter results WHERE "kode" = 'kode part'
String selection = FeedEntry.KODE + " = ?";
String[] selectionArgs = parin.getText().toString(), belangin.getText().toString();//{ "KODE_PART" }; //
// How you want the results sorted in the resulting Cursor
String sortOrder = FeedEntry.KODE + " DESC";
Cursor kr = db.query(
FeedEntry.KODE, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if (kr != null)
kr.moveToFirst();
//String parin = kr.getString(
//kr.getColumnIndexOrThrow(FeedEntry._ID)
//);
}
});
main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Looking by Code"
android:textSize="10pt"
android:id="#+id/txkod"
android:layout_marginTop="63dp"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="insert code"
android:textAlignment="center"
android:layout_marginTop="25dp"
android:id="#+id/inkod"
android:layout_below="#+id/txkod"
android:layout_alignLeft="#+id/txkod"
android:layout_alignStart="#+id/txkod"
android:layout_alignRight="#+id/txkod"
android:layout_alignEnd="#+id/txkod" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Look"
android:id="#+id/carikod"
android:layout_below="#+id/inkod"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/codepar"
android:hint="code part"
android:layout_below="#+id/namkod"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/nampar"
android:hint="name part"
android:layout_below="#+id/nampar"/>
</LinearLayout>
Inserting the data is successful, but reading a datum isn't.
(datum means data*)
enter image description here

I'm not at all sure if the following will get you moving. But it appears that you are not getting the ID's of the views kodin and parin. So perhaps try the following:-
kodin = (EditText) findViewById(R.id.inkod);
parin = (EditText) findViewById(R.id.nampar);
More detailed code (untested and written on the fly so may have errors)
If you are using Android Studio or an IDE with debugging, then using that can be really helpful.
kodcari = (Button) findViewById(R.id.carikod);
// Adding the following lines may get the correct string
kodin = (EditText) findViewById(R.id.inkod); //????
parin = (EditText) findViewById(R.id.nampar); //????
kodcari.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ckodin = kodin.getText().toString(); //wrong string?
parin.getText().toString();
//what should i do? Perhaps the following :-
lipsar myContact = Look(ckodin !!!!CONVERTED TO INT FROM STRING);
// whatever else you need to do with the mycontact .....
}
});
partnam = (EditText) findViewById(R.id.namepart);
dbHandle = new DbHandle(this);
}

Related

How to create a SQLite databse to store input that user key in, not related to listview?

I have no idea how to create a database to store my user information.
I have a rough idea on how to create a database but that is only for item in the listview. I want to store my user information so that i can edit the information anytime. But whenever i key in the value and manage to get my calories, once i exit the app i have to re-enter all the information again.
This is my layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
tools:context=".Calculator"
android:background="#android:color/holo_orange_light">
<TextView
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textSize="15sp"
android:layout_above="#+id/Age"
android:layout_alignEnd="#+id/Age"
android:layout_alignTop="#+id/food"
android:layout_alignParentStart="true"
/>
<TextView
android:id="#+id/Weight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/weight"
android:layout_alignEnd="#+id/Height"
android:layout_alignParentStart="true"
android:layout_below="#+id/Height"
android:text="Weight: (kg)"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textSize="15sp" />
<TextView
android:id="#+id/Height"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/height"
android:layout_alignParentStart="true"
android:layout_below="#+id/age"
android:text="Height: (cm)"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textSize="15sp" />
<TextView
android:id="#+id/Age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age:"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textSize="15sp"
android:layout_above="#+id/Height"
android:layout_below="#+id/food"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/Height" />
<TextView
android:id="#+id/Gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender: "
android:textAppearance="#style/TextAppearance.AppCompat"
android:textSize="20sp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/Name" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioGroup"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="41dp"
android:orientation ="vertical">
<RadioButton
android:id="#+id/Male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/Gender"
android:layout_alignTop="#+id/Gender"
android:layout_marginEnd="14dp"
android:layout_toStartOf="#+id/Female"
android:checked="true"
android:text="Male" />
<RadioButton
android:id="#+id/Female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/Male"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/Gender"
android:layout_marginEnd="20dp"
android:text="Female" />
</RadioGroup>
<EditText
android:id="#+id/food"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/radioGroup"
android:ems="10"
android:inputType="textPersonName"
android:singleLine="true" />
<EditText
android:id="#+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/food"
android:ems="10"
android:gravity="right"
android:inputType="number"
android:singleLine="true"
android:textColorLink="#android:color/background_light"
android:visibility="visible" />
<EditText
android:id="#+id/weight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/height"
android:ems="10"
android:gravity="right"
android:inputType="numberDecimal"
android:singleLine="true"
android:visibility="visible" />
<EditText
android:id="#+id/height"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/age"
android:ems="10"
android:gravity="right"
android:inputType="numberDecimal"
android:singleLine="true"
android:textIsSelectable="false" />
<Button
android:id="#+id/calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/weight"
android:layout_centerHorizontal="true"
android:text="Calculate"
android:textColor="?attr/actionMenuTextColor" />
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/calc" />
</RelativeLayout>
This is my java code:
public class Calculator extends AppCompatActivity {
EditText weight, height, age, name;
double calculate, result;
RadioButton radioGender;
int selectedId;
private Button button;
TextView calresult;
private Cursor model = null;
private CalculatorHelper helper2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calories_calculator);
button = (Button) findViewById(R.id.calc);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
weight = (EditText) findViewById(R.id.weight);
height = (EditText) findViewById(R.id.height);
age = (EditText) findViewById(R.id.age);
name = (EditText) findViewById(R.id.food);
helper2 = new CalculatorHelper(Calculator.this);
model = helper2.getAll();
int Gender;
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton male = (RadioButton) findViewById(R.id.Male);
RadioButton female = (RadioButton) findViewById(R.id.Female);
selectedId = rg.getCheckedRadioButtonId();
radioGender = (RadioButton) findViewById(selectedId);
if (male.isChecked()) {
Gender = 1;
} else {
Gender = 2;
}
if (TextUtils.isEmpty(name.getText().toString())) {
name.setError("Please enter your name");
Toast.makeText(Calculator.this, "Please enter your name",
Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(weight.getText().toString())) {
weight.setError("Please enter your weight");
return;
}
if (TextUtils.isEmpty(height.getText().toString())) {
height.setError("Please enter your height");
return;
}
if (TextUtils.isEmpty(age.getText().toString())) {
age.setError("Please enter your age");
return;
}
String namevr = name.getText().toString();
double weightvr = Double.parseDouble(weight.getText().toString());
double heightvr = Double.parseDouble(height.getText().toString());
int agevr = Integer.parseInt(age.getText().toString());
Intent intent = new Intent(Calculator.this, DataCalculator.class);
intent.putExtra("NAME", namevr);
result = calculate + 0;
intent.putExtra("RESULT", result);
//a.putString("name", String.valueOf(namevr));
if ((weightvr <= 30) || (weightvr >= 200)) {
Toast.makeText(Calculator.this, "Please enter a valid weight",
Toast.LENGTH_SHORT).show();
return;
} else if ((heightvr <= 120) || (heightvr >= 220)) {
Toast.makeText(Calculator.this, "Please enter a valid height",
Toast.LENGTH_SHORT).show();
return;
} else if ((agevr <= 0) || (agevr >= 120)) {
Toast.makeText(Calculator.this, "Please enter a valid age",
Toast.LENGTH_SHORT).show();
return;
} else {
if (selectedId == R.id.Male) {
calculate = (((weightvr * 10) + (heightvr * 6.25)) - (5 * agevr)) + 5;
} else {
calculate = (((weightvr * 10) + (heightvr * 6.25)) - (5 * agevr)) - 161;
}
}
intent.putExtra("RESULT", String.valueOf(calculate));
startActivity(intent);
finish();
}
});
}
}
Assuming that CalculatorHelper will be your database helper.
Step 1 - Create/Amend CallculatorHelper to
extend the SQLiteOpenHelper class
i.e. use public class CalculatorHelper extends SQLiteOpenHelper { ...... }
The class extending the SQLiteOpenHelper requires a minimum of 3 entities
a constructor that calls the super constructor of the SQLiteOpenHelper class.
this call requires 4 values,
1) a valid Context,
2) the name of the database (this will be the name of the file),
3) a CursorFactory (null will be used as one isn't needed),
4) an int version number (1 being the first).
An override for the public onCreate method that has 1 parameter passed to it
the SQLiteDatabase object that has been created. The method returns nothing and is therefore defined using void.
An override for the public onUpgrade method that has 3 parameters passed to it
the SQliteDatabase object
the version number that is stored in the database (the old version)
the version number that has been passed to the constructor of the SQLiteOpenHelper super constructor (the new version).
Is typically where you create the tables for the database.
Is where you would code alterations to the schema when the version is increased.
However the above is useless unless the database has a table or more. So really the design of the database should be first.
Step 2 (should really be 1) Design
It appears that you want to save the Name/Food, Weight, Height, Age and gender.
So without going into normalisation issues etc the assumption is that you want to store the above perhaps on a button click.
As such you want a table that has columns for the Name/Food, Weight, Height, Age and gender.
SQLite is very flexible when it comes to the types of data but has 5 types of columns TEXT, INTEGER, REAL, NUMERIC and BLOB Datatypes In SQLite Version 3
Name/Food will be a string so TEXT.
Weight and Height and Age are INTEGER.
There is no boolean type so Gender will be stored as INTEGER.
As such you want a table with the above
The table needs a name. So perhaps person_data will do. SQLite uses it's implementation of SQL (Structured Query Language) and to create a table if uses CREATE TABLE SQL As Understood By SQLite - CREATE TABLE
So perhaps CREATE TABLE person_data (_name TEXT, _weight INTEGER, _height INTEGER, _age INTEGER, _gender INTEGER) will suffice.
- _ being used before any word so as to ensure that an invalid column name is avoided.
It is strongly suggest that all names of entities table names, column names etc use a single source for the name. This significantly reduces the chance for typing errors. As such it is suggested that these are added as public static final variables to the database helper class.
To create the table when the database has been created the SQLiteDatabase execSQL method can be used. This is one way to run SQL that does not return a result (if the table creation fails then an exception will result as it's an unrecoverable situation).
The table is useless unless data can be inserted and typically you want to be able to update data and perhaps delete data. To be able to do so matters are generally simplified if a row (an entry in the table) can be easily uniquely identified. As such a special column will be added that allows a row to be uniquely identified, actually without specifying otherwise this column exists so really we are creating an alias for that underlying column called the rowid. The special SQL for creating such a column is to use column_name_to_be_the_alias INTEGER PRIMARY KEY. With android there are some instances where the column name has to be a specific name (Cursor Adapters) as such there is a constant called BaseColumns._ID. This will be used for the column name.
With the Android SDK there are what are called convenience methods (they write the SQL given a few paramaters on your behalf, they also provide protection against SQL injection). The SQLiteDatabase insert, update and query methods will be utilised.
Apply all the above then CalculatorHelper.java could be :-
public class CalculatorHelper extends SQLiteOpenHelper {
public static final String DBNAME = "calculator.db";
public static final int DBVERSION = 1;
public static final String PERSONDATA_TABLENAME = "person_data";
public static final String COL_PERSONDATA_ID = BaseColumns._ID;
public static final String COL_PERSONDATA_NAME = "_name";
public static final String COL_PERSONDATA_WEIGHT = "_weight";
public static final String COL_PERSONDATA_HEIGHT = "_height";
public static final String COL_PERSONDATA_AGE = "_age";
public static final String COL_PERSONDATA_GENDER = "_gender";
public static final String PERSONDATA_TABLESQL = "CREATE TABLE IF NOT EXISTS " +
PERSONDATA_TABLENAME + "(" +
COL_PERSONDATA_ID + " INTEGER PRIMARY KEY," +
COL_PERSONDATA_NAME + " TEXT," +
COL_PERSONDATA_WEIGHT + " INTEGER," +
COL_PERSONDATA_HEIGHT + " INTEGER, " +
COL_PERSONDATA_AGE + " INTEGER, " +
COL_PERSONDATA_GENDER + " INTEGER " +
")";
public CalculatorHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(PERSONDATA_TABLESQL); //<< when the database is created create the table
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insertPersonData(String name, int weight, int heigh, int age, boolean gender) {
SQLiteDatabase db = this.getWritableDatabase(); //<< gets the SQLiteDatabase object for this instance
ContentValues cv = new ContentValues(); //<< ContentValues are key (column name) value
cv.put(COL_PERSONDATA_NAME,name);
cv.put(COL_PERSONDATA_WEIGHT,weight);
cv.put(COL_PERSONDATA_HEIGHT,heigh);
cv.put(COL_PERSONDATA_AGE,age);
cv.put(COL_PERSONDATA_GENDER,gender);
//<< NOTE id isn't specified SQLite will generate an id (the value returned)
return db.insert(PERSONDATA_TABLENAME,null,cv);
// Writes and executes the SQL () assuming insertPersonData:-
// INSERT INTO person_data (_name,_weight,_height,_age,_gender) VALUES('Fred',75,160,21,0)
}
/**
*
* #param id The id of the row to be updated
* #param newName The new name to apply ("" or null if not to change)
* #param newWeight The new weight to apply (null or less than 1 to not change)
* #param newHeight as per weight for height
* #param newAge as per weight for age
* #param newGender true or false or null if to not be changed
* #return the number of rows update (should be 1 or 0, o if nothing changed)
*/
public int updatePersonData(long id, String newName, Integer newWeight, Integer newHeight, Integer newAge, Boolean newGender) {
int rv = 0;
ContentValues cv = new ContentValues();
if (newName != null && newName.length() > 0 ) {
cv.put(COL_PERSONDATA_NAME,newName);
}
if (newWeight != null && newWeight > 0) {
cv.put(COL_PERSONDATA_WEIGHT,newWeight);
}
if (newHeight != null && newHeight > 0) {
cv.put(COL_PERSONDATA_HEIGHT,newHeight);
}
if (newAge != null && newAge > 0) {
cv.put(COL_PERSONDATA_AGE,newAge);
}
if (newGender != null) {
cv.put(COL_PERSONDATA_GENDER,newGender);
}
if (cv.size() > 0) {
SQLiteDatabase db = this.getWritableDatabase();
rv = db.update(PERSONDATA_TABLENAME,cv,COL_PERSONDATA_ID + "=?",new String[]{String.valueOf(id)});
}
return rv;
}
public int deletePersonData(long id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(PERSONDATA_TABLENAME,COL_PERSONDATA_ID+"=?",new String[]{String.valueOf(id)});
}
/**
* Returns ALL persondata as a Cursor object
* #return
*/
public Cursor getAllPersonDataRows() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(
PERSONDATA_TABLENAME,
null,
null,
null,
null,
null,
null
);
}
public Cursor getPersonByID(long id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(
PERSONDATA_TABLENAME,
null,
COL_PERSONDATA_ID+"=?",
null,
null,
null,
null
);
}
}
You could then add a button e.g. with an id of save to the layout and then use :-
setContentView(R.layout.calories_calculator); //<<<<<<<<<< existing code
helper2 = new CalculatorHelper(this);
button = (Button) findViewById(R.id.calc); //<<<<<<<<<< existing code
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean gender = true;
if (((RadioButton)Calculator.this.findViewById(R.id.Male)).isChecked()) {
gender = false;
}
long newid = helper2.insertPersonData(
(((EditText)Calculator.this.findViewById(R.id.food)).getText().toString()),
Integer.parseInt(((EditText)Calculator.this.findViewById(R.id.weight)).getText().toString()),
Integer.parseInt(((EditText)Calculator.this.findViewById(R.id.height)).getText().toString()),
Integer.parseInt(((EditText)Calculator.this.findViewById(R.id.age)).getText().toString()),
gender
);
String msg = "Not Inserted into the database.";
if (newid > 0) {
msg = "Successfully Inserted into the database.";
}
Toast.makeText(Calculator.this,msg,Toast.LENGTH_SHORT).show();
//Example getting data and traversing a Cursor
Cursor csr = helper2.getAllPersonDataRows();
while (csr.moveToNext()) {
String gendertype = "M";
if (csr.getInt(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_GENDER)) > 0) {
gendertype = "F";
}
Log.d("PERSONDATA",
"Name is " + csr.getString(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_NAME)) +
"\nWeight is " + String.valueOf(
csr.getInt(
csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_WEIGHT)
)
) + "kg" +
"\nHeight is " + String.valueOf(csr.getInt(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_HEIGHT))) + " cm" +
"\nAge is " + csr.getString(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_AGE)) + " years" +
"\nGender is " + gendertype +
"\nUnique Row Identifier is " + String.valueOf(csr.getLong(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_ID)))
);
}
csr.close(); //<< IMPORTANT to close Cursors when done with them
}
});
//........... rest of your code here ...........
When you click the SAVE button you have added, then
The data will be saved to the database.
A Toast will say that it has been added to the database.
The log will contain some output about the rows in the database.
E.g. after adding 2 rows then the log might contain :-
07-14 10:15:28.462 25100-25100/s.e.so57021686calculator D/PERSONDATA: Name is Fred
Weight is 75kg
Height is 166 cm
Age is 61 years
Gender is M
Unique Row Identifier is 1
07-14 10:15:28.462 25100-25100/s.e.so57021686calculator D/PERSONDATA: Name is Mary
Weight is 68kg
Height is 34 cm
Age is 159 years
Gender is F
Unique Row Identifier is 2
Showing that data has been saved (i.e. the data from Fred was previously saved). If the App is restarted and another row is added then 3 would be displayed and so on.

how to show list view record from sqlite into second listview on setOnItemClickListener

I have created list view, what I want to do is that when user clicks on first list view the selected record For that Particular Field should show in second list view,
in my code I Just get the item position of the first list view and i pass Selected item of that list view into my second Activity i dont know what i do next
so please give me the code/idea how to do this as I am new in android..
Here is My Code
MainActivity:(First List View)
listView= (ListView) findViewById(R.id.listView);
dbHelper = new SqlLiteDbHelper(this);
try {
dbHelper.openDataBase();
} catch (SQLException e) {
e.printStackTrace();
}
sqLiteDatabase=dbHelper.getReadableDatabase();
cursor=dbHelper.gettitles(sqLiteDatabase);
String[] from = new String[] { dbHelper.TITLE };
int[] to = new int[] {R.id.title };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.title_row,cursor,from,to);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor =(Cursor) (listView.getItemAtPosition(position));
String selectedItem = cursor.getString(0);
Intent intent = new Intent(MainActivity.this, SubcategoryActivity.class);
intent.putExtra("selectedItem", selectedItem);
startActivity(intent);
}
});
MainActivity Xmlcode:(Firstlistview)
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
Title_row.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/title"
android:layout_gravity="center_horizontal" />
Second Activity:(Second List view)
listView2= (ListView) findViewById(R.id.listView2);
final String selectedData = intent.getStringExtra("selectedItem");
dbHelper = new SqlLiteDbHelper(this);
try {
dbHelper.openDataBase();
} catch (SQLException e) {
e.printStackTrace();
}
sqLiteDatabase=dbHelper.getReadableDatabase();
cursor=dbHelper.getsubcategory(sqLiteDatabase,selectedData);
String[] from = new String[] { dbHelper.SUBCATEGORY };
int[] to = new int[] {R.id.subcategory };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.subcategory_row,cursor,from,to);
adapter.notifyDataSetChanged();
listView2.setAdapter(adapter);
Subcategory Xml File:
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView2"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
subcategory_row.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/subcategory"
android:layout_gravity="center_horizontal" />
Database CLass:
public Cursor gettitles(SQLiteDatabase db)
{
db = this.getReadableDatabase();
Cursor cursor;
cursor = db.query(true, "record", new String[]{TITLE,ITEMNO + " as _id"}, null, null, TITLE, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor getsubcategory(SQLiteDatabase db,String sub)
{
db=this.getReadableDatabase();
Cursor cursor;
cursor = db.query("record",new String[]{SUBCATEGORY},TITLE + "=" +sub,null,null,null,null);
return cursor;
}
Logcat:
Caused by: android.database.sqlite.SQLiteException: near "FOOD": syntax error (code 1): , while compiling: SELECT subcategory FROM record WHERE title=GENERAL FOOD TIPS
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1448)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1295)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1166)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1334)
at com.example.aeiltech.sidd.SqlLiteDbHelper.getsubcategory(SqlLiteDbHelper.java:118)
at com.example.aeiltech.sidd.SubcategoryActivity.onCreate(SubcategoryActivity.java:38)
I am not quite sure what you want to do, however i see two Errors in your code that may help solve the problem. If they don't, please provide a better understandable problem description.
In the onItemClickListener you are trying to cast the item from the List to a String. However the Method getItemAtPosition(position) will pass to the function getItem(position) of the adapter, which in your case will return a Cursor. You cannot cast a Cursor to a String. Therefore your code at this position should look something like this:
Cursor cursor =(Cursor) (listView.getItemAtPosition(position));
String selectedItem = cursor.getString(0);
In your second list view you have the following function call:
cursor=dbHelper.getsubcategory(sqLiteDatabase,sub);
However i don't see where you define sub. My best guess after reading your code is that sub should be the selected title in the first list view. Therefore this call should look like this:
cursor=dbHelper.getsubcategory(sqLiteDatabase,selectedData);

Android SQLite:How to search a specific value in a database?

I am creating a database based application which requires to search through the database in a specific column for a name and then list all entries which are filtered by the keyword.
For example
Database entries:
1 Test 123 chicken
If someone searches chicken, it will output or direct towards the entry 1.
you need to use WHERE clause along with your SELECT statement,
SELECT *
FROM tableName
WHERE name = 'chicken'
String arg = "chicken";
String query = "select * from table_name where title=\""+ arg + "\"";
Cursor cs = mSqlDB.rawQuery(query, null);
You should have your selected row in cursor cs.
Imagine that you have a button and you click it...Try it:
Button saveButton = (Button) findViewById(R.id.search_button);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String searchStr = search.getText().toString(); // Here is "chicken"
Cursor c = sampleDB.rawQuery("SELECT Id, Name, Price FROM "+SAMPLE_TABLE_NAME+" WHERE Name like '"+searchStr+"'", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
int idNumber = c.getInt(c.getColumnIndex("Id"));
Log.v("IdNumber", id);
}while (c.moveToNext());
}
}
}
});

facing difficulties in getting contacts in listview

I am trying to get all the contacts of the phone in a listview with checkboxes in order to select multiple contacts at a time. I have written some code which is creating the same number of rows as the number of contacts in my emulator. But the problem is the name and number of the contacts are not appearing as you can see in the image attached. Moreover when i click Show contacts button to show the selected contacts in Toast that too is not happening.
custcontactview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="5.0px"
android:paddingLeft="5.0px"
android:paddingTop="5.0px" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/cConName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/checkBox1"
android:layout_marginLeft="15.0dip"
android:layout_toRightOf="#+id/checkBox1"
android:text="Small Text"
android:textAppearance="?android:textAppearanceSmall" />
<TextView
android:id="#+id/cConNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/cConName"
android:layout_marginLeft="15.0dip"
android:layout_toRightOf="#id/checkBox1"
android:text="Medium Text"
android:textAppearance="?android:textAppearanceMedium" />
</RelativeLayout>
activity_contacts_picker.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/btnShow" >
</ListView>
</RelativeLayout>
ContactsPicker.java
public class ContactsPicker extends ListActivity {
protected Object mActionMode;
public int selectedItem = -1;
private Button btnShowContacts;
private ListView myListView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_picker);
myListView = getListView();
btnShowContacts = (Button) findViewById(R.id.btnShow);
btnShowContacts.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_SHORT).show();
String name = null;
String number = null;
long [] ids = myListView.getCheckedItemIds();
for(long id : ids) {
Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
while(contact.moveToNext()){
name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
number = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
Toast.makeText(getApplicationContext(), "Name: " +name + "\n" + "Number: " + number , Toast.LENGTH_LONG).show();
}
}
});
ArrayList<Map<String, String>> list = buildData();
String[] from = { "name", "purpose" };
int[] to = { R.id.cConName, R.id.cConNum };
SimpleAdapter adapter = new SimpleAdapter(this, list,R.layout.custcontactview, from, to);
setListAdapter(adapter);
}
private ArrayList<Map<String, String>> buildData() {
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.clear();
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null,null);
while (people.moveToNext()) {
String contactName = people.getString(people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactId = people.getString(people.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = people.getString(people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ((Integer.parseInt(hasPhone) > 0)) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Map<String, String> NamePhoneType = new HashMap<String, String>();
NamePhoneType.put("Name", contactName);
NamePhoneType.put("Phone", phoneNumber);
list.add(NamePhoneType);
}
phones.close();
}
}
people.close();
startManagingCursor(people);
return list;
}
}
But the problem is the name and number of the contacts are not
appearing as you can see in the image attached
First of all, I guess you checked and see that you have real values in the ArrayList list in the buildData method. Second you use the key names "Name" and "Phone" when you add the values to the HashMap, but in the from String array that you use in the SimpleAdapter you use the values "name" and "purpose". In the from String array you need to have the same keys as you have in the HashMap.
Moreover when i click Show contacts button to show the selected
contacts in Toast that too is not happening.
First, you can't use ListView's default mechanism for checked items when you have a custom row view. If you want to get the checked items you'll need to manage the state of the CheckBox from the row yourself. The getCheckedItemIds() method will not return something valid and the query will fail returning any valid results. Instead you should implement your own custom adapter and return the row's HashMap(which will contain the name and the phone) with SimpleAdapter.getItem method. This way you'll avoid the need to query the contacts again.
call notifyDataSetChanged(); You need to refresh the list..

Begginner working with ListAdapters / SQLite Database

My programming knowledge is slim, i discovered Java and the Android SDK some days ago.
I have a SQLiteDatabase, a SQLiteOpenHelper, and a Cursor working properly
( means i think i understood how to create/open a DB using a SQLiteOpenHelper, make queries on my DB and get a cursor )
currently, i'm wrapping i + labName + labCity into a single results String, and display into a single TextView R.id.label
Is it possible to bind labName to R.id.label, and bind labCity to another TextView R.id.label2 ?
Here is the code of my ListActivity i need help with :
public class MainLabList extends ListActivity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_lab_list);
// DB
GestionDB gdb = new GestionDB(this, GestionDB.DATABASE_NAME, null, GestionDB.DATABASE_VERSION);
SQLiteDatabase theDB = gdb.getWritableDatabase();
// Cursor
String[] columns = {GestionDB.LAB_NAME, GestionDB.LAB_ADDRESS_CITY};
Cursor c =
theDB.query(GestionDB.TABLE_NAME, columns, null, null, null, null, null);
////////
this.setTitle(" " + c.getCount() + " Labs in Local Database");
ArrayList<String> results = new ArrayList<String>();
int i = 0;
c.moveToFirst();
/* Loop through all Results */
do {
i++;
String labName = c.getString(c.getColumnIndex(GestionDB.LAB_NAME));
String labCity = c.getString(c.getColumnIndex(GestionDB.LAB_ADDRESS_CITY));
/* Add current Entry to results. */
results.add("" + i + ": " + labName
+ " (" + labCity + ")");
} while (c.moveToNext());
//need rework
ListView lvLabListing = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> labListAdapter = new ArrayAdapter<String>(this,
R.layout.listing, R.id.label, results );
lvLabListing.setAdapter(labListAdapter);
lvLabListing.setOnItemClickListener(this);
//
// don't forget to close the database
gdb.close();
And the listing.xml i would like to modify :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:layout_width="fill_parent">
<ImageView android:id="#+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="#drawable/icon"></ImageView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/label"></TextView>
</LinearLayout>
My GestionDB class is simple, just define some columns if the database doesn't exist, along with some variables.
You should use a CursorAdapter, perhaps a SimpleCursorAdapter, for this. Here is an example.

Categories

Resources