It's very difficult to explain my problem in English, but I will try.
I have a ListView which should show live the results from a search. When I type "d" in the searchfield it should me show all results that begin with a "d".
The problem is, that it doesn't show me the right results. It shows me the first entry from the original list and not the target entry, but it shows the right numbers entries.
When I have this entries in my ArrayList:
Anti
Beta
Delta
Dirty
Echo
Eleven
Earth
and type "d" in the searchfield, it shows me 2 Hits (which is right), but it shows me Anti and Beta. When I type "e", it shows me 3 Hits (which is right) but it shows me Anti, Beta and Delta.
This is the MainActivity:
package de.resper.pzcrettungsdienstkassel;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ArrayList<HashMap<String, Object>> haupt;
ArrayList<HashMap<String, Object>> code;
ArrayList<HashMap<String, Object>> codeResult;
ListView codeListView;
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeListView = (ListView) findViewById(R.id.listsearch);
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final EditText searchBox=(EditText) findViewById(R.id.searchBox);
sql_helper db = new sql_helper(getApplicationContext());
code = new ArrayList<HashMap<String,Object>>();
code = db.getAllCode();
codeResult = new ArrayList<HashMap<String,Object>>();
final CustomAdapterCode adapter_code = new CustomAdapterCode(this, R.layout.activity_main, codeResult);
codeListView.setAdapter(adapter_code);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString=searchBox.getText().toString();
int textLength=searchString.length();
codeResult.clear();
for(int i=0;i<code.size();i++){
String name=code.get(i).get("name").toString();
if(textLength<=name.length()){
if(searchString.equalsIgnoreCase(name.substring(0,textLength))){
codeResult.add(code.get(i));
Log.d("Suchfeld", String.valueOf(i));
Log.d("Suchfeld", code.get(i).get("name").toString());
}
}
}
adapter_code.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
});
}
private class CustomAdapterCode extends ArrayAdapter<HashMap<String, Object>> {
public CustomAdapterCode(Context context, int textViewResourceId, ArrayList<HashMap<String, Object>> Strings) {
super(context, textViewResourceId, Strings);
}
private class ViewHolder{
TextView code_id, code_layout, name_layout, prio1, prio2, prio3;
}
ViewHolder viewHolder;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView=inflater.inflate(R.layout.code_list_item, null);
viewHolder=new ViewHolder();
viewHolder.code_id=(TextView) convertView.findViewById(R.id.code_id);
viewHolder.code_layout=(TextView) convertView.findViewById(R.id.code_layout);
viewHolder.name_layout=(TextView) convertView.findViewById(R.id.name_layout);
viewHolder.prio1=(TextView) convertView.findViewById(R.id.prio1);
viewHolder.prio2=(TextView) convertView.findViewById(R.id.prio2);
viewHolder.prio3=(TextView) convertView.findViewById(R.id.prio3);
convertView.setTag(viewHolder);
} else {
viewHolder=(ViewHolder) convertView.getTag();
}
viewHolder.code_id.setText(code.get(position).get("_id").toString());
viewHolder.code_layout.setText(code.get(position).get("code").toString());
viewHolder.name_layout.setText(code.get(position).get("name").toString());
viewHolder.prio1.setText(code.get(position).get("prio1").toString());
viewHolder.prio2.setText(code.get(position).get("prio2").toString());
viewHolder.prio3.setText(code.get(position).get("prio3").toString());
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my sql_helper:
package de.resper.pzcrettungsdienstkassel;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class sql_helper extends SQLiteOpenHelper {
private static final String DATABASE_FILE_NAME="pzc";
private static final int SCHEMA_VERSION=1;
public sql_helper(Context context) {
super(context, DATABASE_FILE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE pzc_haupt (_id INTEGER PRIMARY KEY, name TEXT, unter INTEGER);");
db.execSQL("CREATE TABLE pzc_unter (_id INTEGER PRIMARY KEY, name TEXT, haupt INTEGER);");
db.execSQL("CREATE TABLE pzc_code (_id INTEGER PRIMARY KEY,code INTEGER, name TEXT, unter INTEGER, haupt INTEGER, prio1 INTEGER, prio2 INTEGER, prio3 INTEGER);");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('1','124','Anti','0','1','1','0','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('2','130','Beta','0','1','1','0','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('3','201','Delta','1','0','1','1','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('4','202','Dirty','1','0','1','1','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('5','203','Echo','2','0','1','1','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('6','204','Eleven','2','0','1','1','0');");
db.execSQL("INSERT INTO pzc_code (_id,code,name,unter,haupt,prio1,prio2,prio3) VALUES ('7','205','Earth','3','0','1','1','0');");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<HashMap<String,Object>> getAllHaupt() {
ArrayList<HashMap<String,Object>> hauptList = new ArrayList<HashMap<String,Object>>();
String selectQuery = "SELECT * FROM pzc_haupt";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
HashMap<String , Object> haupt;
if (cursor.moveToFirst()) {
do {
haupt = new HashMap<String, Object>();
haupt.put("_id", Integer.parseInt(cursor.getString(0)));
haupt.put("name", cursor.getString(1));
hauptList.add(haupt);
} while (cursor.moveToNext());
}
return hauptList;
}
public ArrayList<HashMap<String,Object>> getAllCode() {
ArrayList<HashMap<String,Object>> codeList = new ArrayList<HashMap<String,Object>>();
String selectQuery = "SELECT * FROM pzc_code ORDER BY _id ASC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
HashMap<String , Object> code;
if (cursor.moveToFirst()) {
do {
code = new HashMap<String, Object>();
code.put("_id", Integer.parseInt(cursor.getString(0)));
code.put("code", Integer.parseInt(cursor.getString(1)));
code.put("name", cursor.getString(2));
if (Integer.parseInt(cursor.getString(5)) == 1) {
code.put("prio1", "\u25CF");
} else {
code.put("prio1", "");
}
if (Integer.parseInt(cursor.getString(6)) == 1) {
code.put("prio2", "\u25CF");
}else{
code.put("prio2", "");
}
if (Integer.parseInt(cursor.getString(7)) == 1) {
code.put("prio3", "\u25CF");
} else {
code.put("prio3", "");
}
codeList.add(code);
} while (cursor.moveToNext());
}
return codeList;
}
}
The activity_main.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" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="#+id/searchBox"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_margin="10dp"
android:hint="#string/suche">
</EditText>
<ListView
android:id="#+id/listsearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="#000000"
android:layout_marginBottom="10dp" />
</LinearLayout>
</LinearLayout>
The code_list_item.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="wrap_content"
android:orientation="horizontal"
android:padding="10dp" >
<TextView android:id="#+id/code_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/prio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textColor="#FF0000" />
<TextView
android:id="#+id/prio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textColor="#FFFF00" />
<TextView
android:id="#+id/prio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:textColor="#40FF00" />
<TextView
android:id="#+id/code_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#000000" />
<TextView
android:id="#+id/name_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#000000"
android:layout_marginLeft="5dp" />
</LinearLayout>
I don't use ListActivity beacause I want to build in one more ListView in this activity.
You are not using codeResult at getView method. You are using original code array. Change code with codeResult like below. Your problem will be solved.
viewHolder.code_id.setText(codeResult.get(position).get("_id").toString());
viewHolder.code_layout.setText(codeResult.get(position).get("code").toString());
viewHolder.name_layout.setText(codeResult.get(position).get("name").toString());
viewHolder.prio1.setText(codeResult.get(position).get("prio1").toString());
viewHolder.prio2.setText(codeResult.get(position).get("prio2").toString());
viewHolder.prio3.setText(codeResult.get(position).get("prio3").toString());
Related
Experts,
I would like to store my Spinner1,Spinner2 and multiple checkbox value,edit text value in to my sqlite database upon submitting the button. I try to tweak the same but no luck. Could you advise experts..
Layout is attached below. Two spinner and multiple check box and one submit button,one edit text.
<?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" >
<!-- Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dip"
android:text="#string/lblAcc" />
<!-- Spinner Dropdown -->
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
android:layout_marginTop="10dip"
/>
<!-- Select Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dip"
android:text="#string/lblSubAcc" />
<!-- Spinner Dropdown -->
<Spinner
android:id="#+id/spinner2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Visit Day" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Saturday" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sunday" />
<CheckBox
android:id="#+id/checkBox3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Monday" />
<CheckBox
android:id="#+id/checkBox4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tuesday" />
<CheckBox
android:id="#+id/checkBox5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Wednesday" />
<CheckBox
android:id="#+id/checkBox6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Thursday" />
<CheckBox
android:id="#+id/checkBox7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Outlet is Closed" />
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calling Frequency" />
<Spinner
android:id="#+id/spinner3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/input_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Comments" />
<Button
android:id="#+id/btn_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />
<!-- Add Button -->
</LinearLayout>
Mainactivity java file.
package aaa.qw.cv;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.DatabaseUtils;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.ArrayList;
import java.util.Arrays;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleCursorAdapter;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.content.Intent;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnClickListener;
import android.util.Log;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.EditText;
import java.util.LinkedList;
import android.view.inputmethod.InputMethodManager;
public class ok extends Activity {
Spinner s1,s2,s3;
Button btnAdd;
EditText inputLabel;
DatabaseHandler dbhndlr;
Cursor spinner1csr, spinner2csr;
SimpleCursorAdapter sca, sca2;
long spinner1_selected = 0;
CheckBox ck1,ck2,ck3,ck4,ck5,ck6,ck7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_ex4);
s1 = (Spinner)findViewById(R.id.spinner1);
s2 = (Spinner)findViewById(R.id.spinner2);
s3 = (Spinner)findViewById(R.id.spinner3);
btnAdd = (Button) findViewById(R.id.btn_add);
inputLabel = (EditText) findViewById(R.id.input_label);
dbhndlr = new DatabaseHandler(this);
ck1=(CheckBox) findViewById(R.id.checkBox);
ck2=(CheckBox)findViewById(R.id.checkBox2);
ck3=(CheckBox)findViewById(R.id.checkBox3);
ck4=(CheckBox)findViewById(R.id.checkBox4);
ck6=(CheckBox) findViewById(R.id.checkBox5);
ck7=(CheckBox)findViewById(R.id.checkBox6);
loadSpinnerData();
// Get Cursors for Spinners
spinner1csr = dbhndlr.getAllLabelsAsCursor();
//Setup Adapter for Spinner 1
sca = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,spinner1csr,
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},
0
);
// Set the Adapters to the Spinners
s1.setAdapter(sca);
// Set Spinner1 OnSelectedItemListener
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"You Selected: " + id + " - " +
spinner1csr.getString(
spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
" - " + spinner1csr.getString(spinner1csr.getColumnIndex(DatabaseHandler.KEY_ID))
,
Toast.LENGTH_SHORT).show();
spinner1_selected = id;
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca2.swapCursor(spinner2csr);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Steup Adapter for Spinner2
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca2 = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
spinner2csr,
new String[]{DatabaseHandler.KEY_ID},
new int[]{android.R.id.text1},
0
);
s2.setAdapter(sca2);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();
if (label.trim().length() > 0) {
// database handler commeneted out, use dbhndlr instance instead
// inserting new label into database
dbhndlr.insertLabel(label);
// making input filed text to blank
inputLabel.setText("");
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
// loading spinner with newly added data
spinner1csr = dbhndlr.getAllLabelsAsCursor();
spinner2csr = dbhndlr.getByRowid(spinner1_selected);
sca.swapCursor(spinner1csr);
sca2.swapCursor(spinner2csr);
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
s3.setAdapter(dataAdapter1);
}
#Override
public void onDestroy() {
spinner1csr.close();
spinner2csr.close();
super.onDestroy();
}
}
database java file.
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "spinnerExample";
// Labels table name
public static final String TABLE_LABELS = "labels"; //<<<< Made public
public static final String TABLE_LABELS1= "labels1";
public static final String TABLE_LABELS2= "labels2";
// Labels Table Columns names
public static final String KEY_ID = "id"; //<<<< Made public
public static final String KEY_NAME = "name"; //<<<< made public
public static final String KEY_ID1 = "id1"; //<<<< Made public
public static final String KEY_NAME1 = "name1";
public static final String KEY_1 = "number"; //<<<< Made public
public static final String KEY_2 = "outletname"; //<<<< made public
public static final String KEY_3 = "sunday"; //<<<< Made public
public static final String KEY_4 = "monday";
public static final String KEY_5 = "tuesday";
public static final String KEY_6 = "wednesday";
public static final String KEY_7 = "thursday";
public static final String KEY_8 = "saturday";
public static final String KEY_9 = "closed";
public static final String KEY_10 = "calling";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
+ KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
+ KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
db.execSQL(CREATE_CATEGORIES_TABLE1);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
// Inserting Row
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
public void insertLabel1(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
// Inserting Row
db.insert(TABLE_LABELS1, null, values);
db.close(); // Closing database connection
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
// Added for adding new data
public void insertlabel(String id, String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_ID,id);
cv.put(KEY_NAME,label);
db.insert(TABLE_LABELS,null,cv);
db.close();
}
// Added to get Cursor for Simple CursorAdapter
public Cursor getAllLabelsAsCursor() {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
}
public Cursor getAllLabelsExceptedSelected(long selected) {
String[] columns = new String[]{"rowid AS _id, *"};
String whereclause = "rowid <> ?";
String[] whereargs = new String[]{String.valueOf(selected)};
return this.getWritableDatabase().query(TABLE_LABELS,
columns,
whereclause,
whereargs,
null,
null,
null
);
}
public Cursor getByRowid(long id) {
String[] columns = new String[]{"rowid AS _id, *"};
return this.getWritableDatabase().query(
TABLE_LABELS,
columns,
"rowid=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
}
issue is solved with
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_3,message3);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
database
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_3,message3);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
main
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//String label = inputLabel.getText().toString();
String SaveString="No";
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
String message1= ((Cursor) s1.getSelectedItem()).getString(2);
String message2= ((Cursor) s2.getSelectedItem()).getString(1);
String message = inputLabel.getText().toString();
// String message1 = s1.getSelectedItem().toString();
// String message2 = s2.getSelectedItem().toString();
String message10 = s3.getSelectedItem().toString();
String message4 = ck1.getText().toString();
String message5 = ck2.getText().toString();
String message6 = ck3.getText().toString();
String message7 = ck4.getText().toString();
String message9 = ck6.getText().toString();
String message3 = ck7.getText().toString();
String message8 = ck8.getText().toString();
if (ck1.isChecked())
{ message4 = ck1.getText().toString();
}
else
{ message4="No";
}
if (ck2.isChecked())
{ message5 = ck2.getText().toString();
}
else
{ message5="No";
}
if (ck3.isChecked())
{ message6 = ck3.getText().toString();
}
else
{ message6="No";
}
if (ck4.isChecked())
{ message7 = ck4.getText().toString();
}
else
{ message7="No";
}
if (ck6.isChecked())
{ message9 = ck6.getText().toString();
}
else
{ message9="No";
}
if (ck7.isChecked())
{ message3 = ck7.getText().toString();
}
else
{ message3="No";
}
if (ck8.isChecked())
{ message8 = ck8.getText().toString();
}
else
{ message8="No";
}
db.insertLabel(message1,message2,message5,message6,message7,message9,message3,message4,message8,message10);
I'm stuck in an application , and I need your advice .
I wish the first page to be able to run items from the database using the buttons inainte(front) and inapoi(back), but I try to order the database in OnClick Lisiner , but the application crashes , and do not know why , tend to, I think i don`t appelea ,the items in the database, properly.
How do you think I should do , or what should I do for this job to do , to run elements .
And again the problem that I have not found it anywhere, how do I do the print button ,to send the print information from the screen element displayed.
The vast majority of the code I've written was hith the help of tutorials.
So, this is the code, and files, that i creat:
Activity_main.xml:
<?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"
tools:context=".MainActivity"
android:orientation="vertical">
<ImageView
android:id="#+id/ivImagineaRetetei"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/INAPOI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/numeleRetetei" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Carrefour Suceava"
android:id="#+id/textView2"
/>
<TextView
android:layout_width="290dp"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Numele Retetei"
android:id="#+id/numeleRetetei"
android:layout_alignTop="#+id/PPR"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/PPR" />
<Button
android:layout_width="99dp"
android:layout_height="wrap_content"
android:text="Adauga"
android:id="#+id/ADD"
android:layout_gravity="right"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/PPR" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Printeaza"
android:id="#+id/PPR"
android:layout_marginTop="28dp"
android:layout_gravity="right"
android:layout_below="#+id/textView2"
android:layout_alignEnd="#+id/INAINTE" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inapoi"
android:id="#+id/INAPOI"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inainte"
android:id="#+id/INAINTE"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="vertical">
<TabHost
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tabHost">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/tabContactList"
android:layout_width="match_parent"
android:layout_height="458dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Retetele mele"
android:id="#+id/textView"
android:layout_gravity="center"
android:layout_marginTop="10dp" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView"
android:layout_gravity="center" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabCreator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Adauga Reteta"
android:id="#+id/lblCreatorTitle"
android:layout_gravity="center"
android:layout_marginTop="10dp" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imgViewContactImage"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:src="#drawable/index" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/txtName"
android:phoneNumber="false"
android:layout_marginTop="15dp"
android:hint="Numele Retetei" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Adaugare"
android:id="#+id/btnAdd"
android:layout_marginTop="10dp"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inapoi"
android:id="#+id/btnRET"
android:layout_marginTop="10dp"
android:enabled="true" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
Contact.java
package ciprian.retete_carrefour;
import android.net.Uri;
public class Contact {
private String _name;
private Uri _imageURI;
private int _id;
public Contact(int id, String name, Uri imageURI){
_id = id;
_name = name;
_imageURI = imageURI;
}
public int getId() { return _id; }
public String getName() { return _name; }
public Uri getImageURI() { return _imageURI; }
}
DatabaseHandler.java
package ciprian.retete_carrefour;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION =1;
private static final String DATABASE_NAME = "contactManager",
TABLE_CONTACTS = "contacts",
KEY_ID = "id",
KEY_NAME = "name",
KEY_IMAGEURI = "imageUri";
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "( " + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME + " TEXT," + KEY_IMAGEURI + " TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
//CREARE DE USER
public void createContact (Contact contact)
{
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGEURI, contact.getImageURI().toString());
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
//CITIRE BAZA DE DATE
public Contact getContact(int id)
{
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_IMAGEURI}, KEY_ID + "=?", new String[] {String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),cursor.getString(1), Uri.parse(cursor.getString(2)));
db.close();
cursor.close();
return contact;
}
//STERGERE CONTACT DIN DB
public void deleteContact(Contact contact) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[] {String.valueOf(contact.getId())});
db.close();
}
public int getContactsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updateContact(Contact contact) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGEURI, contact.getImageURI().toString());
int rowsAffected = db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[]{String.valueOf(contact.getId())});
db.close();
return rowsAffected;
}
public List<Contact> getAllContacts() {
List<Contact> contacts = new ArrayList<Contact>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
if (cursor.moveToFirst()) {
do {
contacts.add(new Contact(Integer.parseInt(cursor.getString(0)),cursor.getString(1), Uri.parse(cursor.getString(2))));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return contacts;
}
}
Main2Activity.java
package ciprian.retete_carrefour;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Main2Activity extends Activity {
private static final int DELETE=1;
EditText nameTxt;
ImageView contactImageImgView;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
Uri imageUri = Uri.parse("android.resource://ciprian.retete_carrefour/drawable/index.jpg");
DatabaseHandler dbHandler;
int longClickedItemIndex;
ArrayAdapter<Contact> contactAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
nameTxt = (EditText) findViewById(R.id.txtName);
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
contactListView = (ListView) findViewById(R.id.listView);
contactImageImgView = (ImageView)findViewById(R.id.imgViewContactImage);
dbHandler = new DatabaseHandler(getApplicationContext());
registerForContextMenu(contactListView);
contactListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
});
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("Adaugare");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("list");
tabSpec.setContent(R.id.tabContactList);
tabSpec.setIndicator("Memorate");
tabHost.addTab(tabSpec);
final Button retBtn = (Button) findViewById(R.id.btnRET);
final Button addBtn = (Button) findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact contact = new Contact(dbHandler.getContactsCount(), String.valueOf(nameTxt.getText()), imageUri);
if (!contactExists(contact)) {
dbHandler.createContact(contact);
Contacts.add(contact);
contactAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), String.valueOf(nameTxt.getText()) + " a fost adaugata la retete!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getApplicationContext(), String.valueOf(nameTxt.getText()) + " exista deja, te rugam alege alta reteta.", Toast.LENGTH_SHORT).show();
}
});
retBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Main2Activity.this, MainActivity.class));
}
});
nameTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addBtn.setEnabled(String.valueOf(nameTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
contactImageImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Selecteaza Imaginea Retetei"), 1);
}
});
if (dbHandler.getContactsCount()!=0)
Contacts.addAll(dbHandler.getAllContacts());
populateList();
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.pencil_icon);
menu.setHeaderTitle("Optiuni");
menu.add(Menu.NONE, DELETE, menu.NONE, "Sterge");
}
public boolean onContextItemSelected(MenuItem item){
switch (item.getItemId())
{
case DELETE:
dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
Contacts.remove(longClickedItemIndex);
contactAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private boolean contactExists(Contact contact)
{
String name = contact.getName();
int contactCount = Contacts.size();
for (int i=0; i <contactCount; i++)
{
if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
return true;
}
return false;
}
public void onActivityResult (int reqCode, int resCode, Intent data)
{
if (resCode == RESULT_OK)
{
if (reqCode == 1) {
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
}
private void populateList() {
contactAdapter = new ContactListAdapter();
contactListView.setAdapter(contactAdapter);
}
private class ContactListAdapter extends ArrayAdapter<Contact>
{
public ContactListAdapter()
{
super(Main2Activity.this, R.layout.listview_item,Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent)
{
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
ImageView ivContactImage = (ImageView) view.findViewById(R.id.ivContactImage);
ivContactImage.setImageURI(currentContact.getImageURI());
return view;
}
}
}
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="#+id/ivContactImage" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Numele Retetei"
android:id="#+id/contactName"
android:layout_marginTop="20dp" />
</LinearLayout>
</LinearLayout>
MainActivity.java
package ciprian.retete_carrefour;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
// DatabaseHandler bazaDate;
// Button inainte;
// List<Contact> Contacts = new ArrayList<Contact>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setupInainte();
setupAdaugaProdus();
}
/* private void setupInainte()
{
inainte = (Button)findViewById(R.id.INAINTE);
inainte.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contacts = bazaDate.getAllContacts();
int contactCount = Contacts.size();
for (int i=0; i <contactCount; i++)
{
Contact currentContact = Contacts.get(i);
TextView name = (TextView) findViewById(R.id.numeleRetetei);
name.setText(currentContact.getName());
ImageView ivContactImage = (ImageView)findViewById(R.id.ivImagineaRetetei);
ivContactImage.setImageURI(currentContact.getImageURI());
}
}
});
}*/
private void setupAdaugaProdus()
{
Button btn = (Button) findViewById(R.id.ADD);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ciprian.retete_carrefour">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Main2Activity"></activity>
</application>
</manifest>
You are facing a NullPointerException probably because you haven't initialized the database helper class in your MainActivity.
Try:
DatabaseHandler bazaDate = new DatabaseHandler(this);
Only then you may call the methods you have implemented such as GetAllContacts
Try i!
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_IMAGEURI = "imageUri";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_IMAGEURI + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_IMAGEURI, contact.getImageURI().toString());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_IMAGEURI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_IMAGEURI, contact.getImageURI().toString());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
I'm trying to do a simple retrieval of data from SQLite Database to the SearchView.
My problem is the SearchView is not populated with respect to the data stored in the database, although it always shows the green signal of
successfully created the database
Below is the code.
fragment_search.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E6E6E6"
android:orientation="vertical" >
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:background="#FFFFFF" />
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp" >
</SearchView>
<ListView
android:id="#+id/listview_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/searchView"
android:layout_centerHorizontal="true"
android:divider="#E6E6E6"
android:dividerHeight="5dp" />
<LinearLayout
android:id="#+id/rightLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/view1"
android:layout_alignTop="#+id/view1"
android:orientation="vertical"
android:paddingTop="25dp" >
</LinearLayout>
</RelativeLayout>
Search_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/hotelLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/section_search"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="2" >
<ImageView
android:id="#+id/hotel_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="left"
android:src="#drawable/aaa" />
<EditText
android:id="#+id/hotel_name"
android:layout_width="209dp"
android:layout_height="56dp"
android:layout_gravity="fill_horizontal" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/hotel_city"
android:layout_width="96dp"
android:layout_column="1"
android:layout_gravity="left|bottom"
android:layout_row="0"
android:ems="10" />
<EditText
android:id="#+id/hotel_country"
android:layout_width="106dp"
android:layout_column="1"
android:layout_gravity="right|bottom"
android:layout_row="0"
android:ems="10" />
</GridLayout>
</TableRow>
</LinearLayout>
</RelativeLayout>
TableData.java
package com.mytry.test;
import android.provider.BaseColumns;
public class TableData
{
public TableData()
{
}
public static abstract class TableInfo implements BaseColumns
{
public static final String DATABASE_NAME = "tourDguide";
public static final String TABLE_NAME = "Hotels";
public static final String HOTEL_ID = "id";
public static final String HOTEL_NAME = "hotel_name";
public static final String HOTEL_ADDRESS = "hotel_address";
public static final String HOTEL_CITY = "hotel_city";
public static final String HOTEL_COUNTRY = "hotel_country";
public static final String HOTEL_POSTAL = "postal_code";
}
}
DataBaseHandler.java
package com.mytry.test;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.mytry.test.TableData.TableInfo;
public class DataHandler
{
public static final int DATABASE_VERSION = 1;
SQLiteDatabase db;
DataBaseHelper dbhelper;
Context ctx;
private static class DataBaseHelper extends SQLiteOpenHelper
{
public String CREATE_QUERY = "CREATE TABLE "+TableInfo.TABLE_NAME+"("+TableInfo.HOTEL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+TableInfo.HOTEL_NAME+" VARCHAR,"+TableInfo.HOTEL_ADDRESS+" VARCHAR,"+TableInfo.HOTEL_CITY+" VARCHAR,"+TableInfo.HOTEL_COUNTRY+" VARCHAR,"+TableInfo.HOTEL_POSTAL+" INT );";
public DataBaseHelper(Context ctx) {
super(ctx,TableInfo.DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operations", "Successfully Created Database");
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
db.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Successfully Created Table");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists "+TableInfo.TABLE_NAME);
onCreate(db);
}
}
public DataHandler(Context ctx) {
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
// TODO Auto-generated constructor stub
}
public DataHandler open()
{
dbhelper = new DataBaseHelper(ctx);
db = dbhelper.getReadableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public Cursor searchHotels(String inputText) throws SQLException
{
String query = "Select "+TableInfo.HOTEL_ID+" as _id,"+TableInfo.HOTEL_NAME+","+TableInfo.HOTEL_ADDRESS+","+TableInfo.HOTEL_CITY+","+TableInfo.HOTEL_COUNTRY+","+TableInfo.HOTEL_POSTAL+" from "+TableInfo.TABLE_NAME+" where "+TableInfo.HOTEL_NAME+" LIKE '" + inputText + "';";
Log.d("table operations","Successfully transferred query");
Cursor cr = db.rawQuery(query, null);
if(cr!=null)
{
cr.moveToFirst();
}
return cr;
}
}
SeachViewActivity.java
package com.mytry.test;
import com.mytry.test.TableData.TableInfo;
import android.R.anim;
import android.app.Activity;
import android.app.DownloadManager.Query;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SearchViewActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener
{
private ListView list;
private SearchView search;
private DataHandler dbHandler;
private TextView name,city,country;
private EditText edit;
Context ctx=this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_search);
search = (SearchView) this.findViewById(R.id.searchView);
list = (ListView) this.findViewById(R.id.listview_search);
name = (TextView)this.findViewById(R.id.hotel_name);
city = (TextView)this.findViewById(R.id.hotel_city);
country = (TextView)this.findViewById(R.id.hotel_country);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
dbHandler = new DataHandler(getBaseContext());
dbHandler.open();
}
public boolean onQueryTextSubmit(String query)
{
showResults(query + "*");
return false;
}
public boolean onQueryTextChange(String newText)
{
showResults(newText + "*");
return false;
}
public boolean onClose()
{
showResults("");
return false;
}
private void showResults(String query)
{
Cursor cr = dbHandler.searchHotels((query!=null?query.toString(): "####"));
if(cr==null)
{
}
else
{
String[] from = new String[]
{TableInfo.HOTEL_NAME,TableInfo.HOTEL_ADDRESS,TableInfo.HOTEL_CITY,TableInfo.HOTEL_COUNTRY,TableInfo.HOTEL_POSTAL};
int[] to = new int[]{R.id.hotel_name,R.id.hotel_city,R.id.hotel_country};
SimpleCursorAdapter hotels = new SimpleCursorAdapter(this,R.layout.search_list, cr, from, to);
list.setAdapter(hotels);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Cursor cr = (Cursor)list.getItemAtPosition(position);
String hotel_name = cr.getString(cr.getColumnIndexOrThrow("hotel_name"));
String hotel_city = cr.getString(cr.getColumnIndexOrThrow("hotel_city"));
String hotel_country = cr.getString(cr.getColumnIndexOrThrow("hotel_country"));
LinearLayout hotelLayout = (LinearLayout)findViewById(R.id.hotelLayout);
if(hotelLayout == null){
//Inflate the Customer Information View
LinearLayout leftLayout = (LinearLayout)findViewById(R.id.rightLayout);
View hotelInfo = getLayoutInflater().inflate(R.layout.search_list, leftLayout, false);
leftLayout.addView(hotelInfo);
}
name.setText(hotel_name);
city.setText(hotel_city);
country.setText(hotel_country);
search.setQuery("", true);
}
});
}
}
}
I can't understand why I doesen't get any data out of the database. I have to admit that I am confues about listviews, textviews and adapters.
The database contains a person and a gift. That should be poured into a textview. Somehow it seems that I have to make a listview, but.... I am confused.
I have read a lot, and worked hard, but I have no idea. I would appreciate it if anyone could help me :-)
The only thing that happens is that na empty list is appearing.
Here is the code:
Main Activity.java:
package com.example.julegaveliste2;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends ListActivity {
DatabaseHelper db;
Button knapp1;
Button knapp2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper db = new DatabaseHelper(MainActivity.this);
knapp1 = (Button) findViewById(R.id.Legg_Til);
knapp2 = (Button) findViewById(R.id.Les_database);
knapp2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
visliste(db.getWritableDatabase());
}
});
knapp1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
LagTabell(db.getWritableDatabase());
}
});
}
public static void LagTabell(SQLiteDatabase db)
{
ContentValues jul = new ContentValues();
jul.put("person", "Ida");
jul.put("gave", "blomst");
db.insert("julegaveliste2", "person", jul);
}
public void visliste(SQLiteDatabase db)
{
Cursor cursor=db.rawQuery("SELECT _id, person, gave FROM julegaveliste2", null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.activity_list_item, cursor, new String[]{"person","gave"}, new int[]{R.id.person,R.id.gave},0);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
}
}
DatabaseHelper.java:
package com.example.julegaveliste2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME="julegaveliste2.db";
private static final int SCHEMA=1;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, SCHEMA);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE julegaveliste2 (_id INTEGER PRIMARY KEY AUTOINCREMENT, person TEXT NOT NULL, gave TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
throw new RuntimeException("How did we get here?");
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/gave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
<Button
android:id="#+id/Legg_Til"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="17dp"
android:text="#string/opprett_database" />
<Button
android:id="#+id/Les_database"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Legg_Til"
android:layout_alignBottom="#+id/Legg_Til"
android:layout_toRightOf="#+id/person"
android:text="#string/les_database" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_above="#+id/Legg_Til"
android:layout_alignParentLeft="true"
android:layout_marginBottom="42dp" >
</ListView>
<ListView
android1:id="#+id/listView1"
android1:layout_width="match_parent"
android1:layout_height="100dp" >
</ListView>
</RelativeLayout>
You should try to replace your SimpleCursorAdapter with an ArrayAdapter. To do this we would need a few modifications to your code. We need a new class in your application, which I will call PresentItem, an ArrayAdapter for your list, an XML layout for each row in the list, and a method for converting SQLite rows to PresentItems. First out is the new model, PresentItem:
public class PresentItem {
private String name, present;
private int id;
public PresentItem(int id, String name, String present) {
// Init
}
// Getters, setters, etc.
}
So, when we now read from your database, we can convert each rows we get from our query to new PresentItems:
public List<PresentItem> getPresentItems(SQLiteDatabase db) {
Cursor cursor = db.query("julegaveliste2",
new String[] {"_id", "person", "gave"}, null, null, null, null, null);
List<PresentItem> result = new ArrayList<PresentItem>();
PresentItem item;
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndex("_id");
int id = cursor.getInt(index));
index = cursor.getColumnIndex("name");
String name = cursor.getString(index));
index = cursor.getColumnIndex("present");
String present = cursor.getString(index);
item = new PresentItem(id, name, present);
result.add(item);
}
return result;
}
Once we have the PresentItems parsed from the database, we need a way to display them. To display the PresentItems in your app, we need our own ArrayAdapter, which would look something like this:
public class PresentListAdapter extends ArrayAdapter<PresentItem> {
private Context ctx;
private List<PresentItem> presentItems;
public PresentListAdapter(Context ctx, int layoutResourceId, List<PresentItem> presentItems) {
super(context, layoutResourceId, presentItems);
this.ctx = ctx;
this.presentItems = presentItems;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity) ctx).getLayoutInflater();
convertView = inflater.inflate(mLayoutResourceId, parent, false);
}
PresentItem item = presentItems.get(position);
((TextView) convertView.findViewById(R.id.row_id)).setText("" + item.getId());
((TextView) convertView.findViewById(R.id.name)).setText(item.getName());
((TextView) convertView.findViewById(R.id.present)).setText(item.getPresent());
return convertView;
}
To use the adapter in your app, do something like this:
public void visListe(SQLiteDatabase db){
List<PresentItem> items = getPresentItems(db);
PresentItemAdapter adapter = new PresentItemAdapter(this, R.layout.presentListItem, items);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
And, as you might notice, our adapter uses presentListItem as its layout, which we define in res/layout/presentListItem.xml as:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/row_id"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/name"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/present"
/>
</LinearLayout>
I hope I made it clear and beware bugs in the code - I wrote most of it from memory with a few quick Google searches to help me :) Ask if you need anymore help ^^
I am creating a checklist and it allows the user to add new items to the list, I am trying to allow the user to delete an item when they want to. So I am creating a contextual menu using this that comes us when the user long-presses an item in the list. Right now, it recognizes the long-press but nothing happens, so the contextual menu doesn't appear.
Here is my activity page: (ViewTask.java)
package com.example.androidhive;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ViewTask extends Activity {
protected TaskerDbHelper db;
List<Task> list;
MyAdapter adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
db = new TaskerDbHelper(this);
list = db.getAllTasks();
adapt = new MyAdapter(this, R.layout.list_inner_view, list);
ListView listTask = (ListView) findViewById(R.id.listView1);
listTask.setAdapter(adapt);
}
public void addTaskNow(View v) {
EditText t = (EditText) findViewById(R.id.editText1);
String s = t.getText().toString();
if (s.equalsIgnoreCase("")) {
Toast.makeText(this, "Enter a goal please!",
Toast.LENGTH_LONG);
} else {
Task task = new Task(s, 0);
db.addTask(task);
Log.d("tasker", "data added");
t.setText("");
adapt.add(task);
adapt.notifyDataSetChanged();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.cmenu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.Delete_Task:
db.deleteTask(info.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.layout.activity_view_task, menu);
return true;
}
private class MyAdapter extends ArrayAdapter<Task> {
Context context;
List<Task> taskList = new ArrayList<Task>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId,
List<Task> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.taskList = objects;
this.context = context;
}
/**
* This method will DEFINe what the view inside the list view will
* finally look like Here we are going to code that the checkbox state
* is the status of task and check box text is the task name
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckBox chk = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_inner_view,
parent, false);
chk = (CheckBox) convertView.findViewById(R.id.chkStatus);
convertView.setTag(chk);
chk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task changeTask = (Task) cb.getTag();
changeTask.setStatus(cb.isChecked() == true ? 1 : 0);
db.updateTask(changeTask);
if(cb.isChecked())
{
Toast.makeText(
getApplicationContext(),
"Goal Accomplished!", Toast.LENGTH_LONG).show();
}
}
});
} else {
chk = (CheckBox) convertView.getTag();
}
Task current = taskList.get(position);
chk.setText(current.getTaskName());
chk.setChecked(current.getStatus() == 1 ? true : false);
chk.setTag(current);
Log.d("listener", String.valueOf(current.getId()));
return convertView;
}
}
}
Here is the xml page associated to this page:(activity_view_task.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DE8126"
android:orientation="vertical" >
<!-- Header Start -->
<LinearLayout
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#layout/header_gradient"
android:orientation="vertical"
android:paddingBottom="5dip"
android:paddingTop="5dip" >
<!-- Logo Start -->
<ImageView
android:id="#+id/logoButton"
android:layout_width="match_parent"
android:layout_height="132dp"
android:src="#drawable/logo" />
<!-- Logo Ends -->
</LinearLayout>
<!-- Header End -->
<!-- Goals Title Start -->
<LinearLayout
android:id="#+id/goalsTitle"
android:layout_width="match_parent"
android:layout_height="80dp"
android:paddingTop="5dip"
android:paddingBottom="5dip">
<TextView
android:id="#+id/gTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="My Goals"
android:textSize="50sp"
android:textScaleX="1.5"
android:textStyle="bold"
android:gravity="center"/>
</LinearLayout>
<!-- Goals Title End -->
<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"
tools:context=".ViewTask" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="14dp"
android:text="#string/Save"
android:onClick="addTaskNow"/>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1" >
</ListView>
</RelativeLayout>
</LinearLayout>
And here is the menu itself: (cmenu.xml)
<?xml version="1.0" encoding="UTF-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/Edit_Task"></item>
<item android:id="#+id/Delete_Task"></item>
</menu>
Thanks you for the responses, now I cannot get the item to actually be deleted.
here is my database helper page:(TaskerDbHelper.java)
package com.example.androidhive;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class TaskerDbHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "taskerManager";
// tasks table name
private static final String TABLE_TASKS = "tasks";
// tasks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TASKNAME = "taskName";
private static final String KEY_STATUS = "status";
public TaskerDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_TASKNAME+ " TEXT, "
+ KEY_STATUS + " INTEGER)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
// Create tables again
onCreate(db);
}
public void addTask(Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName()); // task name
// status of task- can be 0 for not done and 1 for done
values.put(KEY_STATUS, task.getStatus());
// Inserting Row
db.insert(TABLE_TASKS, null, values);
db.close(); // Closing database connection
}
public boolean deleteTask(long task)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_TASKS, KEY_TASKNAME + "=" + task, null) > 0;
}
public List<Task> getAllTasks() {
List<Task> taskList = new ArrayList<Task>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setId(cursor.getInt(0));
task.setTaskName(cursor.getString(1));
task.setStatus(cursor.getInt(2));
// Adding contact to list
taskList.add(task);
} while (cursor.moveToNext());
}
// return task list
return taskList;
}
public void updateTask(Task task) {
// updating row
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName());
values.put(KEY_STATUS, task.getStatus());
db.update(TABLE_TASKS, values, KEY_ID + " = ?",new String[] {String.valueOf(task.getId())});
db.close();
}
}
That file above contains my deleteTask().
I don't see registerForContextMenu() anywhere. This is necessary for the list to actually know that it has a contextmenu.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
db = new TaskerDbHelper(this);
list = db.getAllTasks();
adapt = new MyAdapter(this, R.layout.list_inner_view, list);
ListView listTask = (ListView) findViewById(R.id.listView1);
listTask.setAdapter(adapt);
registerForContextMenu(listTask); // <-- Register!
}
In addition you should put a String value in your menu xml file. Obviously it is better to refer to your string xml file for the actual string.
<item
android:id="#+id/Edit_Task"
android:title="Edit">
</item>
<item
android:id="#+id/Delete_Task"
android:title="Delete">
</item>
Concerning the delete task:
To delete your task from the sql database you need some kind of identifier. As far as I can tell, you have only a task name and a status integer. If you allow tasks to have the same name, this cannot be used as an unique identifier. Perhaps you should add that to your Task class. You can then use this to find and remove the specific task in your database. (Your info.id will not work, because it is merely the identifier of the view) You can use info.position to retrieve the position of the Task in taskList, or more specifically, the current list in the adapter.
case R.id.Delete_Task:
Task task = list.get(info.position);
if (db.deleteTask(task.getUniqueIdentifier())) { // <-- Determine the unique id
list.Remove(info.position);
listTask.invalidate();
return true;
}
return false;
I'm not sure whether invalidate() will do the trick. But give it a try. You could also give the adapter the new list and call notifyDataSetChanged() as you do for the addTaskNow().
You need to add this line to your onCreate method
registerForContextMenu(listTask);
Your onCreateContextMenu() needs to look like this
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listView1) { //YOUR VIEW THAT IS ATTACHED TO LISTASK
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle("Options");
String[] menuItems = { "Option1", "Option2", "Option3", "Option4"} };
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
and finally your OnContextMenuItemSelected()
#Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
menuItemIndex = item.getItemId();
String[] menuItems = { "Option 1, Option 2, Option 3" };
String menuItemName = menuItems[menuItemIndex];
return true;
}