Error in displaying data in custom listView while scrolling - android

My salute to the scholars. I am little embarrassed with custom listview. While scrolling, the values i am displaying in listview, gets changed. And on clicking on any listitem, it shows the data of the first record that is currently visible. Please help me out with it. I dont know how to handle getView() method to correct this bug.
My java code:
package com.addictioncounterapp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class StartActivity extends Activity
{
ListView listview1;
static SQLiteDatabase database;
private Addiction[] addictions;
private ArrayAdapter<Addiction> listAdapter ;
ArrayList<Addiction> addictionList;
ImageView iv_settings;
static int limit;
static String attribute;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
createDB();
loadDB();
iv_settings = (ImageView) findViewById(R.id.imageViewStart);
iv_settings.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(StartActivity.this, Settings.class);
startActivity(intent);
}
}
);
manageList();
listview1 = (ListView) findViewById(R.id.listViewStart);
if(addictionList.isEmpty())
{
Toast.makeText(getBaseContext(), "No records of Addiction found...Go to 'Settings > Manage Addictions > Add' to create new addiction.", Toast.LENGTH_LONG).show();
}
else
{
listview1.setAdapter(listAdapter);
}
listview1.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
View parentView = (View) arg1.getParent();
String textview1 = ((TextView) parentView.findViewById(R.id.textViewStartAddictionName)).getText().toString();
Intent intent = new Intent(StartActivity.this, AddictionDetails.class);
intent.putExtra("cat_name", textview1);
startActivity(intent);
}
}
);
}
private void createDB()
{
database = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
database.setLocale(Locale.getDefault());
database.setVersion(1);
try
{
String create_table_1 = "create table if not exists category (cat_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" cat_server_id INTEGER," +
" cat_name TEXT UNIQUE," +
" parent_cat_id INTEGER," +
" is_delete INTEGER," +
" is_sync INTEGER," +
" creation_date TEXT," +
" update_date TEXT)";
database.execSQL(create_table_1);
String create_table_2 = "create table if not exists category_attribute (cat_attribute_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" cat_attribute_server_id INTEGER," +
" cat_server_id INTEGER," +
" cat_id INTEGER," +
" cat_attribute_name TEXT," +
" cat_attribute_unit INTEGER," +
" cat_limit INTEGER," +
" is_delete INTEGER," +
" is_sync INTEGER," +
" creation_date TEXT," +
" update_date TEXT)";
database.execSQL(create_table_2);
String create_table_3 = "create table if not exists category_limit (limit_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" limit_server_id INTEGER," +
" cat_id INTEGER," +
" limit_count INTEGER," +
" is_delete INTEGER," +
" is_sync INTEGER," +
" creation_date TEXT," +
" update_date TEXT)";
database.execSQL(create_table_3);
String create_table_4 = "create table if not exists counter (counter_id INTEGER PRIMARY KEY AUTOINCREMENT," +
" counter_server_id INTEGER," +
" cat_id INTEGER," +
" cat_attribute_id INTEGER," +
" cat_attribute_unit INTEGER," +
" counter_entry_date TEXT," +
" counter_entry_date_time TEXT," +
" is_delete INTEGER," +
" is_sync INTEGER)";
database.execSQL(create_table_4);
}
catch(SQLException e)
{
Log.e("SQLException","The SQL string is invalid. ");
Toast.makeText(getBaseContext(), "SQLException: The SQL string is invalid.", Toast.LENGTH_SHORT).show();
}
database.close();
}
private void loadDB()
{
database = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.OPEN_READWRITE, null);
}
private void manageList()
{
String addictionName="", todaysCount="", dailyLimit="", unit="";
addictionList = new ArrayList<Addiction>();
AddictionsData objAddictionsData = new AddictionsData();
Cursor cursor = database.query("category", new String[]{"cat_id"}, null, null, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
int tmp_cat_id = cursor.getInt(0);
addictionName = objAddictionsData.getAddictionName(tmp_cat_id);
todaysCount = objAddictionsData.getTodaysCount(tmp_cat_id);
dailyLimit = objAddictionsData.getDailyLimit(tmp_cat_id);
unit = objAddictionsData.getUnit(tmp_cat_id);
addictions = new Addiction[]{new Addiction(tmp_cat_id, addictionName, todaysCount, dailyLimit, unit)};
addictionList.addAll( Arrays.asList(addictions) );
}
cursor.close();
}
listAdapter = new AddictionArrayAdapter(this, addictionList);
database.close();//---------------------------
}
public int insertIntoCounter(int id)
{
loadDB();//------------------------------------
//---------------------insert the record-------------------
ContentValues values = new ContentValues();
int cat_attribute_id = 0;
int cat_attribute_unit = 0;
Cursor cursor1 = database.query("category_attribute", new String[]{"cat_attribute_id", "cat_attribute_unit"}, "cat_id=?", new String[]{id+""}, null, null, null);
if(cursor1.getCount() > 0)
{
while(cursor1.moveToNext())
{
cat_attribute_id = cursor1.getInt(0);
cat_attribute_unit = cursor1.getInt(1);
}
cursor1.close();
}
Calendar c = Calendar.getInstance();
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String currentTimeAndDate = dtf.format(c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String currentDate = df.format(c.getTime());
values.put("counter_server_id", 0);
values.put("cat_id", id);
values.put("cat_attribute_id", cat_attribute_id);
values.put("cat_attribute_unit", cat_attribute_unit);
values.put("counter_entry_date", currentDate);
values.put("counter_entry_date_time", currentTimeAndDate);
values.put("is_delete", 0);
values.put("is_sync", 0);
try
{
database.insert("counter", null, values);
}
catch(Exception e)
{
Log.e("Exception", e+"");
}
//------------------------LIMIT FUNCTIONSLITY---------------------
//------------------------fetching attribute name
cursor1 = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{id+""}, null, null, null);
if(cursor1.getCount() > 0)
{
while(cursor1.moveToNext())
attribute = cursor1.getString(0);
cursor1.close();
}
//------------------------fetching limit
cursor1 = database.query("category_limit", new String[]{"limit_count"}, "cat_id=?", new String[]{id+""}, null, null, null);
if(cursor1.getCount() > 0)
{
while(cursor1.moveToNext())
limit = cursor1.getInt(0);
cursor1.close();
}
//--------------------------fetching todays count
int todays_count = 0;
Calendar cal1 = Calendar.getInstance();
SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
String todays_date = dateFormat1.format(cal1.getTime());
cursor1 = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+id+" AND counter_entry_date = '"+todays_date+"';", null);
while(cursor1.moveToNext())
todays_count = cursor1.getInt(0);
//---------------------sending acknowledgement
int ack;
if(todays_count < limit)
ack = 0;
else if(todays_count == limit)
ack = 1;
else
ack = 2;
return ack;
}
public static class Addiction
{
private String cat_name = "", cat_todays_count="", cat_daily_limit="", cat_attribute_unit="";
private int cat_id = 0;
public Addiction(int id, String catName, String catTodaysCount, String catDailyLimit, String catAttributeUnit)
{
cat_id = id;
cat_name = catName ;
cat_todays_count = catTodaysCount;
cat_daily_limit = catDailyLimit;
cat_attribute_unit = catAttributeUnit;
}
public int getId()
{
return cat_id;
}
public String getCatName()
{
return cat_name;
}
public String getCatTodaysCount()
{
return cat_todays_count;
}
public String getCatDailyLimit()
{
return cat_daily_limit;
}
public String getCatAttributeUnit()
{
return cat_attribute_unit;
}
}
private static class AddictionViewHolder
{
private ImageView imageViewAddictionLog ;
private TextView textViewAddictionName, textViewTodaysCount, textViewDailyLimit, textViewAttributeUnit ;
public AddictionViewHolder( ImageView iv_log, TextView tv_addiction_name, TextView tv_todays_count, TextView tv_daily_limit, TextView tv_attribute_count)
{
imageViewAddictionLog = iv_log;
textViewAddictionName = tv_addiction_name;
textViewTodaysCount = tv_todays_count;
textViewDailyLimit = tv_daily_limit;
textViewAttributeUnit = tv_attribute_count;
}
public ImageView getImageViewAddLog()
{
return imageViewAddictionLog;
}
public TextView getTextViewAddictionName()
{
return textViewAddictionName;
}
public TextView getTextViewTodaysCount()
{
return textViewTodaysCount;
}
public TextView getTextViewDailyLimit()
{
return textViewDailyLimit;
}
public TextView getTextViewAttributeUnit()
{
return textViewAttributeUnit;
}
}
private static class AddictionArrayAdapter extends ArrayAdapter<Addiction>
{
private LayoutInflater inflater;
StartActivity objStartActivity = new StartActivity();
public AddictionArrayAdapter( Context context, List<Addiction> addictionList )
{
super( context, R.layout.single_row_start, R.id.textViewStartAddictionName, addictionList );
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Addiction addiction = (Addiction) this.getItem( position );
ImageView imageViewAddLog ;
TextView textViewAN ;
final TextView textViewTC;
final TextView textViewDL;
final TextView textViewU;
if(convertView == null)
{
convertView = inflater.inflate(R.layout.single_row_start, null);
imageViewAddLog = (ImageView) convertView.findViewById(R.id.imageViewStartAdd);
textViewAN = (TextView) convertView.findViewById(R.id.textViewStartAddictionName);
textViewTC = (TextView) convertView.findViewById(R.id.textViewStartTodaysCountValue);
textViewDL = (TextView) convertView.findViewById(R.id.textViewStartDailyLimitCount);
textViewU = (TextView) convertView.findViewById(R.id.textViewStartAddictionUnit);
imageViewAddLog.setFocusable(false);
imageViewAddLog.setFocusableInTouchMode(false);
imageViewAddLog.setClickable(true);
convertView.setTag( new AddictionViewHolder(imageViewAddLog, textViewAN, textViewTC, textViewDL, textViewU) );
imageViewAddLog.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
ImageView ib = (ImageView) v ;
Addiction addiction = (Addiction) ib.getTag();
int tmp_cat_id = addiction.getId();
int ack = objStartActivity.insertIntoCounter(tmp_cat_id);
String cat_name = addiction.getCatName();
switch(ack)
{
case 0:
String message0 = "Record added Successfully.";
customShowDialog(message0, tmp_cat_id);
break;
case 1:
String message1 = "Please stop "+cat_name+". Today you have already added "+limit+" "+ attribute+". Your daily limit is "+limit+" "+attribute+".";
customShowDialog(message1, tmp_cat_id);
break;
case 2:
String message2 = "Please stop "+cat_name+". Today you have already added "+limit+" "+ attribute+". You have crossed your daily limit of "+limit+" "+attribute+".";
customShowDialog(message2, tmp_cat_id);
break;
}
}
private void customShowDialog(String message, final int cat_id)
{
AlertDialog.Builder adb = new Builder(getContext());
adb.setTitle("Success !!!");
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
adb.setPositiveButton("Ok",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
arg0.cancel();
AddictionsData ad = new AddictionsData();
textViewTC.setText( ad.getTodaysCount(cat_id));
textViewDL.setText( ad.getDailyLimit(cat_id));
textViewU.setText( ad.getUnit(cat_id));
}
}
);
AlertDialog ad = adb.create();
ad.show();
}
}
);
}
else
{
AddictionViewHolder viewHolder = (AddictionViewHolder) convertView.getTag();
imageViewAddLog = viewHolder.getImageViewAddLog();
textViewAN = viewHolder.getTextViewAddictionName();
textViewTC = viewHolder.getTextViewTodaysCount();
textViewDL = viewHolder.getTextViewDailyLimit();
textViewU = viewHolder.getTextViewAttributeUnit();
}
imageViewAddLog.setTag( addiction );
textViewAN.setText( addiction.getCatName());
textViewTC.setText( addiction.getCatTodaysCount());
textViewDL.setText( addiction.getCatDailyLimit());
textViewU.setText( addiction.getCatAttributeUnit());
return convertView;
}
}
public static class AddictionsData
{
Cursor cursor;
String getAddictionName(int cat_id)
{
String tmp_name = null;
cursor = database.query("category", new String[]{"cat_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
tmp_name = cursor.getString(0);
}
cursor.close();
}
return tmp_name;
}
String getTodaysCount(int cat_id)
{
String todaysCount = null;
int todays_count = 0;
Calendar cal1 = Calendar.getInstance();
SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
String todays_date = dateFormat1.format(cal1.getTime());
cursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date = '"+todays_date+"';", null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
todays_count = cursor.getInt(0);
}
cursor.close();
}
String attribute = null;
cursor = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
attribute = cursor.getString(0);
}
cursor.close();
}
todaysCount = todays_count+" "+attribute;
return todaysCount;
}
String getDailyLimit(int cat_id)
{
String dailyLimit;
int daily_limit = 0;
cursor = database.query("category_limit", new String[]{"limit_count"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
daily_limit = cursor.getInt(0);
cursor.close();
}
String attribute = null;
cursor = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
attribute = cursor.getString(0);
}
cursor.close();
}
dailyLimit = daily_limit+ " "+attribute;
return dailyLimit;
}
String getUnit(int cat_id)
{
String unit;
int _unit = 0;
cursor = database.query("category_attribute", new String[]{"cat_attribute_unit"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
_unit = cursor.getInt(0);
cursor.close();
}
String attribute = null;
cursor = database.query("category_attribute", new String[]{"cat_attribute_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() > 0)
{
while(cursor.moveToNext())
{
attribute = cursor.getString(0);
}
cursor.close();
}
unit = _unit+ " "+attribute;
return unit;
}
}
}
My main layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/main_bg_edited" >
<ImageView
android:id="#+id/imageViewStart"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/setting_icon"
android:layout_marginRight="7dp" />
<ListView
android:id="#+id/listViewStart"
android:layout_width="290dp"
android:layout_height="wrap_content"
android:layout_below="#+id/imageViewStart"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:divider="#android:color/transparent"
android:dividerHeight="10dp"
android:drawSelectorOnTop="true" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageViewStart"
android:layout_centerHorizontal="true"
android:text="Addictions"
style="#style/header_style" />
</RelativeLayout>
The layout from which i am inflating the view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/box_midbg" >
<TextView
android:id="#+id/textViewStartTodaysCountValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewStartAddictionName"
android:layout_toRightOf="#+id/textViewTodaysCount"
android:text=" TextView"
android:textSize="10sp"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textViewStartDailyLimitCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textViewStartTodaysCountValue"
android:layout_alignTop="#+id/textViewDailyLimit"
android:text="TextView"
android:textSize="10sp"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textViewStartAddictionUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textViewStartTodaysCountValue"
android:layout_marginRight="15dp"
android:text="TextView"
android:textColor="#ffffff"
android:textSize="10sp" />
<TextView
android:id="#+id/textViewStartAddictionName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageViewStartAdd"
android:layout_alignParentLeft="true"
android:layout_marginLeft="15dp"
android:text="TextView"
android:textColor="#ffffff"
android:textSize="20sp" />
<TextView
android:id="#+id/textViewTodaysCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textViewStartAddictionUnit"
android:layout_alignLeft="#+id/textViewStartAddictionName"
android:text="Today&apos;s Counts : "
android:textColor="#ffffff"
android:textSize="10sp" />
<TextView
android:id="#+id/textViewDailyLimit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textViewTodaysCount"
android:layout_below="#+id/textViewTodaysCount"
android:text="Daily Limit :"
android:textColor="#ffffff"
android:textSize="10sp" />
<ImageView
android:id="#+id/imageViewStartAdd"
android:layout_width="25sp"
android:layout_height="25sp"
android:layout_alignRight="#+id/textViewStartAddictionUnit"
android:layout_centerVertical="true"
android:clickable="true"
android:src="#drawable/add_btn" />
</RelativeLayout>

You should not store your data in the views as views are recycled and what will happen will almost certainly be what you didn't expect. The following
Addiction addiction = (Addiction) ib.getTag();
....
imageViewAddLog.setTag( addiction );
is not advisable. A better way is to let the list view handle the clicks so that you can know which view has been clicked and the correct Addiction object that corresponds to the view's position.
myList.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Addiction addiction = (Addiction) myList.getItemAtPosition(position);
...rest of code...
}
}
);

Please put all your other code after
convertView.setTag( new AddictionViewHolder(imageViewAddLog, textViewAN, textViewTC, textViewDL, textViewU) );
outside if and try to remove else from code.
rest of code of else will be same after if. Remember that when convertview is null, create a new holder and set in Tag. Then retrieve that object from Tag when convertview is not null. And write all other code like setting values to views etc after
AddictionViewHolder viewHolder = (AddictionViewHolder) convertView.getTag();

Related

Android: How can I search data in sqlite database

I making project that user can scanning a barcode. My problem is, if the scanning results are the same as the kode_obat column, then the nama_obat, and harga_jual columns will be displayed or setText to Textview.
Please help me, How should I code ?
Here my Code :
MyDatabaseHelper.class
private Context context;
private static final String DATABASE_NAME = "Apotek.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "obat";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_KODEOBAT = "kode_obat";
private static final String COLUMN_NAMAOBAT = "nama_obat";
//private static final String COLUMN_NOBATCH = "no_batch";
private static final String COLUMN_DISTRIBUTOR = "distributor";
private static final String COLUMN_EXPIRED = "expired_obat";
private static final String COLUMN_SATUAN = "satuan";
private static final String COLUMN_HARGASATUAN = "harga_satuan";
private static final String COLUMN_HARGAJUAL = "harga_jual";
private static final String COLUMN_PRODUSEN = "produsen";
//private static final String COLUMN_STOK = "stok_obat";
//private static final String COLUMN_HARGAOBAT = "harga_obat";
MyDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_KODEOBAT + " TEXT, " +
COLUMN_NAMAOBAT + " TEXT, " +
COLUMN_DISTRIBUTOR + " TEXT, " +
COLUMN_EXPIRED + " TEXT, " +
COLUMN_SATUAN + " TEXT, " +
COLUMN_HARGASATUAN + " INTEGER, " +
COLUMN_HARGAJUAL + " INTEGER, " +
COLUMN_PRODUSEN + " TEXT);";
db.execSQL(query);
String query1 = "CREATE TABLE " + TABLE_NAME1 +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_DATE + " TEXT, " +
COLUMN_BAYAR + " INTEGER);";
db.execSQL(query1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME1);
onCreate(db);
}
void addObat(String kodeobat, String namaobat, String distributor, String expired, String satuan, int hargasatuan, int hargajual, String produsen){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_KODEOBAT, kodeobat);
cv.put(COLUMN_NAMAOBAT, namaobat);
cv.put(COLUMN_DISTRIBUTOR, distributor);
cv.put(COLUMN_EXPIRED, expired);
cv.put(COLUMN_SATUAN, satuan);
cv.put(COLUMN_HARGASATUAN, hargasatuan);
cv.put(COLUMN_HARGAJUAL, hargajual);
cv.put(COLUMN_PRODUSEN, produsen);
long result = db.insert(TABLE_NAME,null, cv);
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
void addLaporan(String date, String bayar){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_DATE, date);
cv.put(COLUMN_BAYAR, bayar);
long result = db.insert(TABLE_NAME1,null, cv);
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
Cursor readAllDataLaporan(){
String query = "SELECT * FROM " + TABLE_NAME1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
void updateObat(String row_id, String kodeobat, String namaobat, String distributor, String expired, String satuan, String hargasatuan, String hargajual, String produsen){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_KODEOBAT, kodeobat);
cv.put(COLUMN_NAMAOBAT, namaobat);
cv.put(COLUMN_DISTRIBUTOR, distributor);
cv.put(COLUMN_EXPIRED, expired);
cv.put(COLUMN_SATUAN, satuan);
cv.put(COLUMN_HARGASATUAN, hargasatuan);
cv.put(COLUMN_HARGAJUAL, hargajual);
cv.put(COLUMN_PRODUSEN, produsen);
long result = db.update(TABLE_NAME, cv, "_id=?", new String[]{row_id});
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Updated Successfully!", Toast.LENGTH_SHORT).show();
}
}
void updateData(String row_id, String date, String bayar){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_DATE, date);
cv.put(COLUMN_BAYAR, bayar);
long result = db.update(TABLE_NAME1, cv, "_id=?", new String[]{row_id});
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Updated Successfully!", Toast.LENGTH_SHORT).show();
}
}
void deleteOneRow(String row_id){
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_NAME, "_id=?", new String[]{row_id});
if(result == -1){
Toast.makeText(context, "Failed to Delete.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Successfully Deleted.", Toast.LENGTH_SHORT).show();
}
}
void deleteData(String row_id){
SQLiteDatabase db = this.getWritableDatabase();
long result = db.delete(TABLE_NAME1, "_id=?", new String[]{row_id});
if(result == -1){
Toast.makeText(context, "Failed to Delete.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Successfully Deleted.", Toast.LENGTH_SHORT).show();
}
}
void deleteAllData(){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME);
}
TransaksiActivity.class
EditText ETnamaobattransaksi1, ETnamaobattransaksi2,ETnamaobattransaksi3, ETnamaobattransaksi4, ETnamaobattransaksi5, ETnamaobattransaksi6, ETnamaobattransaksi7,ETnamaobattransaksi8,ETnamaobattransaksi9,ETnamaobattransaksi10,
EThargaobattransaksi1, EThargaobattransaksi2, EThargaobattransaksi3, EThargaobattransaksi4, EThargaobattransaksi5, EThargaobattransaksi6, EThargaobattransaksi7, EThargaobattransaksi8, EThargaobattransaksi9, EThargaobattransaksi10,
ETjumlahobattransaksi1, ETjumlahobattransaksi2, ETjumlahobattransaksi3, ETjumlahobattransaksi4, ETjumlahobattransaksi5 , ETjumlahobattransaksi6, ETjumlahobattransaksi7, ETjumlahobattransaksi8, ETjumlahobattransaksi9 ,ETjumlahobattransaksi10, ETcash;
Button BTNScan, BTNcetak, BTNtotal, BTNkembalian;
TextView TVtotalobat1, TVtotalobat2, TVtotalobat3, TVtotalobat4, TVtotalobat5,TVtotalobat6, TVtotalobat7, TVtotalobat8, TVtotalobat9, TVtotalobat10, TVdate, TVTotalhitungtransaksi, TVTotalhitungtransaksiclick, TVkembalian;
int total1,total2=0,total3=0,total4=0,total5=0,total6=0,total7=0,total8=0,total9=0, total10=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaksi);
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
TVdate = findViewById(R.id.TVdate);
TVdate.setText(currentDate);
ETnamaobattransaksi1 = findViewById(R.id.ETnamaobattransaksi1);
ETnamaobattransaksi2 = findViewById(R.id.ETnamaobattransaksi2);
ETnamaobattransaksi3 = findViewById(R.id.ETnamaobattransaksi3);
ETnamaobattransaksi4 = findViewById(R.id.ETnamaobattransaksi4);
ETnamaobattransaksi5 = findViewById(R.id.ETnamaobattransaksi5);
ETnamaobattransaksi6 = findViewById(R.id.ETnamaobattransaksi6);
ETnamaobattransaksi7 = findViewById(R.id.ETnamaobattransaksi7);
ETnamaobattransaksi8 = findViewById(R.id.ETnamaobattransaksi8);
ETnamaobattransaksi9 = findViewById(R.id.ETnamaobattransaksi9);
ETnamaobattransaksi10 = findViewById(R.id.ETnamaobattransaksi10);
EThargaobattransaksi1 = findViewById(R.id.EThargaobattransaksi1);
EThargaobattransaksi2 = findViewById(R.id.EThargaobattransaksi2);
EThargaobattransaksi3 = findViewById(R.id.EThargaobattransaksi3);
EThargaobattransaksi4 = findViewById(R.id.EThargaobattransaksi4);
EThargaobattransaksi5 = findViewById(R.id.EThargaobattransaksi5);
EThargaobattransaksi6 = findViewById(R.id.EThargaobattransaksi6);
EThargaobattransaksi7 = findViewById(R.id.EThargaobattransaksi7);
EThargaobattransaksi8 = findViewById(R.id.EThargaobattransaksi8);
EThargaobattransaksi9 = findViewById(R.id.EThargaobattransaksi9);
EThargaobattransaksi10 = findViewById(R.id.EThargaobattransaksi10);
ETjumlahobattransaksi1 = findViewById(R.id.ETjumlahobattransaksi1);
ETjumlahobattransaksi2 = findViewById(R.id.ETjumlahobattransaksi2);
ETjumlahobattransaksi3 = findViewById(R.id.ETjumlahobattransaksi3);
ETjumlahobattransaksi4 = findViewById(R.id.ETjumlahobattransaksi4);
ETjumlahobattransaksi5 = findViewById(R.id.ETjumlahobattransaksi5);
ETjumlahobattransaksi6 = findViewById(R.id.ETjumlahobattransaksi6);
ETjumlahobattransaksi7 = findViewById(R.id.ETjumlahobattransaksi7);
ETjumlahobattransaksi8 = findViewById(R.id.ETjumlahobattransaksi8);
ETjumlahobattransaksi9 = findViewById(R.id.ETjumlahobattransaksi9);
ETjumlahobattransaksi10 = findViewById(R.id.ETjumlahobattransaksi10);
TVtotalobat1 = findViewById(R.id.ETtotalobat1);
TVtotalobat2 = findViewById(R.id.ETtotalobat2);
TVtotalobat3 = findViewById(R.id.ETtotalobat3);
TVtotalobat4 = findViewById(R.id.ETtotalobat4);
TVtotalobat5 = findViewById(R.id.ETtotalobat5);
TVtotalobat6 = findViewById(R.id.ETtotalobat6);
TVtotalobat7 = findViewById(R.id.ETtotalobat7);
TVtotalobat8 = findViewById(R.id.ETtotalobat8);
TVtotalobat9 = findViewById(R.id.ETtotalobat9);
TVtotalobat10 = findViewById(R.id.ETtotalobat10);
BTNtotal = findViewById(R.id.BTNtotal);
TVTotalhitungtransaksi = findViewById(R.id.TVTotalhitungtransaksi);
BTNkembalian = findViewById(R.id.BTNkembalian);
TVkembalian = findViewById(R.id.TVkembalian);
ETcash = findViewById(R.id.ETcash);
BTNcetak = findViewById(R.id.BTNcetak);
BTNcetak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyDatabaseHelper myDB = new MyDatabaseHelper(TransaksiActivity.this);
myDB.addLaporan(currentDate.toString().trim(),
TVTotalhitungtransaksi.getText().toString().trim());
}
});
BTNScan = findViewById(R.id.BTNscan);
BTNScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanCode();
}
});
BTNtotal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String harga1 = EThargaobattransaksi1.getText().toString();
String jumlah1 = ETjumlahobattransaksi1.getText().toString();
String harga2 = EThargaobattransaksi2.getText().toString();
String jumlah2 = ETjumlahobattransaksi2.getText().toString();
String harga3 = EThargaobattransaksi3.getText().toString();
String jumlah3 = ETjumlahobattransaksi3.getText().toString();
String harga4 = EThargaobattransaksi4.getText().toString();
String jumlah4 = ETjumlahobattransaksi4.getText().toString();
String harga5 = EThargaobattransaksi5.getText().toString();
String jumlah5 = ETjumlahobattransaksi5.getText().toString();
String harga6 = EThargaobattransaksi6.getText().toString();
String jumlah6 = ETjumlahobattransaksi6.getText().toString();
String harga7 = EThargaobattransaksi7.getText().toString();
String jumlah7 = ETjumlahobattransaksi7.getText().toString();
String harga8 = EThargaobattransaksi8.getText().toString();
String jumlah8 = ETjumlahobattransaksi8.getText().toString();
String harga9 = EThargaobattransaksi9.getText().toString();
String jumlah9 = ETjumlahobattransaksi9.getText().toString();
String harga10 = EThargaobattransaksi10.getText().toString();
String jumlah10 = ETjumlahobattransaksi10.getText().toString();
if(harga1.equals("")&&jumlah1.equals(""))
{
int harga1int = 0;
int jumlah1int = 0;
total1 = (harga1int*jumlah1int);
}
else
{
int harga1int = Integer.parseInt(harga1);
int jumlah1int = Integer.parseInt(jumlah1);
total1 = (harga1int*jumlah1int);
}
if(harga2.equals("")&&jumlah2.equals(""))
{
int harga2int = 0;
int jumlah2int = 0;
total2 = (harga2int*jumlah2int);
}
else
{
int harga2int = Integer.parseInt(harga2);
int jumlah2int = Integer.parseInt(jumlah2);
total2 = (Integer.parseInt(harga2)*Integer.parseInt(jumlah2));
}
if(harga3.equals("")&&jumlah3.equals(""))
{
int harga3int = 0;
int jumlah3int = 0;
total3 = (harga3int*jumlah3int);
}
else
{
int harga3int = Integer.parseInt(harga3);
int jumlah3int = Integer.parseInt(jumlah3);
total3 = (Integer.parseInt(harga3)*Integer.parseInt(jumlah3));
}
if(harga4.equals("")&&jumlah4.equals(""))
{
int harga4int = 0;
int jumlah4int = 0;
total4 = (harga4int*jumlah4int);
}
else
{
int harga4int = Integer.parseInt(harga4);
int jumlah4int = Integer.parseInt(jumlah4);
total4 = (Integer.parseInt(harga4)*Integer.parseInt(jumlah4));
}
if(harga5.equals("")&&jumlah5.equals(""))
{
int harga5int = 0;
int jumlah5int = 0;
total5 = (harga5int*jumlah5int);
}
else
{
int harga5int = Integer.parseInt(harga5);
int jumlah5int = Integer.parseInt(jumlah5);
total5 = (Integer.parseInt(harga5)*Integer.parseInt(jumlah5));
}
if(harga6.equals("")&&jumlah6.equals(""))
{
int harga6int = 0;
int jumlah6int = 0;
total6 = (harga6int*jumlah6int);
}
else
{
int harga6int = Integer.parseInt(harga6);
int jumlah6int = Integer.parseInt(jumlah6);
total6 = (Integer.parseInt(harga6)*Integer.parseInt(jumlah6));
}
if(harga7.equals("")&&jumlah7.equals(""))
{
int harga7int = 0;
int jumlah7int = 0;
total7 = (harga7int*jumlah7int);
}
else
{
int harga7int = Integer.parseInt(harga7);
int jumlah7int = Integer.parseInt(jumlah7);
total7 = (Integer.parseInt(harga7)*Integer.parseInt(jumlah7));
}
if(harga8.equals("")&&jumlah8.equals(""))
{
int harga8int = 0;
int jumlah8int = 0;
total8 = (harga8int*jumlah8int);
}
else
{
int harga8int = Integer.parseInt(harga8);
int jumlah8int = Integer.parseInt(jumlah8);
total8 = (Integer.parseInt(harga8)*Integer.parseInt(jumlah8));
}
if(harga9.equals("")&&jumlah9.equals(""))
{
int harga9int = 0;
int jumlah9int = 0;
total9 = (harga9int*jumlah9int);
}
else
{
int harga9int = Integer.parseInt(harga9);
int jumlah9int = Integer.parseInt(jumlah9);
total9 = (Integer.parseInt(harga9)*Integer.parseInt(jumlah9));
}
if(harga10.equals("")&&jumlah10.equals(""))
{
int harga10int = 0;
int jumlah10int = 0;
total10 = (harga10int*jumlah10int);
}
else
{
int harga10int = Integer.parseInt(harga10);
int jumlah10int = Integer.parseInt(jumlah10);
total10 = (Integer.parseInt(harga10)*Integer.parseInt(jumlah10));
}
int totalbayar = (total1+total2+total3+total4+total5+total6+total7+total8+total9+total10);
//int totalbayar = (total1);
TVtotalobat1.setText("Rp."+String.valueOf(total1));
TVtotalobat2.setText("Rp."+String.valueOf(total2));
TVtotalobat3.setText("Rp."+String.valueOf(total3));
TVtotalobat4.setText("Rp."+String.valueOf(total4));
TVtotalobat5.setText("Rp."+String.valueOf(total5));
TVtotalobat6.setText("Rp."+String.valueOf(total6));
TVtotalobat7.setText("Rp."+String.valueOf(total7));
TVtotalobat8.setText("Rp."+String.valueOf(total8));
TVtotalobat9.setText("Rp."+String.valueOf(total9));
TVtotalobat10.setText("Rp."+String.valueOf(total10));
//String texttotalbayar = String.valueOf(totalbayar);
TVTotalhitungtransaksi.setText("Rp."+String.valueOf(totalbayar));
BTNkembalian.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String bayar = ETcash.getText().toString();
int bayarint = Integer.parseInt(bayar);
int kembalian = bayarint - totalbayar;
TVkembalian.setText(String.valueOf("Rp."+kembalian));
}
});
private void scanCode()
{
ScanOptions options = new ScanOptions();
options.setPrompt("Volume to flash on");
options.setBeepEnabled(true);
options.setOrientationLocked(true);
options.setCaptureActivity(CaptureAct.class);
barLauncher.launch(options);
}
ActivityResultLauncher<ScanOptions> barLauncher = registerForActivityResult(new ScanContract(), result ->
{
if(result.getContents() !=null)
{
String namaobattransaksi1 = ETnamaobattransaksi1.getText().toString();
String namaobattransaksi2 = ETnamaobattransaksi2.getText().toString();
String namaobattransaksi3 = ETnamaobattransaksi3.getText().toString();
String namaobattransaksi4 = ETnamaobattransaksi4.getText().toString();
String namaobattransaksi5 = ETnamaobattransaksi5.getText().toString();
String namaobattransaksi6 = ETnamaobattransaksi6.getText().toString();
String namaobattransaksi7 = ETnamaobattransaksi7.getText().toString();
String namaobattransaksi8 = ETnamaobattransaksi8.getText().toString();
String namaobattransaksi9 = ETnamaobattransaksi9.getText().toString();
String namaobattransaksi10 = ETnamaobattransaksi10.getText().toString();
for(int f = 1; f<10; f++){
}
AlertDialog.Builder builder = new AlertDialog.Builder(TransaksiActivity.this);
//ETnamaobat.setText(result.getContents());
if(namaobattransaksi1.equals(""))
{
ETnamaobattransaksi1.setText(result.getContents());
}
else if (namaobattransaksi2.equals(""))
{
ETnamaobattransaksi2.setText(result.getContents());
}
else if (namaobattransaksi3.equals(""))
{
ETnamaobattransaksi3.setText(result.getContents());
}
else if (namaobattransaksi4.equals(""))
{
ETnamaobattransaksi4.setText(result.getContents());
}
else if (namaobattransaksi5.equals(""))
{
ETnamaobattransaksi5.setText(result.getContents());
}
else if (namaobattransaksi6.equals(""))
{
ETnamaobattransaksi6.setText(result.getContents());
}
else if (namaobattransaksi7.equals(""))
{
ETnamaobattransaksi7.setText(result.getContents());
}
else if (namaobattransaksi8.equals(""))
{
ETnamaobattransaksi8.setText(result.getContents());
}
else if (namaobattransaksi9.equals(""))
{
ETnamaobattransaksi9.setText(result.getContents());
}
else{
ETnamaobattransaksi10.setText(result.getContents());
}
builder.setTitle("Result");
builder.setMessage(result.getContents());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
}).show();
}
result.getContents().equals(null);
});
activity_transaksi.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:id="#+id/utama"
android:stretchColumns="1,2,3"
android:layout_margin="10dp"
android:divider="?android:attr/dividerHorizontal"
tools:context=".TransaksiActivity"
android:showDividers="middle">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:id="#+id/TVdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date"
android:textSize="18dp"
android:textAlignment="center"
android:layout_span="4"
android:textStyle="bold"
android:layout_margin="20dp"
android:layout_column="1"/>
</TableRow>
<TableRow>
<EditText
android:id="#+id/ETnamaobattransaksi1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Nama Obat"
android:textSize="15dp"
android:textStyle="bold"
android:textAlignment="center"
android:layout_column="1"/>
<EditText
android:id="#+id/ETjumlahobattransaksi1"
android:layout_width="27dp"
android:layout_height="wrap_content"
android:layout_column="1"
android:hint="Jumlah"
android:inputType="number"
android:textAlignment="center"
android:textSize="15dp"
android:textStyle="bold" />
<EditText
android:id="#+id/EThargaobattransaksi1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Harga Obat"
android:textSize="15dp"
android:inputType="number"
android:textStyle="bold"
android:textAlignment="center"
android:layout_column="1"/>
<TextView
android:id="#+id/ETtotalobat1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Total Obat"
android:textSize="15dp"
android:inputType="number"
android:textStyle="bold"
android:textColor="#color/black"
android:textAlignment="center"
android:layout_column="1"/>
</TableRow>
<TableRow>
<TableRow>
<!--<TextView
android:id="#+id/TVTotalhitungtransaksiclick"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:text="Total : Rp."
android:gravity="right"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginRight="30dp"
android:paddingTop="15dp"
android:textColor="#color/black"
android:layout_column="1"
android:layout_span="3"
/>-->
<Button
android:id="#+id/BTNtotal"
android:layout_width="85sp"
android:layout_height="40sp"
android:backgroundTint="#5a8f7b"
android:text="total"
android:textColor="#color/white"
android:layout_column="1"
android:layout_span="3"
android:layout_gravity="right"
android:textSize="10sp" />
<TextView
android:id="#+id/TVTotalhitungtransaksi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_column="4"
android:hint="Total"
android:layout_gravity="center"
android:textAlignment="center"
android:textColor="#color/black"
android:textColorHint="#A2B5BB"
android:textSize="15sp"
android:textStyle="bold" />
<!--<View
android:id="#+id/line1"
android:layout_width="match_parent"
android:layout_height="50dip"
android:layout_weight="1"
android:background="#00FFFFFF"
android:padding="2dip" />-->
</TableRow>
<TableRow>
<Button
android:id="#+id/BTNscan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="scan"
android:textSize="24dp"
android:layout_span="4"
android:layout_column="1"/>
</TableRow>
</TableLayout>
</ScrollView>
to do the search in the database thing you will need to add this code.
SQLiteDatabase database = new MyDatabaseHelper(context).getReadableDatabase();
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT " +
MyDatabaseHelper.COLUMN_NAMAOBAT + " , " + MyDatabaseHelper.COLUMN_HARGAJUAL +" FROM " + MyDatabaseHelper.TABLE_NAME + " WHERE " + MyDatabaseHelper.COLUMN_KODEOBAT + " = '" + YOUR_TEXT_HERE +"'", null);
if(cursor.getCount()>0){
cursor.moveToFirst();
YOUR_TEXTVIEW1.setText(cursor.getString(0));
YOUR_TEXTVIEW2.setText(cursor.getString(1));
}
else{
DO_YOUR_CODE_HERE
}
I hope this will help.
And you didn't have to post all of the code just a small sample,
Actually, in your case, you don't have to post any of this.

how I can change the value of the button depending on Spinner which takes the data from the database in Android?

I have a project to do android app, my app is about movies, I used the spinner to choose the name of the movie and there is a trailer button for each movie.
my question is how I can change the value of the button depending on the name of the movie.
I hope my question was clear
MainActivity class
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
TextView director;
TextView year;
TextView genre;
ImageView imageView;
TextView rating;
Button trailer;
TextView movieStory;
String[] movieNames = {"Test"};
Spinner movieSpinner;
movieDB MovieDB;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
movieSpinner = (Spinner) findViewById(R.id.moviespinner);
trailer = (Button) findViewById(R.id.button);
MovieDB = new movieDB(getApplicationContext());
rating = (TextView) findViewById(R.id.rateText);
director = (TextView) findViewById(R.id.director);
year = (TextView) findViewById(R.id.year);
genre = (TextView) findViewById(R.id.genretext);
imageView = (ImageView) findViewById(R.id.imageView);
movieStory = (TextView) findViewById(R.id.movieDetails);
movieNames = MovieDB.getMovieNames();
ArrayAdapter<String> movieAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.list_movie, movieNames);
movieAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
movieSpinner.setAdapter(movieAdapter);
movieSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
final int position, long arg3) {
if (movieNames.length > position) {
director.setText(MovieDB.getDirector(movieNames[position]));
year.setText(MovieDB.getYear(movieNames[position]).toString());
genre.setText(MovieDB.getGenre(movieNames[position]));
imageView.setImageResource(MovieDB.getPhoto(movieNames[position]));
rating.setText(((Float) MovieDB.getRate(movieNames[position])).toString());
movieStory.setText(MovieDB.getStory(movieNames[position]));
// here is the trailer button
trailer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.youtube.com/watch?v=gZjQROMAh_s"));
try {
MainActivity.this.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}
}
});
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
the database
movieDB class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class movieDB {
public static final String KEY_ID = "_id";
public static final String KEY_MOVIE_NAME =
"movie_name";
public static final String KEY_DIRECTOR =
"director_name";
public static final String KEY_YEAR =
"year";
public static final String KEY_GENRE =
"genre";
public static final String KEY_PHOTO =
"pic";
public static final String KEY_RATE =
"rate";
public static final String KEY_STORY =
"story";
public static final String KEY_URL =
"url";
private Context context;
private ModuleDBOpenHelper moduleDBOpenHelper;
public movieDB(Context context) {
this.context = context;
moduleDBOpenHelper = new ModuleDBOpenHelper(context, ModuleDBOpenHelper.DATABASE_NAME, null,
ModuleDBOpenHelper.DATABASE_VERSION);
// populate the database with some data in case it is empty
if (getAll().length == 0) {
this.addRow("1917", "Todd Phillips", 2019 ,"Crime, Drama, Thriller" , R.mipmap.mov_1917_foreground, 8.4f , context.getString(R.string.mov1917story),"https://www.youtube.com/watch?v=gZjQROMAh_s");
this.addRow("Avatar", "James Cameron", 2009, "Action, Adventure, Fantasy, Sci-Fi" , R.mipmap.avatar_foreground , 7.8f , context.getString(R.string.avatarstory),"https://www.youtube.com/watch?v=5PSNL1qE6VY");
this.addRow("Joker", "Todd Phillips", 2019,"Crime, Drama, Thriller" , R.mipmap.joker_foreground , 8.6f, context.getString(R.string.jokerstory),"https://www.youtube.com/watch?v=zAGVQLHvwOY");
this.addRow("Once Upon a Time in Hollywood", "Vladislav Kozlov", 2019,"Drama" , R.mipmap.hollywood_foreground , 7.7f , context.getString(R.string.hollywoodstory),"https://www.youtube.com/watch?v=ELeMaP8EPAA");
this.addRow("The Irishman", "Martin Scorsese", 2019,"Biography, Crime, Drama" , R.mipmap.irish_foreground , 8.0f , context.getString(R.string.irishmanstory),"https://www.youtube.com/watch?v=RS3aHkkfuEI");
}
}
public void addRow(String movieName, String director, int year, String genre , int pic , float rate , String story , String url) {
// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_MOVIE_NAME, movieName);
newValues.put(KEY_DIRECTOR, director);
newValues.put(KEY_YEAR, year);
newValues.put(KEY_GENRE, genre);
newValues.put(KEY_PHOTO, pic);
newValues.put(KEY_RATE, rate);
newValues.put(KEY_STORY, story);
newValues.put(KEY_URL, url);
// Insert the row into your table
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
db.insert(ModuleDBOpenHelper.DATABASE_TABLE, null, newValues);
}
public String[] getAll() {
ArrayList<String> outputArray = new ArrayList<String>();
String[] result_columns = new String[]{
KEY_MOVIE_NAME, KEY_DIRECTOR, KEY_YEAR , KEY_GENRE};
String movieName;
String directorName;
int year;
String genre;
String where = null;
String whereArgs[] = null;
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
boolean result = cursor.moveToFirst();
while (result) {
movieName = cursor.getString(cursor.getColumnIndex(KEY_MOVIE_NAME));
directorName = cursor.getString(cursor.getColumnIndex(KEY_DIRECTOR));
year = cursor.getInt(cursor.getColumnIndex(KEY_YEAR));
genre = cursor.getString(cursor.getColumnIndex(KEY_GENRE));
outputArray.add(movieName + " "+ directorName + year + " " + genre);
result = cursor.moveToNext();
}
return outputArray.toArray(new String[outputArray.size()]);
}
public String[] getMovieNames() {
ArrayList<String> outputArray = new ArrayList<String>();
String[] result_columns = new String[]{
KEY_MOVIE_NAME};
String movieName;
String where = null;
String whereArgs[] = null;
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
//
boolean result = cursor.moveToFirst();
while (result) {
movieName = cursor.getString(cursor.getColumnIndex(KEY_MOVIE_NAME));
outputArray.add(movieName);
result = cursor.moveToNext();
}
return outputArray.toArray(new String[outputArray.size()]);
}
public String geturl(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_URL};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnGenre = cursor.getColumnIndex(KEY_URL);
return cursor.getString(columnGenre);
} else return null;
}
public Integer getYear(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_YEAR};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnYear = cursor.getColumnIndex(KEY_YEAR);
return cursor.getInt(columnYear);
} else return 0;
}
public String getGenre(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_GENRE};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnGenre = cursor.getColumnIndex(KEY_GENRE);
return cursor.getString(columnGenre);
} else return null;
}
public String getStory(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_STORY};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnStory = cursor.getColumnIndex(KEY_STORY);
return cursor.getString(columnStory);
} else return null;
}
public Integer getPhoto(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_PHOTO};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnPhoto = cursor.getColumnIndex(KEY_PHOTO);
return cursor.getInt(columnPhoto);
} else return 0;
}
public float getRate(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_RATE};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnRate = cursor.getColumnIndex(KEY_RATE);
return cursor.getFloat(columnRate);
} else return 0;
}
public String getDirector(String movieName) {
String[] result_columns = new String[]{
KEY_ID, KEY_DIRECTOR};
String where = KEY_MOVIE_NAME + "= ?";
String whereArgs[] = {movieName};
String groupBy = null;
String having = null;
String order = null;
SQLiteDatabase db = moduleDBOpenHelper.getWritableDatabase();
Cursor cursor = db.query(ModuleDBOpenHelper.DATABASE_TABLE,
result_columns, where,
whereArgs, groupBy, having, order);
if (cursor.moveToFirst()) {
int columnDirector = cursor.getColumnIndex(KEY_DIRECTOR);
return cursor.getString(columnDirector);
} else return null;
}
private static class ModuleDBOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase.db";
private static final String DATABASE_TABLE = "Movies";
private static final int DATABASE_VERSION = 1;
// SQL Statement to create a new database.
private static final String DATABASE_CREATE = "create table " +
DATABASE_TABLE + " (" + KEY_ID +
" integer primary key autoincrement, " +
KEY_MOVIE_NAME + " text not null, " +
KEY_DIRECTOR + " text , " +
KEY_YEAR + " int , " +
KEY_GENRE + " text , " +
KEY_PHOTO + " int , " +
KEY_RATE + " float , " +
KEY_STORY + " text , " +
KEY_URL + " text );";
public ModuleDBOpenHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that
// the version of the database on disk needs to be upgraded to
// the current version.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +
oldVersion + " to " +
newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new
// version. Multiple previous versions can be handled by
// comparing oldVersion and newVersion values.
// The simplest case is to drop the old table and create a new one.
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Create a new one.
onCreate(db);
}
}
}
XML Layout
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Spinner
android:id="#+id/moviespinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<RelativeLayout
android:id="#+id/directorcontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/moviespinner">
<TextView
android:id="#+id/directorHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/director"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/director"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/directorHeading"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/yearcontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/directorcontainer"
android:layout_toRightOf="#+id/directorcontainer"
android:layout_marginLeft="20dp"
android:layout_toEndOf="#+id/directorcontainer"
android:layout_marginStart="20dp">
<TextView
android:id="#+id/yearHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/year"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/yearHeading"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/genrecontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/directorcontainer"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#id/yearcontainer"
android:layout_marginStart="20dp"
android:layout_toEndOf="#id/yearcontainer">
<TextView
android:id="#+id/genreHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/genre"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/genretext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/genreHeading"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<LinearLayout
android:layout_below="#+id/genrecontainer"
android:layout_width="match_parent"
android:layout_height="661dp"
android:layout_alignParentBottom="true"
android:layout_marginTop="8dp"
android:layout_marginBottom="0dp"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="147dp"
android:contentDescription="#string/thumb"
app:srcCompat="#drawable/ic_launcher_background" />
<Space
android:layout_width="match_parent"
android:layout_height="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal">
<Button
android:id="#+id/button"
style="#android:style/Widget.Button.Inset"
android:layout_width="98dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/trailer" />
<Space
android:layout_width="34dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<LinearLayout
android:layout_width="34dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<Space
android:layout_width="match_parent"
android:layout_height="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/star"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
app:srcCompat="#android:drawable/btn_star_big_on" />
<TextView
android:id="#+id/rateText"
android:layout_width="35dp"
android:layout_height="match_parent"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/rate10"
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:text="#string/_10" />
</LinearLayout>
<Space
android:layout_width="match_parent"
android:layout_height="13dp" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/movieDetails"
android:layout_width="match_parent"
android:layout_height="180dp" />
<Space
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:id="#+id/test_URL"
android:layout_width="match_parent"
android:layout_height="90dp" />
</LinearLayout>
</RelativeLayout>
XML Layout list_movie.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
[Image] the appearance of the application
Thanks in advance
Try this:
trailer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(MovieDB.geturl(movieNames[position])));
try {
MainActivity.this.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}
}
});

Populating data from Edittext input to Spinner Display using Sqlite

Expert Please advise with following my query.
I am trying to run the query in Android studio .
As is : Spinner shows the X value as per edittext X value input using Textwatcher.
To be : Spinner should show the Y value as per X value input in Edit text.
Example: If i enter value "6" in edittext then my spinner should show the vaue "Data Structures"
My Database follows.
Database follows
package com.bar.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
class DBHelper extends SQLiteOpenHelper {
private Context mContext;
//TASK: DEFINE THE DATABASE VERSION AND NAME (DATABASE CONTAINS MULTIPLE TABLES)
static final String DATABASE_NAME = "OCC";
private static final int DATABASE_VERSION = 1;
//TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE COURSES TABLE
public static final String COURSES_TABLE = "Courses";
public static final String COURSES_KEY_FIELD_ID = "_id";
public static final String FIELD_ALPHA = "alpha";
public static final String FIELD_NUMBER = "number";
public static final String FIELD_TITLE = "title";
//TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE INSTRUCTORS TABLE
//TASK: DEFINE THE FIELDS (COLUMN NAMES) FOR THE OFFERINGS TABLE
private static final String OFFERINGS_TABLE = "Offerings";
private static final String OFFERINGS_KEY_FIELD_ID = "crn";
private static final String FIELD_SEMESTER_CODE = "semester_code";
public static final String FIELD_COURSE_ID = "course_id";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase database) {
String createQuery = "CREATE TABLE " + COURSES_TABLE + "(" +
COURSES_KEY_FIELD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FIELD_ALPHA + " TEXT, " +
FIELD_NUMBER + " TEXT, " +
FIELD_TITLE + " TEXT" + ")";
database.execSQL(createQuery);
createQuery = "CREATE TABLE " + OFFERINGS_TABLE + "(" +
OFFERINGS_KEY_FIELD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
FIELD_SEMESTER_CODE + " INTEGER, " +
FIELD_COURSE_ID + " INTEGER, "
+
"FOREIGN KEY(" + FIELD_COURSE_ID + ") REFERENCES "
+
COURSES_TABLE + "(" + COURSES_KEY_FIELD_ID + ")" +
")";
database.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase database,
int oldVersion,
int newVersion) {
database.execSQL("DROP TABLE IF EXISTS " + COURSES_TABLE);
database.execSQL("DROP TABLE IF EXISTS " + OFFERINGS_TABLE);
onCreate(database);
}
//********** COURSE TABLE OPERATIONS: ADD, GETALL, EDIT, DELETE
public void addCourse(Course course) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_ALPHA, course.getAlpha());
values.put(FIELD_NUMBER, course.getNumber());
values.put(FIELD_TITLE, course.getTitle());
db.insert(COURSES_TABLE, null, values);
// CLOSE THE DATABASE CONNECTION
db.close();
}
public ArrayList < Course > getAllCourses() {
ArrayList < Course > coursesList = new ArrayList < > ();
SQLiteDatabase database = this.getReadableDatabase();
//Cursor cursor = database.rawQuery(queryList, null);
Cursor cursor = database.query(
COURSES_TABLE,
new String[] {
COURSES_KEY_FIELD_ID,
FIELD_ALPHA,
FIELD_NUMBER,
FIELD_TITLE
},
null,
null,
null, null, null, null);
//COLLECT EACH ROW IN THE TABLE
if (cursor.moveToFirst()) {
do {
Course course =
new Course(cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3));
coursesList.add(course);
} while (cursor.moveToNext());
}
return coursesList;
}
public void deleteCourse(Course course) {
SQLiteDatabase db = this.getWritableDatabase();
// DELETE THE TABLE ROW
db.delete(COURSES_TABLE, COURSES_KEY_FIELD_ID + " = ?",
new String[] {
String.valueOf(course.getId())
});
db.close();
}
public void deleteAllCourses() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(COURSES_TABLE, null, null);
db.close();
}
public void updateCourse(Course course) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_ALPHA, course.getAlpha());
values.put(FIELD_NUMBER, course.getNumber());
values.put(FIELD_TITLE, course.getTitle());
db.update(COURSES_TABLE, values, COURSES_KEY_FIELD_ID + " = ?",
new String[] {
String.valueOf(course.getId())
});
db.close();
}
public Course getCourse(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
COURSES_TABLE,
new String[] {
COURSES_KEY_FIELD_ID,
FIELD_ALPHA,
FIELD_NUMBER,
FIELD_TITLE
},
COURSES_KEY_FIELD_ID + "=?",
new String[] {
String.valueOf(id)
},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Course course = new Course(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3));
db.close();
return course;
}
//********** OFFERING TABLE OPERATIONS: ADD, GETALL, EDIT, DELETE
public void addOffering(int crn, int semesterCode, int courseId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(OFFERINGS_KEY_FIELD_ID, crn);
values.put(FIELD_SEMESTER_CODE, semesterCode);
values.put(FIELD_COURSE_ID, courseId);
db.insert(OFFERINGS_TABLE, null, values);
// CLOSE THE DATABASE CONNECTION
db.close();
}
public ArrayList < Offering > getAllOfferings() {
ArrayList < Offering > offeringsList = new ArrayList < > ();
SQLiteDatabase database = this.getReadableDatabase();
//Cursor cursor = database.rawQuery(queryList, null);
Cursor cursor = database.query(
OFFERINGS_TABLE,
new String[] {
OFFERINGS_KEY_FIELD_ID,
FIELD_SEMESTER_CODE,
FIELD_COURSE_ID
},
null,
null,
null, null, null, null);
//COLLECT EACH ROW IN THE TABLE
if (cursor.moveToFirst()) {
do {
Course course = getCourse(cursor.getInt(2));
//Instructor instructor = getInstructor(cursor.getInt(3));
Offering offering = new Offering(cursor.getInt(0),
cursor.getInt(1), course);
offeringsList.add(offering);
} while (cursor.moveToNext());
}
return offeringsList;
}
public void deleteOffering(Offering offering) {
SQLiteDatabase db = this.getWritableDatabase();
// DELETE THE TABLE ROW
db.delete(OFFERINGS_TABLE, OFFERINGS_KEY_FIELD_ID + " = ?",
new String[] {
String.valueOf(offering.getCRN())
});
db.close();
}
public void deleteAllOfferings() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(OFFERINGS_TABLE, null, null);
db.close();
}
public void updateOffering(Offering offering) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_SEMESTER_CODE, offering.getSemesterCode());
values.put(FIELD_COURSE_ID, offering.getCourse().getId());
db.update(OFFERINGS_TABLE, values, OFFERINGS_KEY_FIELD_ID + " = ?",
new String[] {
String.valueOf(offering.getCRN())
});
db.close();
}
public Offering getOffering(int crn) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
OFFERINGS_TABLE,
new String[] {
OFFERINGS_KEY_FIELD_ID,
FIELD_SEMESTER_CODE,
FIELD_COURSE_ID
},
OFFERINGS_KEY_FIELD_ID + "=?",
new String[] {
String.valueOf(crn)
},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Course course = getCourse(cursor.getInt(2));
//Instructor instructor = getInstructor(cursor.getInt(3));
Offering offering = new Offering(cursor.getInt(0),
cursor.getInt(1), course);
db.close();
return offering;
}
public Cursor getAllLabelsAsCursor() {
String[] columns = new String[] {
"rowid AS _id, *"
}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(COURSES_TABLE, columns, null, null, null, null, null);
}
public boolean importCoursesFromCSV(String csvFileName) {
AssetManager manager = mContext.getAssets();
InputStream inStream;
try {
inStream = manager.open(csvFileName);
} catch (IOException e) {
e.printStackTrace();
return false;
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 4) {
Log.d("OCC Course Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int id = Integer.parseInt(fields[0].trim());
String alpha = fields[1].trim();
String number = fields[2].trim();
String title = fields[3].trim();
addCourse(new Course(id, alpha, number, title));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean importOfferingsFromCSV(String csvFileName) {
AssetManager am = mContext.getAssets();
InputStream inStream = null;
try {
inStream = am.open(csvFileName);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream));
String line;
try {
while ((line = buffer.readLine()) != null) {
String[] fields = line.split(",");
if (fields.length != 4) {
Log.d("OCC Course Finder", "Skipping Bad CSV Row: " + Arrays.toString(fields));
continue;
}
int crn = Integer.parseInt(fields[0].trim());
int semesterCode = Integer.parseInt(fields[1].trim());
int courseId = Integer.parseInt(fields[2].trim());
addOffering(crn, semesterCode, courseId);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
main activity.
package com.bar.example.myapplication;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class CourseSearchActivity extends AppCompatActivity {
private DBHelper db;
private List < Course > allCoursesList;
private List < Offering > allOfferingsList;
private List < Offering > filteredOfferingsList;
public Button reset;
private EditText courseTitleEditText;
private Spinner ok;
private ListView offeringsListView;
// private selectedInstructorName selectedInstructorName;
private InstructorSpinnerAdapter instructorSpinnerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_search);
deleteDatabase(DBHelper.DATABASE_NAME);
db = new DBHelper(this);
db.importCoursesFromCSV("courses.csv");
db.importOfferingsFromCSV("offerings.csv");
Button reset = (Button) findViewById(R.id.resetButton);
allOfferingsList = db.getAllOfferings();
filteredOfferingsList = new ArrayList < > (allOfferingsList);
allCoursesList = db.getAllCourses();
courseTitleEditText = (EditText) findViewById(R.id.courseTitleEditText);
courseTitleEditText.addTextChangedListener(courseTitleTextWatcher);
ok = (Spinner) findViewById(R.id.spinner1);
// offeringListAdapter = new OfferingListAdapter(this, R.layout.offering_list_item, filteredOfferingsList);
// ok.setAdapter(offeringListAdapter);
instructorSpinnerAdapter = new InstructorSpinnerAdapter(this, R.layout.offering_list_item, filteredOfferingsList);
ArrayAdapter < String > instructorSpinnerAdapter = new ArrayAdapter < String >
(this, android.R.layout.simple_spinner_item, getAllCourse());
ok.setAdapter(instructorSpinnerAdapter);
ok.setOnItemSelectedListener(instructorSpinnerListener);
}
private String[] getAllCourse1() {
String[] instructorNames = new String[allCoursesList.size() + 1];
instructorNames[0] = "[Select Course]";
for (int i = 1; i < instructorNames.length; i++) {
instructorNames[i] = allCoursesList.get(i - 1).getTitle();
}
return instructorNames;
}
private ArrayList < String > getAllCourse() {
ArrayList < String > instructorNames = new ArrayList < > ();
instructorNames.add("[Select Course]");
for (int i = 0; i < allCoursesList.size(); i++) {
instructorNames.add(allCoursesList.get(i).getTitle());
}
return instructorNames;
}
public TextWatcher courseTitleTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String input = charSequence.toString().toLowerCase();
ArrayAdapter adapter = (ArrayAdapter) ok.getAdapter();
adapter.clear();
if (input.equals("")) {
adapter.addAll(getAllCourse());
} else {
Course course;
for (int j = 0; j < allCoursesList.size(); j++) {
// If the course title starts with the user input,
// add it to the listAdapter
course = allCoursesList.get(j);
if (course.getTitle().toLowerCase().startsWith(input)) {
adapter.add(course.getTitle());
}
}
}
adapter.notifyDataSetChanged();
if (adapter.getCount() != 0) ok.setSelection(0);
}
#Override
public void afterTextChanged(Editable editable) {
}
};
public AdapterView.OnItemSelectedListener instructorSpinnerListener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView << ? > adapterView, View view, int i, long l) {
String selectedInstructorName = adapterView.getItemAtPosition(i).toString();
if (selectedInstructorName.equals("[Select Instructor]")) {
instructorSpinnerAdapter.clear();
for (Offering offering: allOfferingsList)
instructorSpinnerAdapter.add(offering);
} else {
instructorSpinnerAdapter.clear();
}
}
#Override
public void onNothingSelected(AdapterView << ? > adapterView) {
adapterView.setSelection(0);
// Toast.makeText(getApplicationContext(), "Why?", Toast.LENGTH_SHORT).show();
}
};
}
Activity_course_search.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: id = "#+id/activity_course_search"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: orientation = "vertical"
android: paddingBottom = "#dimen/activity_vertical_margin"
android: paddingLeft = "#dimen/activity_horizontal_margin"
android: paddingRight = "#dimen/activity_horizontal_margin"
android: paddingTop = "#dimen/activity_vertical_margin"
tools: context = "com.bar.example.myapplication.CourseSearchActivity" >
<
LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >
<
TextView
android: text = "Filter By Instructor"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: id = "#+id/textView" /
>
<
Spinner
android: id = "#+id/instructorSpinner"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_weight = "1" / >
<
/LinearLayout>
<
LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >
<
TextView
android: text = "Filter By Course Title"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: id = "#+id/textView2" /
>
<
EditText
android: id = "#+id/courseTitleEditText"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: inputType = "textPersonName"
android: ems = "10" /
>
<
/LinearLayout>
<
LinearLayout
android: orientation = "horizontal"
android: layout_width = "match_parent"
android: layout_height = "wrap_content" >
<
Button
android: text = "#string/reset_button_text"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: id = "#+id/resetButton" /
>
<
/LinearLayout>
<
ListView
android: id = "#+id/offeringsListView"
android: layout_width = "match_parent"
android: layout_height = "18dp" >
<
/ListView>
<
Spinner
android: id = "#+id/spinner1"
android: layout_width = "341dp"
android: layout_height = "93dp"
android: layout_weight = "1" / >
<
/LinearLayout>
offering_list_item.xml
<< ? xml version = "1.0"
encoding = "utf-8" ? >
<
LinearLayout xmlns : android = "http://schemas.android.com/apk/res/android"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: id = "#+id/offeringListLinearLayout" >
<
LinearLayout
android: orientation = "vertical"
android: layout_width = "match_parent"
android: layout_height = "match_parent" >
<
TextView
android: text = "TextView"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: textSize = "20sp"
android: id = "#+id/offeringListFullNameTextView" / >
<
/LinearLayout>
<
/LinearLayout>
Main Screen 1 :
Requirement 1 : (Working Fine) spinner selection from database.
Requirement 2 : Working but need in another way . Spinner display from database based on edittext entry using textwacher. What i want is that if enter "Number A170 then my spinner should show "title" Java Programming 1 from database
Current screen shows
I want it in this way ...
revised onTextChanged code.
public TextWatcher courseTitleTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String input = charSequence.toString().toLowerCase();
ArrayAdapter adapter = (ArrayAdapter) ok.getAdapter();
adapter.clear();
if (input.equals("")) {
adapter.addAll(getAllCourse());
} else {
Course course;
for (int j = 0; j < CoursesList.size(); j++) {
// If the course title starts with the user input,
// add it to the listAdapter
// course = allCoursesList.get(j);
if (courseTitleEditText.getText().equals(CoursesList.get(j).get("number"))) {
//adapter.add(course.getTitle());
ok.setSelection(j);
}
}
}
// adapter.notifyDataSetChanged();
//if(adapter.getCount() != 0)
// ok.setSelection(i);
}
#Override
public void afterTextChanged(Editable editable) {
}
};
Try this. It should solve your issue.
Replace if (course.getTitle().toLowerCase().startsWith(input)) {
with if (course.getNumber().toLowerCase().startsWith(input)) {.
i think i figure what do you need
actully it's little simple
im try to work it with your code but not by modeling way like you
it will be by hashmap array
first we need to get the data from you sqlite by using this code
THIS in class DBHelper
import java.util.HashMap;
import java.util.Map;
this the import you need here
public ArrayList<Map<String, String>> getCourses()
{
ArrayList<Map<String, String>> array_list = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from " + COURSES_TABLE, null);
res.moveToFirst();
while(res.isAfterLast() == false){
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("id", res.getString(res.getColumnIndex(COURSES_KEY_FIELD_ID)));
datanum.put("alpha", res.getString(res.getColumnIndex(FIELD_ALPHA)));
datanum.put("number", res.getString(res.getColumnIndex(FIELD_NUMBER)));
datanum.put("title", res.getString(res.getColumnIndex(FIELD_TITLE)));
array_list.add(datanum);
res.moveToNext();
}
return array_list;
}
this code here will work perfect with you not need to edit i make it with your class
now you need to call this method in you class
THIS in class CourseSearchActivity
DBHelper DB;
ArrayList<Map<String, String>> CoursesList = new ArrayList<Map<String, String>>();
on create
DB = new DBHelper(this);
CoursesList= DB.getCourses();
now you have all in your CoursesList now you need to figure out which spinner position you wanna to select it
so
you going to loop on it
THIS in Textlistener
for(int i = 0 ; i < CoursesList.size() ; i++){
if(courseTitleEditText.getText().equals(CoursesList.get(i).get("number"))){//ex.A170
// you must to be filled your spinner from same courses db and here you gonna to set your selection by iteration
ok.setSelection(i);
}
}
maybe it's not the right thing to your code because i see you use modeling in your code and i use Hashmap but i think it's useful to see the same way in your modeling from this code
i didn't test it i wrote it direct so test and told me what happen
hope i help

Why getView not getting called? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have an adapter that extends simplecursoradapter. For some reason I can't seem to see, my getView is not even being called. I have a breakpoint inside getView and it never gets there and the list just shows up empty. Can anyone take a look thru and see what I've done wrong?
package com.example.ok1;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.app.ListActivity;
public class MainActivity extends Activity {
// Button btnCalendar;
//*******************************************8
String[] names = {"Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
"Костя", "Игорь", "Анна", "Денис", "Андрей"};
//Button buttonAddTask;
final String Tag="States";
final String Ten = "Ten";
TextView txtDataTaskToday;
String id_for_listtsk_today;
ListView lvMain_today;
String[] arr_date;
SharedPreferences sPref;
static Cursor c;
private ListView listView = null;
//public static String id_for_listtsk_today;
// static SQLiteDatabase db;
MySqlCursorAdapter adapter = null;
//***********************************************8
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// btnCalendar = (Button) findViewById(R.id.btnActTwo);
// btnCalendar.setOnClickListener(this);
//*********************************************
// переменные для query
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
//*********работа с БД****************
// создаем объект для данных
// txtDataTaskToday = (TextView) findViewById(R.id.txtDataTaskToday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
//final String b = id_for_listtsk_today;
// txtDataTaskToday.setText(id_for_listtsk_today.toString());
Log.d(Tag, "id_for_listtsk_today ="+id_for_listtsk_today );
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(this);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
columns = new String[] {"name"};
selection = "data_id = ?";
selectionArgs = new String[] {id_for_listtsk_today};
//c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
try {
c=dbHelper.getCursor();
} catch (SQLException sqle) {
Log.d(Tag, "неудача");
throw sqle;
}
String[] arr_date = logCursor(c);
//*********работа с БД****************
lvMain_today = (ListView) findViewById(R.id.list);
// lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//this.listView=getl
//listView = MainActivity.this.getlgetListView();
lvMain_today.setItemsCanFocus(false);
lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, arr_date);// R.layout.item, my_list_item
startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME };
Log.d(Tag, "трассировка" );
MainActivity.this.adapter = new MySqlCursorAdapter(
this, R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
//
lvMain_today.setAdapter(MainActivity.this.adapter);
// setListAdapter(MainActivity.this.adapter);
names = arr_date;
c.close();
db.close();
dbHelper.close();
lvMain_today.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
SparseBooleanArray chosen = ((ListView) parent).getCheckedItemPositions();
for (int i = 0; i < chosen.size(); i++) {
int key = chosen.keyAt(i);
if (chosen.get(key))
Log.d(Tag, "выделены ====="+names[key]);
Log.d(Tag, "itemClick: position = " + position + ", id = "
+ id);}
//****************nen пробная фигня**************
// String[] columns = null;
// String selection = null;
// String[] selectionArgs = null;
// String groupBy = null;
// String having = null;
// String orderBy = null;
// columns = new String[] {"name"};
// selection = "data_id = ?";
// selectionArgs = new String[] {id_for_listtsk_today};//id_for_listtsk_today
// Cursor c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
// String[] arr = logCursor(c);
//**************************************************
// String s=test();
}
});
// lvMain_today.setOnItemSelectedListener(new OnItemSelectedListener() {
// public void onItemSelected(AdapterView<?> parent, View view,
// int position, long id) {
// Log.d(Tag, "Было выделение позиции меню!!!!position = " + position + ", id = "
// + id);
// }
//
// public void onNothingSelected(AdapterView<?> parent) {
// Log.d(Tag, "itemSelect: nothing");
// }
// });
}
private String[] logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
String[] arr_date = new String[c.getCount()];//String[] arr_date = new String[] {};
Log.d(Tag,"мы в курсоре");
if (c!=null) {
if (c.moveToFirst()) {
// Log.d(Tag,"мы в курсоре1");
String str;
int i=-1;
do {
// Log.d(Tag,"мы в курсоре2");
str="";
i=i+1;
for (String cn: c.getColumnNames()) {
str = str.concat(c.getString(c.getColumnIndex(cn)));
}
Log.d(Tag, "++++"+str);
arr_date[i]=String.valueOf(str);
} while (c.moveToNext());
}
}
return arr_date;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "календарь");
menu.add(0, 2, 0, "Убрать выполненные");
menu.add(0, 3, 3, "Уйти");
// menu.add(1, 4, 1, "copy");
// menu.add(1, 5, 2, "paste");
// menu.add(1, 6, 4, "exit");
return super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.main, menu);
//return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
// Выведем в TextView информацию о нажатом пункте меню
// txtDataTaskToday.setText("Item Menu");
// txtDataTaskToday.setText(item.getGroupId());
//// txtDataTaskToday.setText("\r\n itemId: " + String.valueOf(item.getItemId()));
// txtDataTaskToday.setText("\r\n order: " + String.valueOf(item.getOrder()));
// txtDataTaskToday.setText("\r\n title: " + item.getTitle());
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, ToDoCalendarActivity.class);
startActivity(intent);
break;
case 2:
SparseBooleanArray sbArray = lvMain_today.getCheckedItemPositions();
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key))
Log.d(Tag, "выделены "+names[key]);
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString(Ten, "1");
ed.commit();
Log.d(Tag, "ставим константу для скрытия");
}
break;
case 3:
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(Ten, "");
Log.d(Tag, "ten= "+ savedText);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// switch (v.getId()) {
// case R.id.btnActTwo:
//
// Intent intent = new Intent(this, ToDoCalendarActivity.class);
// startActivity(intent);
// break;
// }
// }
}
MySqlCursorAdapter
package com.example.ok1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener {
final String Tag="States";
private Context context;
private DBHelper dbHelper;
private Cursor currentCursor;
public MySqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, DBHelper dbHelper) {
super(context, layout, c, from, to);
Log.d(Tag, "трассировка1" );
this.currentCursor = c;
this.context = context;
this.dbHelper = dbHelper;
Log.d(Tag, "MySqlCursorAdapter()");
Integer b = c.getCount();
Log.d(Tag, "b="+b);
}
public View getView(int pos, View inView, ViewGroup parent) {
Log.d(Tag, "getView() + posss=" + pos);
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.my_list_item, null);
}
this.currentCursor.moveToPosition(pos);
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
cBox.setTag(Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_ID))));
Log.d(Tag, "tag="+cBox.getTag().toString());
if (this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS)) != null
&& Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS))) != 0) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
cBox.setOnClickListener(this);
TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_NAME)));
return (v);
}
public void ClearSelections() {
Log.d(Tag, "ClearSelections()");
//this.dbHelper.clearSelections();
//this.currentCursor.requery();
}
#Override
public void onClick(View v) {
Log.d(Tag, "onClick");
CheckBox cBox = (CheckBox) v;
Integer _id = (Integer) cBox.getTag();
Log.d(Tag, "Integer _id="+_id.toString());
ContentValues values = new ContentValues();
values.put(" selected", cBox.isChecked() ? 1 : 0);
//this.dbHelper.dbSqlite.update(SqlHelper.TABLE_NAME, values, "_id=?",
// new String[] { Integer.toString(_id) });
}
}
DBHelper
package com.example.ok1;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
final String Tag="States";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATA = "data_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_STATUS = "status";
public static final String TABLE_NAME = "mytable";
public SQLiteDatabase dbSqlite;
public DBHelper(Context context) {
// конструктор суперкласса
super(context, "myDB", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(Tag, "--- onCreate database ---");
// создаем таблицу с полями
db.execSQL("create table mytable ("
+ "_id integer primary key autoincrement,"
+ "data_id text,"
+ "name text,"
+ "task text,"
+ "status integer"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getCursor() {
Log.d(Tag, "getCursor() получили курсор с базы");
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
// SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// queryBuilder.setTables(TABLE_NAME);
// String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
// COLUMN_DATA, COLUMN_STATUS };
// Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
// null, null, null, "title ASC");
// Log.d(Tag, "getCursor() получили курсор с базы конец");
final SQLiteDatabase db = this.getWritableDatabase();
columns = new String[] { COLUMN_ID, COLUMN_DATA, COLUMN_NAME, COLUMN_STATUS };
// selection = "data_id = ?";
// selectionArgs = new String[] {id_for_listtsk_today};
Cursor c = db.query("mytable", columns, null, null, null, null, null);
return c;
}
}
ActivityMain.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#81BEF7" android:scrollbars="vertical">
<TableLayout android:id="#+id/TableLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" >
<TableRow>
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</TableRow>
</TableLayout>
</LinearLayout>
my_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/bcheck"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:focusable="false">
</CheckBox>
<TextView
android:id="#+id/txtTitle"
android:layout_width="138dp"
android:layout_height="?android:attr/listPreferredItemHeight"
android:focusable="false"
android:gravity="left|center_vertical"
android:text="Test" >
</TextView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right|center_vertical"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:clickable="true" >
</ImageButton>
</LinearLayout>
</LinearLayout>
I removed
c.close();
db.close();
and now its working fine.

listview items disappearing

So.. my listview items are disappearing after they're scrolled off the screen. They're there, you scoll down, back up, and they're gone. After rotation they reappear, but I have no idea why this is happening.
package com.teslaprime.prirt;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.content.ContentValues;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ListView;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
public class TaskList extends Activity {
List<Task> tasks = new ArrayList<Task>();
TaskAdapter adapter = null;
SQLiteDatabase db = null;
public void populateList(){
adapter = new TaskAdapter();
adapter.clear();
Cursor cur = db.query("tasks",null,null,null,null,null,"timestamp");
cur.moveToFirst();
int anchor = 0;
while (cur.isAfterLast() == false) {
if (cur.getInt(cur.getColumnIndex("completed")) == 1) {
Task task = new Task(cur.getString(cur.getColumnIndex("name")),cur.getString(cur.getColumnIndex("type")));
task.id = cur.getInt(cur.getColumnIndex("id"));
task.completed = 1;
adapter.add(task);
anchor = anchor+1;
}
cur.moveToNext();
}
cur.moveToFirst();
while (cur.isAfterLast() == false) {
if (cur.getInt(cur.getColumnIndex("completed")) == 0) {
Task task = new Task(cur.getString(cur.getColumnIndex("name")),cur.getString(cur.getColumnIndex("type")));
task.id = cur.getInt(cur.getColumnIndex("id"));
adapter.add(task);
}
cur.moveToNext();
}
cur.close();
for (int i = tasks.size(); i <= 8; i++) {
adapter.add(new Task());
}
ListView list = (ListView) findViewById(R.id.tasks);
list.setAdapter(adapter);
list.setSelection(anchor);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent setupProcess = new Intent (TaskList.this, SetupWelcome.class);
boolean first = checkDatabase() ? true : false;
db = openOrCreateDatabase("priRT.db",
SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.setVersion(1);
db.setLockingEnabled(true);
db.execSQL("create table if not exists tasks ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "time integer,"
+ "completed integer,"
+ "timestamp integer,"
+ "spacer integer,"
+ "type text);");
db.execSQL("create table if not exists schedule ("
+ "id integer primary key autoincrement,"
+ "hours_free integer);");
if (first) { startActivityForResult(setupProcess,0); }
populateList();
Button add = (Button) findViewById(R.id.addTask);
add.setOnClickListener(onAdd);
}
public View.OnClickListener closeTaskListener = new View.OnClickListener(){
public void onClick(View v){
int pos = (Integer) (v.getTag());
Task task = adapter.getItem(pos);
ContentValues values = new ContentValues();
if (task.completed == 1){
values.put("completed", 0);
task.completed = 0;
} else {
values.put("completed", 1);
task.completed = 1;
}
Long time = new Date().getTime();
values.put("timestamp", time);
db.update("tasks", values, "id='"+task.id+"'", null);
populateList();
}
};
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(
"/data/data/com.teslaprime.prirt/databases/priRT.db", null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {}
return checkDB == null ? true : false;
}
private View.OnClickListener onAdd = new View.OnClickListener() {
public void onClick(View view) {
Intent addTask = new Intent (view.getContext(), TaskEntry.class);
startActivityForResult(addTask, 2);
}
};
protected void onActivityResult(int req, int res, Intent data) {
if (req == 0 && res == RESULT_OK) {
Intent setup = new Intent (TaskList.this, SetupWizard.class);
startActivityForResult(setup, 1);
}
if (req == 2 && res == RESULT_OK) {
Task task = new Task(data.getStringExtra("name"),data.getStringExtra("type"));
adapter.add(task);
ContentValues values = new ContentValues();
values.put("name", data.getStringExtra("name"));
values.put("type", data.getStringExtra("type"));
values.put("completed", 0);
values.put("spacer", 0);
db.insert("tasks", null, values);
Cursor cur = db.query("tasks", null, null, null, null, null, null);
cur.moveToLast();
task.id = cur.getInt(cur.getColumnIndex("id"));
cur.close();
populateList();
}
}
class TaskAdapter extends ArrayAdapter<Task> {
TaskAdapter() {super(TaskList.this,R.layout.task,tasks);}
private List<Task> taskList;
private Context context;
public View getView(int pos, View convertView, ViewGroup parent) {
View task = convertView;
if (convertView == null) {
LayoutInflater inflater = getLayoutInflater();
task = inflater.inflate(R.layout.task,null);
}
if (tasks.get(pos).spacer == 0) {
TextView taskName = (TextView) task.findViewById(R.id.name);
TextView taskType = (TextView) task.findViewById(R.id.type);
taskName.setText(tasks.get(pos).name);
taskType.setText(tasks.get(pos).type);
Task taskList = adapter.getItem(pos);
CheckBox closeTask = (CheckBox) task.findViewById(R.id.closeTask);
if (taskList.completed == 0) {
closeTask.setChecked(false);
} else {
closeTask.setChecked(true);
}
closeTask.setTag(pos);
closeTask.setOnClickListener(closeTaskListener);
} else {
CheckBox closeTask = (CheckBox) task.findViewById(R.id.closeTask);
task.setVisibility(View.GONE);
task.setFocusable(false);
task.setClickable(false);
}
return task;
}
}
}
It may be happening because of the background color of surface in which list appears. Try setting the background color to white in linerlayout and text view coolr black then scroll the through the list view again.

Categories

Resources