store an EditText value into SQLite database line by line - android

i made an EditText that displayed value with multiple line like this...
i want to keep that value in a SQLite database. this is the code i use:
export.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final View export_layout = getLayoutInflater().inflate(R.layout.export_layout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setView(export_layout);
builder.setTitle("Input new DB");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
editText1 = (EditText) export_layout.findViewById(R.id.editText1);
String table = editText1.getText().toString();
String val = textStatus.getText().toString();
db.execSQL("create table "+table+"(ANY text)");
db.execSQL("insert into "+table+" values('"+val+"')");
}
});
builder.setNegativeButton("back",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
TextStatus is an EditText where the value is displayed like the image above. editText1 is where the user input the table name.
the problem is when i save the value, the whole value is inserted into one cell. i want the value to be separated per line then inserted into a single cell for each line.
is there any way to do that?
edit:
this is how i set the text in TextStatus:
x = new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
if (size > 0) {
for (int i=0; i<size; i++){
ScanResult scanresult = wifi.getScanResults().get(i);
String ssid = scanresult.SSID;
int rssi = scanresult.level;
String bssid = scanresult.BSSID;
String rssiString = String.valueOf(rssi);
textStatus.append(ssid + "," + bssid + "," + rssiString + "\n");
}
unregisterReceiver(x); //stops the continuous scan
textStatus.append("------------"+j+"\n");
j++;
}
}
};

Try Scanner:
Scanner scanner = new Scanner(val);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//Insert the line here
}
Update: This is how it should looks like in your codes
editText1 = (EditText) export_layout.findViewById(R.id.editText1);
String table = editText1.getText().toString();
String val = textStatus.getText().toString();
db.execSQL("create table "+table+"(ANY text)");
Scanner scanner = new Scanner(val);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
db.execSQL("insert into "+table+" values('"+line+"')");
}

Related

Display Multiple data from database to textview android

my problem is cant display all the data i call from my database to my textview when i click the button , but i can only display 1 data at the time , and i read the other question like this but still i dont get it.
This is my Code to call the data from database
public WordObject getPOSbyWords(String wordd){
WordObject wordObject2 = null;
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
if (cursor.moveToFirst()){
do {
//=
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
//String pos2 = cursor.getString(cursor.getColumnIndexOrThrow("words"));
wordObject2 = new WordObject(pos1,null);
}while (cursor.moveToNext());
}
cursor.close();
return wordObject2;
}
This my Code in main activity
public class GrammarActivity extends AppCompatActivity {
TextView postv, wordtv;
Button btngo;
MultiAutoCompleteTextView multiple;
Listview listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grammar);
wordtv = (TextView) findViewById(R.id.grammar);
multiple = (MultiAutoCompleteTextView) findViewById(R.id.MultipleAuto);
btngo = (Button) findViewById(R.id.check);
postv = (TextView) findViewById(R.id.Partofspeech);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Welcome user
builder.setMessage("Welcome to the Grammar Checker")
.setIcon(R.mipmap.ic_launcher)
.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create();
builder.show();
//Space Tokenizer splitting the words
final String[] words = getResources().getStringArray(R.array.autocomplete);
multiple.setTokenizer(new SpaceTokenizer());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, words);
multiple.setAdapter(adapter);
btngo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String space = "";
String foo = " ";
String foo1 = ",";
String sentences = null;
String red = multiple.getText().toString();
if (red.isEmpty()) {
Toast.makeText(getApplicationContext(), " Input text please ", Toast.LENGTH_SHORT).show();
multiple.setBackgroundColor(Color.RED);
}else
Toast.makeText(getApplicationContext(), "THanks ", Toast.LENGTH_SHORT).show();
//Splitting the sentence into words
sentences = multiple.getText().toString().toLowerCase();
String[] splitwords = sentences.trim().split("\\s+");
for (String biyak : splitwords) {
foo = (foo + "'" + biyak + "'" + foo1);
String fot = foo.replaceAll(",$", " ");
wordtv.setText(fot);
Db1Backend db1Backend = new Db1Backend(GrammarActivity.this);
WordObject DisplayPOS = db1Backend.getPOSbyWords(fot);
postv.setText(DisplayPOS.getWord());
}
World Class
public class WordObject {
private String word;
private String pos;
public WordObject(String word, String definition) {
this.word = word;
this.pos = definition;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPOS() {
return pos;
}
public void setPOS(String definition) {
this.pos = definition;
}
}
Try this one.
public String getPOSbyWords(String wordd)
{
String myPos = "";
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
try
{
if (cursor != null && cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
myPos = pos1;
}
}
}
catch (Exception e)
{
// Handle Exception here
}
finally
{
// release cursor
if (cursor != null && !cursor.isClosed())
cursor.close();
}
return myPos;
}
Now in your GrammarActivity inside for loop do this.
// Taking String Builder to append all the String in one.
StringBuilder sb = new StringBuilder();
for (String biyak : splitwords)
{
foo = (foo + "'" + biyak + "'" + foo1);
String fot = foo.replaceAll(",$", " ");
wordtv.setText(fot);
Db1Backend db1Backend = new Db1Backend(GrammarActivity.this);
// Append all your position into StringBuilder
sb.append(db1Backend.getPOSbyWords(fot));
}
postv.setText(sb.toString());
Replace your method with this.
public ArrayList<WordObject> getPOSbyWords(String wordd){
WordObject wordObject2 = null;
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
ArrayList<WordObject> words = new ArrayList<>();
if (cursor.moveToFirst()){
do {
//=
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
//String pos2 = cursor.getString(cursor.getColumnIndexOrThrow("words"));
wordObject2 = new WordObject(pos1,null);
words.add(wordObject2);
}while (cursor.moveToNext());
}
cursor.close();
return words;
}

Nullpointer exception while using SQLite

I am using sqlitedatabase,and i am able to insert data properly,but issue is when i am trying to display inserted data,my app got crash and giving nullpointer exception,can any one tell the what is the issue with my code,following is my snippet code,
Error in this line
if (c1 != null & c1.getCount() != 0) {
MAinActivity.java
public class MainActivity extends Activity {
private ListView upcominglist;
private ListView todays;
private ListView eventhistory;
private ImageView addnewevent;
public ArrayList<ContactListItems> contactList;
public ContactListItems contactListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upcominglist=(ListView)findViewById(R.id.listview_upcoming);
todays=(ListView)findViewById(R.id.listview_todays);
eventhistory=(ListView)findViewById(R.id.listview_eventhistory);
addnewevent=(ImageView)findViewById(R.id.addneweventbutton);
addnewevent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddNewEvent.class);
startActivity(intent);
}
});
contactList = new ArrayList<ContactListItems>();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
if (c1 != null & c1.getCount() != 0) {
if (c1.moveToNext()) {
do {
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
else
{
c1.close();
}
c1.close();
String first=contactListItems.getSlno();
System.out.println("First" + first);
String second=contactListItems.getNameofevent();
System.out.println("SEcond"+second);
String third=contactListItems.getDtofevent();
System.out.println("Third"+third);
String fourth=contactListItems.getTimeofevent();
System.out.println("Fourth"+fourth);
String fifth=contactListItems.getDuration();
System.out.println("Fifth"+fifth);
}
Addnewevent.java
public class AddNewEvent extends Activity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
static final int TIME_PICKER_ID = 11111;
int flag = 0;
private ImageView addnewdata;
private LinearLayout lnr;
private Button submit;
private EditText edtnmofevent;
private EditText edtdtofevent;
private EditText edttmofevent;
private EditText edtdurationofevent;
SqlHandler sqlHandler;
private ImageView datepicks;
private ImageView timepicks;
private Calendar cal;
private int hour;
private int min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_event);
sqlHandler = new SqlHandler(getApplicationContext());
addnewdata = (ImageView) findViewById(R.id.addnewdata);
submit = (Button) findViewById(R.id.btnsubmit);
edtnmofevent = (EditText) findViewById(R.id.edtnameofevent);
edtdtofevent = (EditText) findViewById(R.id.edtdateofevent);
edttmofevent = (EditText) findViewById(R.id.edttimeofevent);
edtdurationofevent = (EditText) findViewById(R.id.edtdurationofevent);
datepicks = (ImageView) findViewById(R.id.calndrdat);
timepicks = (ImageView) findViewById(R.id.timepickrs);
cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
timepicks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(TIME_PICKER_ID);
}
});
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
StringBuilder dateValue1 = new StringBuilder().append(day).append("-").append(month + 1).append("-")
.append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
try {
testDate1 = sdf123.parse(abs1);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
edtdtofevent.setText(DateFormat);
edtdtofevent.setFocusable(false);
edtdtofevent.setInputType(InputType.TYPE_NULL);
datepicks.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
addnewdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(AddNewEvent.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AddNewEvent.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
lnr = (LinearLayout) findViewById(R.id.addnewlinear);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(25, 0, 0, 0);
TextView valueTV = new TextView(AddNewEvent.this);
// valueTV.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
valueTV.setText(userInput.getText());
valueTV.setLayoutParams(lp);
valueTV.setTextSize(18);
valueTV.setTextColor(Color.parseColor("#2d6cae"));
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp1.setMargins(25, 0, 25, 0);
lp1.height = 50;
EditText edtvalues = new EditText(AddNewEvent.this);
edtvalues.setBackgroundResource(R.drawable.rect_edt);
edtvalues.setLayoutParams(lp1);
lnr.addView(valueTV);
lnr.addView(edtvalues);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AddNewEvent.this, EventDetails.class);
startActivity(intent);
String nameofevent = edtnmofevent.getText().toString();
String dtofevent = edtdtofevent.getText().toString();
String timeofevent = edttmofevent.getText().toString();
String duration = edtdurationofevent.getText().toString();
String query = "INSERT INTO PHONE_CONTACTS(nameofevent,dtofevent,timeofevent,duration) values ('"
+ nameofevent + "','" + dtofevent + "','" + timeofevent + "','" + duration + "')";
sqlHandler.executeQuery(query);
System.out.println("Querys" + query);
}
});
}
SQL
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "slno";
public static final String COLUMN2 = "nameofevent";
public static final String COLUMN3 = "dtofevent";
public static final String COLUMN4 = "timeofevent";
public static final String COLUMN5 = "duration";
/* public static final String COLUMN6 = "dlabl";
public static final String COLUMN7 = "dedt";*/
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ DATABASE_TABLE + " (" + COLUMN1
+ " integer primary key autoincrement, " + COLUMN2
+ " text not null, " + COLUMN3 + " text not null, " + COLUMN4 + " text not null, " + COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#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);
}
}
The problem is in your SqlHandler.selectQuery() that returns a null, and another problem here checking the result:
if (c1 != null & c1.getCount() != 0)
You're using bitwise and & and not the short-circuiting logical and &&. Without short circuiting the complete expression including c1.getCount() on a null reference is evaluated.
There is too much here to explain it all, so I will give you the flaws causing a null pointer exception.
I can see your method of programming is coming from worrying too much about closing things and clearing up
resources to a point, it's causing problems.
contactList = new ArrayList<ContactListItems>();
// You are clearing your list, it should be empty, you have just created it.
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
// As mentioned by the other answer. You need && not &
// if (c1 != null & c1.getCount() != 0) {
if (c1 != null && c1.getCount() != 0) {
// Move to the first entry.
c1.moveToFirst();
//if (c1.moveToNext()) {
// do {
// Continue while it has not passed the last entry.
while (!cursor.isAfterLast())
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
// Move the cursor along to the next entry.
cursor.moveToNext();
}
}
// Close cursor after while and within if (so you know it is not null).
c1.close();
}
else
{
// You can't close c1 if it is Null. This will throw and error. Lose the else.
c1.close();
}
// Move this to within your if statment.
c1.close();
From your code you provided in the chat.
Don't open and close your database continuously, just close each cursor you use when you're done. Just open it at the beginning and end of your program run.
public static Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (sqlDatabase.isOpen()) {
// You are closing the database.
sqlDatabase.close();
}
sqlDatabase = dbHelper.getWritableDatabase();
c1 = sqlDatabase.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
There are many other flaws in your project. Like the structure and how and when you are calling things. You need to modularise it out, create methods for particular tasks and call those methods, rather than have a great lump of code in oncreate.
I am sure you will have many questions about this. But currently this question is addressing your null pointer exception and that is all I will discuss here. For questions about this not relating to this exception, please ask a new question. Hope this helps.

Update Listview after deleting database item

Ive been trying to get my listview to update after removing an item. Here's what I have so far:
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String str = null;
public void onItemClick(AdapterView<?> arg0, final View view, int arg2, long arg3) {
//TextView txtview = (TextView)view.findViewById(R.id.txtview);
final String item = ((TextView) view.findViewById(R.id.txtview)).getText().toString();
str = item;
final long arr = arg3;
final String arg22 = longToString(arg3);
//Creating an Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(Home.this);
builder.setMessage("Are you sure you want to delete the hike " + str + " ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase db1=openOrCreateDatabase("hikeManager", MODE_PRIVATE, null);
DatabaseHandler db = new DatabaseHandler(Home.this);
String table = "hikes";
Cursor c = db1.rawQuery("select id from "+ table + " where name='"+item+"'", null);
int dhike = c.getColumnIndex("name") + 1;
try {
Hike hike = db.getHike(arr + 1);
db.deleteHike(hike);
Log.d("DLT", "Deleted hike at index " + arr);
//db.updateList(adapter, myList, listItems);
adapter.remove(arg22);
adapter.notifyDataSetChanged();
//updateData();
db.close();
} catch (CursorIndexOutOfBoundsException e) {
Log.d("DLT", "Failed to delete: " + e.getMessage());
db.close();
}
//db.updateList(adapter, myList, listItems);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
I Have quite a bit of unused code in there, as I have tried a few different methods to get this to work, but have failed so far. Here is updateData:
private void updateData() {
// Get all of the notes from the database and create the item list
DatabaseHandler db = new DatabaseHandler(this);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txtview, listItems);
final ListView myList = (ListView) findViewById(R.id.cardListView);
int num = db.getHikesCount();
for (int i=1; i<num+1; ++i){
Hike name = db.getHike(i);
String nam = name.getName();
listItems.add(nam);
}
myList.setAdapter(adapter);
db.close();
}
The updateData does have some unintended consequences when I use it to update the view after adding an item to a non-empty list, but it works for now. The item is successfully deleted, since I can close the app and reload it and the item will be gone. I just cant seem to get it to update properly for me.
Just use
adapter.notifyDataSetChanged();

traaversing a listview and saving data of any view which is checked

hey i have created a listview and using custom ArrayListAdapter and overridding the getView() method. i have a save button to save data from listview items which are checked . as they contain checkbox. Now the problem is when i save data using getchildCount method to loop each item(Row,Child) it only traverse to the visible items. if i use getCount() method it gives NullPointerexception as it is not considering the items which are not visible . i know i have to use my adapter to do all this but how???????????
this is my class using adapter adapter--------------
package com.bmi.cal.hitesh;
public class BreakFast extends Activity {
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
db.close();
}
float cal_needed=0;
public int counter =0,listItemCount=0,flag=1;
TextView tv_cal_count;
CheckBox check;
public ListView list;
ContentValues values = new ContentValues();
SQLiteDatabase db;
List<Employer> data = new ArrayList<Employer>();
Cursor cur,cur2;
String type, title,form,descr,tv_cal_str;
int calories;
private Button done;
private TextView tv_cal_needed;
private String cust;
int temp_diet_id[]= new int[234];
//final String CREATE_TABLE= "CREATE TABLE IF NOT EXISTS Bfast_table (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "diet TEXT,calories INTEGER,type INTEGER);";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String MYPREFS = "mySharedPreferences";
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,0);
list= (ListView)findViewById(R.id.list);
done = (Button)findViewById(R.id.button1);
tv_cal_count = (TextView)findViewById(R.id.tv_cal_count);
tv_cal_needed = (TextView)findViewById(R.id.tv_calories);
check = (CheckBox)findViewById(R.id.checkBox1);
db = openOrCreateDatabase("bmi.db",SQLiteDatabase.CREATE_IF_NECESSARY , null );
db.setVersion(1);
db.setLocale(Locale.getDefault());
cust = mySharedPreferences.getString("txt_cust", null);
db.setLockingEnabled(false);
db.execSQL("CREATE TABLE IF NOT EXISTS cust_diet(" + "cd_id INTEGER PRIMARY KEY AUTOINCREMENT," + "cust_id Integer,diet_id INTEGER,cd_validity DATE);");
try {
cur = db.query("tbl_diet",null,"type=?",new String[] {"Breakfast"}, null,null, null);
cur.moveToFirst();
while(!cur.isAfterLast())
{
title = cur.getString(1);
descr = cur.getString(2);
form = cur.getString(6);
type = cur.getString(5);
calories = cur.getInt(3);
data.add(new Employer(title,"Calories : " + calories,"("+descr+")",form));
cur.moveToNext();
}
list.setAdapter(new EmployerArrayAdapter(this, data));
cur.close();
} catch (Exception u) {
u.printStackTrace();
}
done.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int flag = 1;
listItemCount = list.getCount();
// TODO Auto-generated method stub
System.out.println(cust+"aaaaaaaaaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaaaaaaa"+list.getCount());
cur = db.query("user_bmi",null,"cust_id=?",new String[]{cust}, null,null, null);
System.out.println(cur.getCount()+"aaaaaaaaaaaaaaaa");
cur.moveToFirst();
cal_needed = (Float.parseFloat(cur.getString(9)))*(0.25f);
cur.close();
System.out.println(cust+"bbbbbbb");
tv_cal_needed.setText("you must not exceed "+ cal_needed +" calories");
tv_cal_count.setText("calories of your selected diets are as follows : ");
for(int i=0; i<listItemCount; i++)
{ TextView tv_name= (TextView) ((View)list.getChildAt(i)).findViewById(R.id.textViewName);
TextView tv_calorie= (TextView) ((View)list.getChildAt(i)).findViewById(R.id.textViewAddress);
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
{ tv_cal_str = tv_name.getText().toString();
cur = db.query("tbl_diet",null,"diet_title=?",new String[] {tv_cal_str}, null,null, null);
cur.moveToFirst();
temp_diet_id[counter]= cur.getInt(0);;
counter++;
tv_cal_count.append(tv_calorie.getText()+".");
System.out.println(cust+"cccccccc"+temp_diet_id[counter-1]);
System.out.println("not saved sill"+counter+"11111111111111111111111");
String temp_cal= tv_calorie.getText().toString().substring(11);
System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee11111111111111111111111");
float temp_calorie = Float.parseFloat(temp_cal);
System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee222222222222222222222222");
if(temp_calorie>cal_needed)
{ System.out.println("eeeeeeeeeeeeeeeeeeeeeee3333333333333333333333333");
System.out.println(cust+"dddddddddd");
flag=0;
}
}
cur.close();
}
System.out.println("not saved sill"+counter+"22222222222222222222");
if(counter<=3 && counter>=1)
{
for(int i=0; i<listItemCount; i++)
{
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
cbox.setChecked(false);
}
final int temp_count = counter;
System.out.println("not saved sill"+counter+"3333333333333333333333");
if(flag==1){
AlertDialog.Builder builder = new AlertDialog.Builder(BreakFast.this);
builder.setMessage("Do you want to save your BreakFast?")
.setCancelable(false)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.out.println("not saved sill"+temp_count+"3333333333333333333333");
for(int i=0; i<temp_count; i++)
{
cur2 = db.query("user_bmi",null,"cust_id=? and bmi_active=?",new String[]{cust,"1"}, null,null, null);
cur2.moveToFirst();
System.out.println("not saved sill");
values.put("diet_id",temp_diet_id[i]);
values.put("cd_validity",cur2.getString(5));
values.put("cust_id",cust); System.out.println("saved");
db.insert("cust_diet", null, values);
cur.close();
cur2.close();
}
tv_cal_count.setText("Your BreakFast has been saved");
tv_cal_needed.setText(null);
done.setVisibility(View.INVISIBLE); }
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
for(int i=0; i<listItemCount; i++)
{
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
cbox.setChecked(false);
}
dialog.cancel();
tv_cal_count.setText(null);
}
});
AlertDialog alert = builder.create();
alert.show();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(BreakFast.this);
builder.setMessage("please select diet which do not exceed "+cal_needed+" calories!!!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
tv_cal_count.setText(null);
for(int i=0; i<listItemCount; i++)
{
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
cbox.setChecked(false);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
counter=0;
}
else
{
tv_cal_count.setText(null);
Dialog mesg = new Dialog(BreakFast.this);
TextView text = new TextView(BreakFast.this);
if(counter==0)
text.setText("plzz select some items but not more then three!!!");
else
text.setText("can't select more then three");
mesg.setContentView(text);
mesg.show();
counter=0;
for(int i=0; i<listItemCount; i++)
{
CheckBox cbox = (CheckBox) ((View)list.getChildAt(i)).findViewById(R.id.checkBox1);
if(cbox.isChecked())
cbox.setChecked(false);
}
}
}
});
}
Use try catch block and post the stack trace.

Create and display a ListView of the ZXing ProductDatabase

I created an app for scanning barcodes and QR code using the ZXing library. I also implemented a database that stores the scanned products. I need to implement a listview to display the stored products. any ideas?
here are classes:
BarCodeActivity
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spot_pay);
Button addButton = (Button) findViewById (R.id.addMenuButton);
addButton.setOnClickListener (new OnClickListener(){
public void onClick (View v){
startActivity(new Intent(CodiceBarreActivity.this, AggiungiCodiceActivity.class));
}
});
}
static final class ProductData {
String barcode;
String format;
String title;
BigDecimal price;
}
}
ProductDatabase:
private SQLiteDatabase db;
private static class ProductDatabaseHelper extends SQLiteOpenHelper {
public ProductDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
StringBuilder sql = new StringBuilder();
sql.append("create table ").append(PRODUCT_TABLE)
.append("( ")
.append(" _id integer primary key,")
.append(" barcode text,")
.append(" format text,")
.append(" title text,")
.append(" price currency")
.append(") ");
db.execSQL(sql.toString());
Log.d(TAG, PRODUCT_TABLE + "table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + PRODUCT_TABLE);
Log.d(TAG, PRODUCT_TABLE + "table dropped");
onCreate(db);
}
}
public CodiciDatabase(Context context) {
ProductDatabaseHelper helper = new ProductDatabaseHelper(context);
db = helper.getWritableDatabase();
}
public boolean insert(ProductData product) {
ContentValues vals = new ContentValues();
vals.put("barcode", product.barcode);
vals.put("format", product.format);
vals.put("title", product.title);
vals.put("price", product.price.multiply(ONE_HUNDRED).longValue());
return db.insert(PRODUCT_TABLE, null, vals) != -1;
}
}
AddProduct
private static final int REQUEST_BARCODE = 0;
private static final ProductData mProductData = new ProductData();
private EditText mBarcodeEdit;
private EditText mFormatEdit;
private EditText mTitleEdit;
private EditText mPriceEdit;
private Button mScanButton;
private Button mAddButton;
private CodiciDatabase mProductDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scanButton);
mScanButton.setOnClickListener(this);
mAddButton = (Button) findViewById(R.id.addButton);
mAddButton.setOnClickListener(this);
mProductDb = new CodiciDatabase(this); // not yet shown
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.scanButton:
Intent intent = new Intent ("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, REQUEST_BARCODE);
break;
case R.id.addButton:
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(this, "Success", "Product saved successfully");
resetForm();
}
break;
}
}
}
private void resetForm() {
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder (context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent){
if (requestCode == REQUEST_BARCODE){
if (resultCode == RESULT_OK) {
String barcode = intent.getStringExtra("SCAN_RESULT");
mBarcodeEdit.setText(barcode);
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
mFormatEdit.setText(format);
} else if (resultCode == RESULT_CANCELED){
finish();
}
}
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}
Overview of what you need to do:
Run a query on your database that will return a Cursor to you. Once you've got that you'll have to make make a CursorAdapter and override its getView() method to inflate and populate the row Views. After that you can use the ListView.setAdapter() method passing in an instance of your adapter. It will handle updating the list on the screen for you whenever there is new data.
I suggest instead of trying to tackle this in your own project you take a break from that and go do this Notepad tutorial from the developer docs. It is very small and simple but once you are complete you will have some sample code to use when you are working on doing this for your barcode application.

Categories

Resources