How to overcome the situation when content of spinner is hidden? - android

I created an android application that takes some data using editText field such as Name, Contact, one radiogroup button, two buttons for save and view stored data and a spinner and stores these information in database when save button is pressed. Datas are displayed at the bottom of the screen when view button is pressed.Usually the spinner shows value 18 as by default.Everything is fine,when I open the application and press save button after entering the fields it saves and when once view button is pressed datas are displayed but I can not insert more data by opening the application once because the content of spinner is hidden now. To do that I need to close the application and then open it once again. How to overcome this problem. Anyone plz run the codes and see what is the problem
.xml file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textContcat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:text="#string/name"
android:textSize="20sp" />
<EditText
android:id="#+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="#string/namehint"
android:inputType="textPersonName"
android:paddingRight="5dp"
android:textSize="20sp" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textAge"
android:layout_width="wrap_content"
android:layout_height="37dp"
android:gravity="center"
android:paddingLeft="5dp"
android:paddingRight="20dp"
android:text="#string/age"
android:textSize="20sp" />
<Spinner
android:id="#+id/spAge"
android:layout_width="80dp"
android:layout_height="match_parent"
android:layout_weight="0.00"
android:clickable="true"
android:gravity="top|center"
android:paddingRight="20dp"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textContcat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:text="#string/contact"
android:textSize="20sp" />
<EditText
android:id="#+id/editContact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="#string/contacthint"
android:inputType="number"
android:paddingRight="5dp"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/sLabel"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="left|center"
android:paddingLeft="5dp"
android:paddingRight="10dp"
android:text="#string/sx"
android:textSize="20sp" />
<RadioGroup
android:id="#+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/malebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/mal"
android:textSize="20sp" />
<RadioButton
android:id="#+id/femalebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/femal"
android:textSize="20sp" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/savebutton"
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/save"
android:textSize="20sp" />
<Button
android:id="#+id/viewbutton"
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/view"
android:textSize="20sp" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
</TableRow>
</TableLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray" />
<TextView
android:id="#+id/tvSQLinfo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:padding="5dp"
android:text="#string/nullvalue"
android:textColor="#color/text_color"
android:textSize="20sp" >
</TextView>
</LinearLayout>
.java file:
public class SqlLiteExample extends Activity implements OnClickListener,
OnItemSelectedListener {
Button sqlUpdate, sqlView;
EditText etName, etContact;
RadioGroup myRadioGrp;
RadioButton rbtn1, rbtn2;
Spinner sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlliteexample);
sqlUpdate = (Button) findViewById(R.id.savebutton);
etName = (EditText) findViewById(R.id.editName);
etContact = (EditText) findViewById(R.id.editContact);
rbtn1 = (RadioButton) findViewById(R.id.malebutton);
rbtn2 = (RadioButton) findViewById(R.id.femalebutton);
sqlView = (Button) findViewById(R.id.viewbutton);
sqlView.setOnClickListener(this);
sqlUpdate.setOnClickListener(this);
uI();
spElements();
}
private void spElements() {
// TODO Auto-generated method stub
List<String> ages = new ArrayList<String>();
for (int i = 18; i <= 99; i++) {
ages.add(String.valueOf(i));
}
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, ages);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
sp.setAdapter(dataAdapter);
}
private void uI() {
// TODO Auto-generated method stub
sp = (Spinner) findViewById(R.id.spAge);
sp.setOnItemSelectedListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.savebutton:
boolean didWork = true;
try {
String name = etName.getText().toString();
String age = (String) sp.getSelectedItem();
String contact = etContact.getText().toString();
myRadioGrp = (RadioGroup) findViewById(R.id.RadioGroup01);
String sex = ((RadioButton) this.findViewById(myRadioGrp
.getCheckedRadioButtonId())).getText().toString();
MyDB entry = new MyDB(SqlLiteExample.this);
entry.open();
entry.createEntry(name, age, contact, sex);
entry.close();
} catch (Exception e) {
didWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
} finally {
if (didWork) {
Dialog d = new Dialog(this);
d.setTitle("Updated");
TextView tv = new TextView(this);
tv.setText("Succesfully");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.viewbutton:
Intent i = new Intent("com.bysakiralam.mydatabase.DISPLAYRECORDS");
startActivity(i);
break;
}
}
#Override
public void onItemSelected(AdapterView<?> main, View arg1, int position,
long Id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Displayrecords.java :
public class DisplayRecords extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlliteexample);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
MyDB info = new MyDB(this);
try {
info.open();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String data = info.getData();
info.close();
tv.setText(data);
}
}
MyDB.java :
public class MyDB {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "persons_name";
public static final String KEY_AGE = "persons_age";
public static final String KEY_CONTACT = "persons_contact";
public static final String KEY_SEX = "gender";
private static final String DATABASE_NAME = "MyDatabase";
private static final String DATABASE_TABLE = "peopleTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
+ " TEXT NOT NULL, " + KEY_AGE + " TEXT NOT NULL, "
+ KEY_CONTACT + " TEXT NOT NULL, " + KEY_SEX
+ " TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public MyDB(Context c) {
ourContext = c;
}
public MyDB open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name, String age, String contact, String sex) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_AGE, age);
cv.put(KEY_CONTACT, contact);
cv.put(KEY_SEX, sex);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_AGE,
KEY_CONTACT, KEY_SEX };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iAGE = c.getColumnIndex(KEY_AGE);
int iCONTACT = c.getColumnIndex(KEY_CONTACT);
int iSEX = c.getColumnIndex(KEY_SEX);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + "\t\t" + c.getString(iName)
+ "\t" + c.getString(iAGE) + "\t\t" + c.getString(iCONTACT)
+ "\t" + c.getString(iSEX) + "\n";
}
return result;
}
}

Maybe you have to reset the spinner once you save or view an entry? (Perhaps in the onClick methods of the save/view buttons)
Also the xml file doesn't seem right as you have a Linear Layout within a ScrollView.

Related

How to send List View values to the another activity in android

i am creating a simple crud system in android.i can view all data in to Listview. if i select a item from the list view it going to another activity for edit. but pass data to the Another activity successfully. but how to assign to textfields. i can pass only one textfield. how to pass values in to the relavent textfields. i attached the screen shot and codes below
Screen Shots
view.xml
<LinearLayout 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="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".view">
<ListView
android:id="#+id/lst1"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</LinearLayout>
View.java
public class view extends AppCompatActivity {
ListView lst1;
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
SQLiteDatabase db = openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
lst1 = findViewById(R.id.lst1);
Cursor c = db.rawQuery("select * from record",null);
int id = c.getColumnIndex("id");
int name = c.getColumnIndex("name");
int age = c.getColumnIndex("age");
c.moveToFirst();
titles.clear();
arrayAdapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,titles);
lst1.setAdapter(arrayAdapter);
if(c.moveToFirst()) {
do {
titles.add(c.getString(id) + " \t " + c.getString(name) + " \t " + c.getString(age));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tt = titles.get(position).toString();
Intent i = new Intent(getApplicationContext(),edit.class);
i.putExtra("age",tt);
startActivity(i);
}
});
}
Edit.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity = "center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit System"
android:textColor="#color/colorAccent"
android:textSize="40dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID" />
<EditText
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Age" />
<EditText
android:id="#+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Edit" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Delete" />
</LinearLayout>
Edit.java
public class edit extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
EditText ed1 = findViewById(R.id.age);
Intent i = getIntent();
String ttt = i.getStringExtra("age").toString();
ed1.setText(ttt);
}
}
Create one pojo class like
class student{
String id,
String name,
String age,
String titles
}
now replace below code
if(c.moveToFirst()) {
do {
titles.add(c.getString(id) + " \t " + c.getString(name) + " \t " + c.getString(age));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tt = titles.get(position).toString();
Intent i = new Intent(getApplicationContext(),edit.class);
i.putExtra("age",tt);
startActivity(i);
}
});
with
ArrayList<student> stud = new ArrayList<student>();
if(c.moveToFirst()) {
do {
student stu = new student()
stu.id = c.getString(id);
stu.name = c.getString(name);
stu.age = c.getString(age);
//you need to add the Student object stu not the ArrayList Object stud
stud.add(stu);
titles.add(c.getString(id) + " \t " + c.getString(name) + " \t " + c.getString(age));
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tt = titles.get(position).toString();
student stu = stud.get(position);
Intent i = new Intent(getApplicationContext(),edit.class);
i.putExtra("age",stu.age);
startActivity(i);
}
});
You need to create a class for your custom items:
class Student{
String id;
String name;
String age;
String title;
public Student(String id, String name, String age)
{
this.id = id;
this.name = name;
this.age = age;
title = id + " \t" +name+" \t"+age;
}
}
//View.java:
if(c.moveToFirst()) {
do {
Student tmpStudent = new Student(c.getString(id), c.getString(name), c.getString(age));
titles.add(tmpStudent.title);
} while (c.moveToNext());
arrayAdapter.notifyDataSetChanged();
lst1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String studentString[] = titles.get(position).toString().Split(" \t");
Student tmpStringStudent = new Student(studentString[0], studentString[1], studentString[2]);
Intent i = new Intent(getApplicationContext(),edit.class);
i.putExtra("id",tmpStringStudent.id);
i.putExtra("name",tmpStringStudent.name);
i.putExtra("age",tmpStringStudent.age);
startActivity(i);
}
});
}
//Edit.java:
public class edit extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
EditText ageEditText = findViewById(R.id.age);
EditText idEditText = findViewById(R.id.id);
EditText nameEditText = findViewById(R.id.name);
Intent i = getIntent();
String id = i.getStringExtra("id").toString();
String name = i.getStringExtra("name").toString();
String age = i.getStringExtra("age").toString();
idEditText.setText(id);
nameEditText.setText(name);
ageEditText.setText(age);
}
}
I hope this helps.

Android SQLite cursor/adapter cannot get data from database

I have a gridview class here:
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#color/colorPrimaryDark"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/topContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="7">
<TextView
android:id="#+id/textView0"
android:background="#color/white"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID: "
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView1"
android:background="#color/purple"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridCode"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView2"
android:background="#color/green"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridDay"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView3"
android:background="#color/orange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridStart"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView4"
android:background="#color/blue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridDuration"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView5"
android:background="#color/yellow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridType"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView6"
android:background="#color/red"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridRoom"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
</LinearLayout>
<GridView
android:id="#+id/gridTable"
android:layout_below="#+id/topContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="10dip"
android:verticalSpacing="15dip"
android:stretchMode="columnWidth"
android:gravity="center"
android:numColumns="7"
android:background="#color/colorPrimary"
android:textSize="14sp"
>
</GridView>
</RelativeLayout>
and a database helper:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
//database information
public static final String DATABASE_NAME = "timetable.db";
public static final String TABLE_NAME = "timetable_data";
//the data each column will store
public static final String COL_1 = "ID";
public static final String COL_2 = "CODE";
public static final String COL_3 = "DAY";
public static final String COL_4 = "START";
public static final String COL_5 = "DURATION";
public static final String COL_6 = "TYPE";
public static final String COL_7 = "ROOM";
//construct the database
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,CODE TEXT,DAY TEXT,START TEXT,DURATION TEXT,TYPE TEXT,ROOM TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String code, String day, String start, String duration, String type, String room)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,code);
contentValues.put(COL_3,day);
contentValues.put(COL_4,start);
contentValues.put(COL_5,duration);
contentValues.put(COL_6,type);
contentValues.put(COL_7, room);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("select * from "+TABLE_NAME,null);
return data;
}
public Integer deleteEntry(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME,"ID = ?", new String [] {id});
}
}
I'm trying to populate this gridview with data stored in the database, everything compiles fine, but in the app i get an error saying that data from Col-1 (the id column) cannot be retrieved.
this is the gridviewactivity.java class mentioned in the above code:
public class GridViewActivity extends MainActivity
{
private GridView gridTable;
private ArrayList<String> moduleList;
private ArrayAdapter<String> adapter;
private Cursor data;
DatabaseHelper timetableDB;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.gridview);
//GridView
gridTable=(GridView) findViewById(R.id.gridTable);
String id, code, day, time, duration, type, room;
id = ""; code = ""; day = ""; time = "";
duration = ""; type = ""; room = "";
timetableDB = new DatabaseHelper(getBaseContext());//getting the context object
timetableDB.getAllData();
try
{
//for holding retrieve data from query and store in the form of rows
Cursor data=timetableDB.getAllData();
moduleList = new ArrayList<>();
//Move the cursor to the first row.
if(data.moveToFirst())
{
do
{
id = data.getString(data.getColumnIndex ("id"));
code = data.getString(data.getColumnIndex ("code"));
day = data.getString(data.getColumnIndex ("day"));
time = data.getString(data.getColumnIndex ("time"));
duration = data.getString(data.getColumnIndex ("duration"));
type = data.getString(data.getColumnIndex ("type"));
room = data.getString(data.getColumnIndex ("room"));
//add in to array list
moduleList . add(id);
moduleList . add(code);
moduleList . add(day);
moduleList . add(time);
moduleList . add(duration);
moduleList . add(type);
moduleList . add(room);
}
while(data.moveToNext());//Move the cursor to the next row.
adapter = new ArrayAdapter<>(getApplicationContext(),
android.R.layout.simple_spinner_item,moduleList);
gridTable.setAdapter(adapter);
}
else
{
Toast.makeText(getApplicationContext(),
"No data found", Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
Toast.makeText(getApplicationContext(),
"No data found "+e.getMessage(), Toast.LENGTH_LONG).show();
}
timetableDB.close();
}
}
am i using the cursor correctly in this class?
thanks!
am i using the cursor correctly in this class?
Yes, but problem is creating ArrayAdapter in wrong place.
Create object of ArrayAdapter after adding all items in moduleList ArrayList from Cursor.like:
do{
// add items in moduleList
}
while(data.moveToNext());//Move the cursor to the next row.
// create ArrayAdapter object here:
adapter = new ArrayAdapter<>(getApplicationContext(),
android.R.layout.simple_spinner_item,moduleList);
// call setAdapter
gridTable.setAdapter(adapter);
The "id" column doesn't exist.
When you're creating the database you're using "ID" as the column name and not "id" so when you're calling data.getString(data.getColumnIndex("id")); it won't be able to find the column.

How to get the value from element in the GridView in Android app?

basically, I'm a noob in Android programming and among other problems I'm stuck with this one: I have a GridView declared in my main layout and the XML definition for this grid in the separate xml. I'm adapting grid with SimpleCursorAdapter (not custom adapter). The thing is that I want to remember the value of corresponding ROW_ID when I touch the checkbox in the one of the displayed rows of data ... So, is there an option to do this without the need to customize SimpleCursorAdapter (BTW, is it possible?).
Here are snippets of Layout XML files and code, where I adapt cursor with SimpleCursorAdapter:
main.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"
android:background="#BAF0ED"
android:gravity="right" >
<GridView
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="#+id/view1"
android:numColumns="2" >
</GridView>
</RelativeLayout>
grid.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<TextView
android:id="#+id/row_ID"
android:layout_width="50px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="5px"
android:textColor="#4BA79E"
android:textSize="22dp" />
<TextView
android:id="#+id/name"
android:layout_width="50px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="5px"
android:textSize="22dp" />
<TextView
android:id="#+id/email"
android:layout_width="50px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="5px"
android:textSize="22dp" />
<CheckBox
android:id="#+id/chk"
android:layout_width="10px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="x"/>
</TableRow>
</TableLayout>
Using SimpleCursorAdapter:
public void showGridData() {
#SuppressWarnings("static-access")
String[] fromColumns = { db.KEY_ROWID, db.KEY_NAME, db.KEY_EMAIL };
int[] toViews = new int[] { R.id.row_ID, R.id.name, R.id.email };
db.openDatabase();
#SuppressWarnings("deprecation")
SimpleCursorAdapter sCAdapter = new SimpleCursorAdapter(this,
R.layout.table_row, db.getContacts(), fromColumns, toViews);
sCAdapter.setViewResource(R.layout.table_row);
gv.setAdapter(sCAdapter);
db.closeDatabase();
}
...and the method to read the value of the ROW_ID in the same record as the chebox is positioned (I'am getting allways the value of the first ROW_ID, wheather I touch first, second or n-th checkbox and this is the problem!):
public void x(View view) {
TextView tv = (TextView) findViewById(R.id.row_ID);
recordIds.add(Long.valueOf(tv.getText().toString()));
long[] longArray = new long[recordIds.size()];
for (int i = 0; i < recordIds.size(); i++) {
longArray[i] = recordIds.get(i);
Toast.makeText(this, String.valueOf(longArray[i]),Toast.LENGTH_LONG).show();
}
}
Thanks in advance and sorry for bothering you, regards,
Erik D.
add1 (1. edit)
Dear friends! Thank you all very much for the answer, but unfortunatelly this suggestions doesn't work for me. Let me post entire code, which I had altered with "setOnItemClickListener(new OnItemClickListener()". It still doesn't work...
I'm posting entire code (xml & java) if someone would have some spare time to look at it--I can't figure out what is wrong.
**activity_main.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"
android:gravity="right" >
<GridView
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText2"
android:layout_marginTop="20dp"
android:numColumns="3" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_toRightOf="#+id/button1"
android:ems="10"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/gridView1"
android:layout_toLeftOf="#+id/button1"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:onClick="AddRecord"
android:text="Insert" />
</RelativeLayout>
**table_row.xml**
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<TextView
android:id="#+id/row_ID"
android:layout_width="50px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:clickable="true"
android:padding="5px"
android:textSize="22dp" />
<TextView
android:id="#+id/name"
android:layout_width="50px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:clickable="true"
android:padding="5px"
android:textSize="22dp" />
<TextView
android:id="#+id/email"
android:layout_width="50px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:clickable="true"
android:padding="5px"
android:textSize="22dp" />
<CheckBox
android:id="#+id/chk"
android:layout_width="10px"
android:layout_height="wrap_content"
android:layout_weight="1" />
</TableRow>
</TableLayout>
*MainActivity.java*
> package net.learn2develop.databases;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
DBAdapter db;
EditText name, mail;
GridView gv;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.editText1);
mail = (EditText) findViewById(R.id.editText2);
db = new DBAdapter(this);
gv = (GridView) findViewById(R.id.gridView1);
showGridData();
}
public void AddRecord(View view) {
if (!(name.getText().toString().isEmpty())
&& !(mail.getText().toString().isEmpty())) {
db.openDatabase();
if (db.insertContact(name.getText().toString(), mail.getText()
.toString()) >= 0) {
showMessage("Record added succesfully!", "Inserting...");
db.closeDatabase();
showGridData();
}
} else {
showMessage("You can't add empty record!", "Inserting...");
}
}
public void showGridData() {
String[] fromColumns = { db.KEY_ROWID, db.KEY_NAME, db.KEY_EMAIL };
int[] toViews = new int[] { R.id.row_ID, R.id.name, R.id.email };
db.openDatabase();
SimpleCursorAdapter sCAdapter = new SimpleCursorAdapter(this,
R.layout.table_row, db.getContacts(), fromColumns, toViews);
sCAdapter.setViewResource(R.layout.table_row);
gv.setAdapter(sCAdapter);
// Implement On Item click listener
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
db.closeDatabase();
}
public void showMessage(String message, String source) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setCancelable(false);
dlgAlert.setMessage(message);
dlgAlert.setTitle(source);
dlgAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
}
*DBAdapter.java*
package net.learn2develop.databases;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
static final String KEY_ROWID = "_id";
static final String KEY_NAME = "name";
static final String KEY_EMAIL = "email";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "MyDB";
static final String DATABASE_TABLE = "contacts";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, " + KEY_EMAIL + " text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {// CONSTRUCTOR!!
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
public DBAdapter openDatabase() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void closeDatabase() {
DBHelper.close();
}
public long insertContact(String name, String email) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteContact(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor getContacts() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME,
KEY_EMAIL }, null, null, null, null, null);
}
public Cursor getContact(long rowId) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_NAME, KEY_EMAIL }, KEY_ROWID + "=" + rowId,
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateContact(long rowId, String name, String email) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
Dear friends, thanks in advance once again, regards,
Erik D.
You can use setTag and getTag methods of View class to tie a piece of information to your views.
You need to implement ItemClickListener. onItemClick will be invoked for each item clicked in the gridview and provides the position of click.
Check this sample code on how to implement it. Fetch this position data from adapter.
I have found the origin of the problem - basically, all it has to be done is defining the view element of the GridView with:
android:focusable="false"
android:focusableInTouchMode="false"
for instance:
<TextView
android:id="#+id/row_ID"
android:layout_width="50px"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:textSize="20dp" />
With these two parameters elements of the GridView do not steal the focus of the grid and listener on the grid works.
Have a great time,
Erik D.

Show immediate changes when data deleted from database

View Database XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/wood_bg" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:text="Daily Fruit Log"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold"/>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableRow>
<TextView
android:layout_width="110dp"
android:layout_height="fill_parent"
android:text="Name of fruit"
android:layout_weight="1"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="No Of Fruit"
android:layout_weight="1"
android:textStyle="bold"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Total Calories"
android:layout_weight="1"
android:textStyle="bold"/>
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<TableRow>
<TextView
android:id="#+id/view"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:text="food"
android:layout_weight="1" />
<TextView
android:id="#+id/view1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="1"
android:layout_weight="1"/>
<TextView
android:id="#+id/view2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="20"
android:layout_weight="1"/>
</TableRow>
</TableLayout>
<Button
android:id="#+id/bdelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Log"
android:layout_gravity="center"
android:layout_marginTop="30dp" />
Java class of View Database page:
public class FruitLog extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fruitlog);
TextView tv = (TextView) findViewById(R.id.view);
TextView tv1 = (TextView) findViewById(R.id.view1);
TextView tv2 = (TextView) findViewById(R.id.view2);
FruitDB info = new FruitDB(this);
info.open();
String data = info.getName();
String data1 = info.getNum();
String data2 = info.getCal();
info.close();
tv.setText(data);
tv1.setText(data1);
tv2.setText(data2);
Button save = (Button) findViewById(R.id.bdelete);
save.setTextColor(Color.BLUE);
save.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
FruitDB info = new FruitDB(FruitLog.this);
info.open();
info.deleteAll();
info.close();
}
});
}
I have edited the code, now I can delete all the data in my page, but the issue is that, I have to navigate back and enter this FruitLog page to see the changes (all rows deleted).
I want to see a immediate result when the user click 'Clear Log' Button without navigating back and front.
This method in your db class:
public boolean deleteAll() {
// Returns true if number of deleted rows is larger than 0;
return mDb.delete(DATABASE_TABLE, null, 1) > 0;
}
In the onClickListener:
public void onClick(View v) {
FruitDB db = new FruitDB(YourClass.this);
db.open();
db.deleteAll();
db.close();
}
To delete entire table:
db.delete(DATABASE_TABLE, null, null);
To delete particular records in a table:
db.delete(DATABASE_TABLE, whereCondition, null);
for eg:
db.delete(DATABASE_TABLE, "KEY_NAME='mango'", null);
Button save = (Button) findViewById(R.id.bdelete);
save.setTextColor(Color.BLUE);
save.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
DbHelper myDbHelper =new DbHelper(Activity.this);
try{
myDbHelper.open();
myDbHelper.delete();
}catch(Exception e){
e.printStackTrace();
}finally{
myDbHelper.close();
}
}
});
create a method in your DBHelper class
public void delete() {
ourDatabase.execSQL("delete from "+ DATABASE_TABLE);
ourDatabase.execSQL("UPDATE sqlite_sequence set "+ KEY_ROWID + " =0 where name= '"+DATABASE_TABLE+"'");
}
It will delete all records
public void deleteAll() {
final SQLiteDatabase db = getWritableDatabase();
db.delete(DATABASE_TABLE, null, null);
db.close();
}
Move this code to save.setOnClickListener(new View.OnClickListener(){..} after deleting
or move it to onResume()
FruitDB info = new FruitDB(this);
info.open();
String data = info.getName();
String data1 = info.getNum();
String data2 = info.getCal();
info.close();
tv.setText(data);
tv1.setText(data1);
tv2.setText(data2);

SQLITE LISTVIEW FILTER USING EDITEXT

Please i really need help with listview filter.because I've seen many tutorials but it doesn't work.and i really tired of this
just i need the EdiText filter
my project contain four classes:
1-LocationActivity (l'activity prencipale)
public class LocationActivity extends Activity implements LocationListener{
public final static String LOCATION_ID = "location_id";
private long location_id;
private EditText name;
private EditText comment;
private RatingBar ratevalue;
private EditText latitude;
private EditText longitude;
private TextView current_latitude;
private TextView current_longitude;
private TextView current_source;
private TextView current_accuracy;
private LocationDatabase db;
private BestLocationProxy best_location_proxy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new LocationDatabase(this);
best_location_proxy = new BestLocationProxy(this);
if (savedInstanceState != null) {
location_id = savedInstanceState.getLong(LOCATION_ID);
}
Intent intent = getIntent();
location_id = intent.getLongExtra(LOCATION_ID, -1);
setContentView(R.layout.location);
name = (EditText) findViewById(R.id.name);
comment = (EditText) findViewById(R.id.comment);
ratevalue = (RatingBar) findViewById(R.id.ratingbar);
latitude = (EditText) findViewById(R.id.latitude);
longitude = (EditText) findViewById(R.id.longitude);
current_latitude = (TextView) findViewById(R.id.current_latitude);
current_longitude = (TextView) findViewById(R.id.current_longitude);
current_source = (TextView) findViewById(R.id.current_source);
current_accuracy = (TextView) findViewById(R.id.current_accuracy);
updateLocation(best_location_proxy.getLastKnownLocation());
Button set_location = (Button) findViewById(R.id.set_location);
set_location.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Location l = best_location_proxy.getLastKnownLocation();
if (l == null) {
return;
}
latitude.setText(Double.toString(l.getLatitude()));
longitude.setText(Double.toString(l.getLongitude()));
}
});
Button closeButton = (Button) findViewById(R.id.close_location_window);
closeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
if (location_id != -1) {
Cursor c = db.getLocation(location_id);
if (c.getCount() != 1) {
finish();
return;
}
c.moveToFirst();
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int comment_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_COMM);
int ratevalue_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_RATE);
int latitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
name.setText(c.getString(name_id));
comment.setText(c.getString(comment_id));
ratevalue.setRating(c.getLong(ratevalue_id));
latitude.setText(Double.toString(c.getDouble(latitude_id)));
longitude.setText(Double.toString(c.getDouble(longitude_id)));
c.close();
}
}
#Override
protected void onResume() {
super.onResume();
best_location_proxy.requestLocationUpdates(100000, 0, this);
}
#Override
protected void onPause() {
super.onPause();
best_location_proxy.removeUpdates(this);
String s_name = name.getText().toString();
if (s_name.equals("")) {
return;
}
String s_comment = comment.getText().toString();
if (s_comment.equals("")) {
return;
}
Double d_ratevalue = (double) ratevalue.getRating();
Double d_latitude = null;
String s_latitude = latitude.getText().toString();
if (!s_latitude.equals("")) {
d_latitude = Double.parseDouble(s_latitude);
}
Double d_longitude = null;
String s_longitude = longitude.getText().toString();
if (!s_longitude.equals("")) {
d_longitude = Double.parseDouble(s_longitude);
}
if (location_id != -1) {
db.updateLocation(location_id, s_name, s_comment, d_ratevalue, d_latitude, d_longitude);
} else {
location_id = db.createLocation(s_name, s_comment, d_ratevalue, d_latitude, d_longitude);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(LOCATION_ID, location_id);
}
private void updateLocation(Location l){
if (l == null){
current_source.setText(R.string.no_provider);
current_latitude.setText(R.string.unavailable);
current_longitude.setText(R.string.unavailable);
current_accuracy.setText(R.string.unavailable);
return;
}
String source;
if (l.getProvider().equals(LocationManager.GPS_PROVIDER)){
source = getString(R.string.location_map);
} else if (l.getProvider().equals(LocationManager.NETWORK_PROVIDER)){
source = getString(R.string.cell);
} else {
source = getString(R.string.unknown);
}
current_source.setText(source);
current_latitude.setText(Double.toString(l.getLatitude()));
current_longitude.setText(Double.toString(l.getLongitude()));
current_accuracy.setText(Float.toString(l.getAccuracy()));
}
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
2-LocationListActivity (listview activity)
public class LocationListActivity extends ListActivity {
private Cursor locations;
private LocationDatabase db;
private final static String RADAR_ACTION = "com.google.android.radar.SHOW_RADAR";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new LocationDatabase(this);
setContentView(R.layout.list);
registerForContextMenu(this.getListView());
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor c = (Cursor) parent.getAdapter().getItem(position);
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int latitude_id = c
.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c
.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
String name = c.getString(name_id);
float latitude = c.getFloat(latitude_id);
float longitude = c.getFloat(longitude_id);
startBest(latitude, longitude, name);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem add = menu.add(R.string.location_add);
add.setIcon(android.R.drawable.ic_menu_add);
add.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent();
i.setClass(LocationListActivity.this, LocationActivity.class);
startActivity(i);
return true;
}
});
return true;
}
#Override
protected void onResume() {
super.onResume();
updateList();
}
#Override
protected void onStop() {
super.onStop();
if (locations != null){
locations.close();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
Cursor c = (Cursor) getListView().getItemAtPosition(info.position);
int id_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_ID);
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int latitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
final long id = c.getLong(id_id);
final String name = c.getString(name_id);
final float latitude = c.getFloat(latitude_id);
final float longitude = c.getFloat(longitude_id);
menu.setHeaderTitle(name);
MenuItem map = menu.add(R.string.location_map);
map.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
startMap(latitude, longitude, name);
return true;
}
});
MenuItem edit = menu.add(R.string.location_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent();
i.setClass(LocationListActivity.this, LocationActivity.class);
i.putExtra(LocationActivity.LOCATION_ID, id);
startActivity(i);
return true;
}
});
MenuItem delete = menu.add(R.string.location_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
db.deleteLocation(id);
updateList();
return true;
}
});
}
private void updateList() {
if (locations != null) {
locations.close();
}
locations = db.getAllLocations();
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, locations,
new String[] { LocationDatabase.FIELD_LOCATIONS_NAME, },
new int[] { android.R.id.text1 });
setListAdapter(adapter);
}
private void startRadar(float latitude, float longitude){
Intent i = new Intent(RADAR_ACTION);
i.putExtra("latitude", latitude);
i.putExtra("longitude", longitude);
startActivity(i);
}
private void startMap(float latitude, float longitude, String name){
Formatter f = new Formatter(Locale.US);
f.format("geo:0,0?q=%1$.5f,%2$.5f(%3$s)", latitude, longitude, name);
Uri uri = Uri.parse(f.toString());
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
}
private void startBest(float latitude, float longitude, String name){
if (isRadarAvailable()){
startRadar(latitude, longitude);
} else {
startMap(latitude, longitude, name);
}
}
private boolean isRadarAvailable(){
return isIntentAvailable(RADAR_ACTION);
}
private boolean isIntentAvailable(String action) {
PackageManager packageManager = getPackageManager();
final Intent intent = new Intent(action);
#SuppressWarnings("rawtypes")
List list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}
3-LocationDataase (database activity sqlite)
public class LocationDatabase extends SQLiteOpenHelper {
public final static String TAG = LocationDatabase.class.toString();
public final static String DB_NAME = "locations";
public final static int DB_VERSION = 1;
public final static String TABLE_LOCATIONS = "locations";
public final static String FIELD_LOCATIONS_ID = "_id";
public final static String FIELD_LOCATIONS_NAME = "name";
public final static String FIELD_LOCATIONS_COMM = "comment";
public final static String FIELD_LOCATIONS_RATE = "ratevalue";
public final static String FIELD_LOCATIONS_LATITUDE = "latitude";
public final static String FIELD_LOCATIONS_LONGITUDE = "longitude";
public final static String[] PROJECTION_LOCATIONS = { FIELD_LOCATIONS_ID,
FIELD_LOCATIONS_NAME, FIELD_LOCATIONS_COMM, FIELD_LOCATIONS_RATE, FIELD_LOCATIONS_LATITUDE,
FIELD_LOCATIONS_LONGITUDE };
public LocationDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
getWritableDatabase(); // make upgrades work
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_LOCATIONS + " ( " +
FIELD_LOCATIONS_ID + " INTEGER PRIMARY KEY NOT NULL, " +
FIELD_LOCATIONS_NAME + " Text, " +
FIELD_LOCATIONS_COMM + " Text, " +
FIELD_LOCATIONS_RATE + " REAL, " +
FIELD_LOCATIONS_LATITUDE + " REAL, "
+ FIELD_LOCATIONS_LONGITUDE + " REAL )");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
public long createLocation(String name, String comment, Double ratevalue, Double latitude, Double longitude) {
Log.d(TAG, "Inserting location " + name + comment + ratevalue);
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_LOCATIONS_NAME, name);
values.put(FIELD_LOCATIONS_COMM, comment);
values.put(FIELD_LOCATIONS_RATE, ratevalue);
values.put(FIELD_LOCATIONS_LATITUDE, latitude);
values.put(FIELD_LOCATIONS_LONGITUDE, longitude);
long id = db.insert(TABLE_LOCATIONS, null, values);
Log.d(TAG, Long.toString(id));
db.close();
return id;
}
public void updateLocation(Long location_id, String name, String comment, Double ratevalue, Double latitude,
Double longitude) {
Log.d(TAG, "Updating location");
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_LOCATIONS_NAME, name);
values.put(FIELD_LOCATIONS_COMM, comment);
values.put(FIELD_LOCATIONS_RATE, ratevalue);
values.put(FIELD_LOCATIONS_LATITUDE, latitude);
values.put(FIELD_LOCATIONS_LONGITUDE, longitude);
db.update(TABLE_LOCATIONS, values, "_id = ?",
new String[] { location_id.toString() });
db.close();
}
public Cursor getAllLocations() {
Log.d(TAG, "Selecting all locations");
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_LOCATIONS, PROJECTION_LOCATIONS, null, null,
null, null, FIELD_LOCATIONS_NAME);
Log.d(TAG, Integer.toString(c.getCount()));
db.close();
return c;
}
public Cursor getLocation(long location_id) {
Log.d(TAG, "Selecting location " + Long.toString(location_id));
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_LOCATIONS, PROJECTION_LOCATIONS, "_id = ?",
new String[] { Long.toString(location_id) }, null, null, null);
Log.d(TAG, Integer.toString(c.getCount()));
db.close();
return c;
}
public void deleteLocation(long location_id){
Log.d(TAG, "Deleting location " + Long.toString(location_id));
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_LOCATIONS, "_id = ?", new String[] {Long.toString(location_id)});
}
}
4-BestLocationProxy
in the Layout I have location.xml and list.xml
1-location.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="311dp"
android:orientation="vertical"
android:paddingRight="20dip" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="#string/name"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true"
android:id="#+id/name"
android:singleLine="true"
android:layout_weight="1" />
<TextView
android:text="#string/comment"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true"
android:id="#+id/comment"
android:singleLine="true"
android:layout_weight="1" />
<TextView
android:text="#string/Rate"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
</TableLayout>
<RatingBar
android:id="#+id/ratingbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stepSize="1"
/>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:text="#string/latitude"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true"
android:id="#+id/latitude"
android:singleLine="true"
android:layout_weight="1"
android:numeric="signed|decimal" />
<TextView
android:text="#string/longitude"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true"
android:id="#+id/longitude"
android:singleLine="true"
android:layout_weight="1"
android:numeric="signed|decimal" />
</TableLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:text="#string/source"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/current_source"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
<TableRow>
<TextView
android:text="#string/latitude"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/current_latitude"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
<TableRow>
<TextView
android:text="#string/longitude"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/current_longitude"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
<TableRow>
<TextView
android:text="#string/accuracy"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/current_accuracy"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
</TableLayout>
<View
android:layout_width="fill_parent"
android:background="#android:drawable/divider_horizontal_bright"
android:layout_marginBottom="10dip"
android:layout_marginTop="10dip"
android:layout_height="4dip" />
<Button
android:id="#+id/set_location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/set_location" />
<Button
android:id="#+id/close_location_window"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/close" />
</LinearLayout>
</ScrollView>
2- list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:longClickable="true"
android:layout_weight="1" />
<ScrollView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<TextView
android:id="#+id/emptyText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/empty_msg"
android:textSize="20sp"
android:textColor="?android:attr/textColorSecondary"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:lineSpacingMultiplier="0.92" />
</ScrollView>
</LinearLayout>
Sorry...too Long
I think I see what you are trying to do. Here is an example using the ListView's TextFilter:
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
ListView list = new ListView(this);
layout.addView(list);
setContentView(layout);
String[] array = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
}
You need to open the keyboard by long pressing the Menu button.
Unfortunately, this feature is completely inadequate to sort a result set from a CursorAdapter. In fact the TextFilter doesn't even respond when I bound it to a SimpleCursorAdapter.
Solution:
Here's one basic approach, try adding an EditText and a Button. Say, you want to sort the location by name. When the user clicks the button you query your database with what's in the EditText, like this:
db.query(TABLE_LOCATIONS, PROJECTION_LOCATIONS,
FIELD_LOCATIONS_NAME " LIKE '%?%'", editTextString,
null, null, FIELD_LOCATIONS_NAME);
Of course, editTextString is the user's input from the EditText. Now simply set this new Cursor returned from your Database to your adapter like this:
adapter.changeCursor(newCursor);
You will have to use the same approach to sort by more than just the name, but this is the general idea. Design wise you can move the search EditText and Button into a PopUpWindow, or instead of a Button your can re-query the Database with every new letter typed into the EditText with a TextWatcher; there are many different methods. Hope that helps.

Categories

Resources