Android: How can I search data in sqlite database - android

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.

Related

database.sqlite.SQLiteException: near "=": syntax error (code 1 SQLITE_ERROR): , while compiling: DELETE FROM users = UserModel#dff4685;

I need your help. I want to delete data from my Database by actionModeCallbacks inside the RecyclerView.
remove a users from my recyclerview/database.
This is my logcat.
Process: com.andylab.recovermessages, PID: 24576
android.database.sqlite.SQLiteException: near "=": syntax error (code 1 SQLITE_ERROR): , while compiling: DELETE FROM users = com.andylab.recovermessages.models.UserModel#dff4685;
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:939)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:550)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1770)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1698)
at com.andylab.recovermessages.db.recentNumberDB.deleteItem(recentNumberDB.java:367)
at com.andylab.recovermessages.adapters.UsersAdapter$1.onActionItemClicked(UsersAdapter.java:70)
at androidx.appcompat.app.AppCompatDelegateImpl$ActionModeCallbackWrapperV9.onActionItemClicked(AppCompatDelegateImpl.java:2171)
at androidx.appcompat.view.StandaloneActionMode.onMenuItemSelected(StandaloneActionMode.java:141)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)
at androidx.appcompat.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
at androidx.appcompat.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
2020-05-10 02:55:30.109 24576-24576/com.andylab.recovermessages I/Process: Sending signal. PID: 24576 SIG: 9
This is my datadb.
private class datadb extends SQLiteOpenHelper {
private static final String CREATE_TABLE_ADDED_PACKAGES = "CREATE TABLE table_packages (ID INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT unique);";
static final String CREATE_TABLE_FILES = "CREATE TABLE files (_id INTEGER PRIMARY KEY AUTOINCREMENT, files TEXT, whole_time LONG);";
static final String CREATE_TABLE_MSG = "CREATE TABLE messeges (_id INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT, username TEXT, msg TEXT, small_time TEXT, whole_time LONG);";
private static final String CREATE_TEBLE_COOL = "CREATE TABLE cool_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, cool_text TEXT unique);";
private static final String CREATE_TEBLE_QUICK_REPLY = "CREATE TABLE quick_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, quick_reply TEXT);";
private static final String CREATE_TEBLE_REPEATER = "CREATE TABLE repeater_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, text_repeater TEXT);";
private static final String CREATE_TEBLE_UNSAVED = "CREATE TABLE num_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, nums TEXT unique);";
static final String CREATE_USER_WITH_ID = "CREATE TABLE users (_id INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT, username TEXT UNIQUE, read_unread boolean, whole_time DATETIME DEFAULT CURRENT_TIMESTAMP);";
private static final String ID = "_id";
private static final String NAME = "recover.db";
private static final int version = 1;
public void onUpgrade(SQLiteDatabase sQLiteDatabase, int i, int i2) {
}
public datadb(Context context) {
super(context, NAME, null, version);
}
public void onCreate(SQLiteDatabase sQLiteDatabase) {
sQLiteDatabase.execSQL(CREATE_TEBLE_UNSAVED);
sQLiteDatabase.execSQL(CREATE_TEBLE_QUICK_REPLY);
sQLiteDatabase.execSQL(CREATE_TEBLE_REPEATER);
sQLiteDatabase.execSQL(CREATE_TEBLE_COOL);
sQLiteDatabase.execSQL(CREATE_USER_WITH_ID);
sQLiteDatabase.execSQL(CREATE_TABLE_MSG);
sQLiteDatabase.execSQL(CREATE_TABLE_FILES);
sQLiteDatabase.execSQL(CREATE_TABLE_ADDED_PACKAGES);
}
}
public recentNumberDB(Context context) {
this.context = context;
}
public long addData(String str, String str2, String str3, String str4, String str5) {
Long l = null;
try {
addUser(str2, str, str5);
SQLiteDatabase writableDatabase = new datadb(this.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", str);
contentValues.put("small_time", str4);
contentValues.put("whole_time", str5);
contentValues.put(NotificationCompat.CATEGORY_MESSAGE, str3);
contentValues.put("package", str2);
l = writableDatabase.insert("messeges", null, contentValues);
writableDatabase.close();
} catch (Exception str6) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str6.toString());
Log.d("dblog", stringBuilder.toString());
}
return l;
}
public void addUser(String str, String str2, String str3) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
String str4 = str;
String str5 = str2;
String str6 = str3;
String str7 = "package";
String str8 = "read_unread";
String str9 = "whole_time";
String str10 = "username";
String str11 = "addedusrsnum";
Log.d(str11, "adding started");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("current time ");
stringBuilder.append(str6);
Log.d(str11, stringBuilder.toString());
try {
SQLiteDatabase writableDatabase = new datadb(view_deleted_messages_dbs_recentNumberDB.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(str10, str5);
contentValues.put(str9, str6);
contentValues.put(str8, Boolean.valueOf(false));
contentValues.put(str7, str4);
String str12 = "users";
if (writableDatabase.query("users", new String[]{str10, str7}, "username=? AND package=?", new String[]{str5, str4}, null, null, null).getCount() == 0) {
writableDatabase.insert(str12, null, contentValues);
Log.d(str11, "greater 0");
} else {
contentValues.clear();
contentValues.put(str9, str6);
contentValues.put(str8, Boolean.valueOf(false));
writableDatabase.update(str12, contentValues, "username=? AND package=?", new String[]{str5, str4});
Log.d(str11, "updates");
}
writableDatabase.close();
} catch (Exception e) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("error: ");
stringBuilder2.append(e.toString());
Log.d(str11, stringBuilder2.toString());
}
}
public List<HashMap> getUsers(String str) {
String str2 = "username";
String str3 = "read_unread";
List<HashMap> arrayList = new ArrayList();
try {
SQLiteDatabase readableDatabase = new datadb(this.context).getReadableDatabase();
SQLiteDatabase sQLiteDatabase = readableDatabase;
Cursor query = sQLiteDatabase.query("users", new String[]{str3, str2}, "package=?", new String[]{str}, null, null, "whole_time DESC");
while (query.moveToNext()) {
HashMap hashMap = new HashMap();
Log.d("readunr", query.getString(query.getColumnIndex(str3)));
hashMap.put("boolean", query.getString(query.getColumnIndex(str3)));
hashMap.put("string", query.getString(query.getColumnIndex(str2)));
arrayList.add(hashMap);
}
query.close();
readableDatabase.close();
} catch (Exception str4) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str4.toString());
Log.d("dblog", stringBuilder.toString());
}
return arrayList;
}
public List<DataModel> getMsg(String str, String str2) {
String str3 = "small_time";
String str4 = NotificationCompat.CATEGORY_MESSAGE;
List<DataModel> arrayList = new ArrayList();
try {
SQLiteDatabase writableDatabase = new datadb(this.context).getWritableDatabase();
SQLiteDatabase sQLiteDatabase = writableDatabase;
Cursor query = sQLiteDatabase.query("messeges", new String[]{str4, str3}, "username=? AND package=?", new String[]{str, str2}, null, null, null);
while (query.moveToNext()) {
arrayList.add(new DataModel(query.getString(query.getColumnIndex(str4)), query.getString(query.getColumnIndex(str3))));
}
query.close();
writableDatabase.close();
} catch (Exception str5) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str5.toString());
Log.d("dblog", stringBuilder.toString());
}
return arrayList;
}
public boolean isPresent(String str, String str2, String str3) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
String str4 = str;
String str5 = NotificationCompat.CATEGORY_MESSAGE;
String str6 = "dblog";
boolean z = false;
try {
SQLiteDatabase readableDatabase = new datadb(view_deleted_messages_dbs_recentNumberDB.context).getReadableDatabase();
SQLiteDatabase sQLiteDatabase = readableDatabase;
Cursor query = sQLiteDatabase.query("messeges", new String[]{str5}, "username=? AND package=?", new String[]{str4, str3}, null, null, "_id DESC", "1");
if (query.getCount() > 0) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("isPresentusername=");
stringBuilder.append(str4);
stringBuilder.append("Size=");
stringBuilder.append(String.valueOf(query.getCount()));
Log.d(str6, stringBuilder.toString());
while (query.moveToNext()) {
str4 = query.getString(query.getColumnIndex(str5));
stringBuilder = new StringBuilder();
stringBuilder.append("ispresend greater 0. chat = ");
stringBuilder.append(str4);
Log.d(str6, stringBuilder.toString());
z = str4.equals(str2);
}
} else {
Log.d(str6, "ispresent is 0");
}
query.close();
readableDatabase.close();
} catch (Exception e) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("error: ");
stringBuilder2.append(e.toString());
Log.d(str6, stringBuilder2.toString());
}
return z;
}
public List<UserModel> getHomeList(String s) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
ArrayList<UserModel> list = new ArrayList<UserModel>();
try {
List<HashMap> users = this.getUsers(s);
SQLiteDatabase readableDatabase = new recentNumberDB.datadb(view_deleted_messages_dbs_recentNumberDB.context).getReadableDatabase();
for (int i = 0; i < users.size(); ++i) {
Cursor query = readableDatabase.query("messeges", new String[] { "msg", "small_time" }, "username=? AND package=?", new String[] { users.get(i).get("string").toString(), s }, (String)null, (String)null, "_id DESC", "1");
if (query != null) {
StringBuilder sb = new StringBuilder();
sb.append("users lenght ");
sb.append(users.size());
Log.d("emptylog", sb.toString());
StringBuilder sb2 = new StringBuilder();
sb2.append("cursor lenght ");
sb2.append(String.valueOf(query.getCount()));
Log.d("emptylog", sb2.toString());
if (query.getCount() == 0) {
list.add(new UserModel(users.get(i).get("string").toString(), "no recent msg", "", 1));
}
else {
while (true) {
int moveToNext = query.moveToNext() ? 1 : 0;
if (moveToNext == 0) {
break;
}
list.add(new UserModel(users.get(i).get("string").toString(), query.getString(0), query.getString(moveToNext), Integer.parseInt(users.get(i).get("boolean").toString())));
Log.d("emptylog", query.getString(0));
}
}
query.close();
}
else {
Log.d("emptylog", "cursor null");
}
}
readableDatabase.close();
return list;
}
catch (Exception ex) {
return list;
}
}
public void addPackages(String s) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("package", s);
writableDatabase.insert("table_packages", (String)null, contentValues);
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public ArrayList<String> getAllPackages() {
String[] array = { "com.whatsapp", "com.whatsapp.w4b", "com.gbwhatsapp", "com.facebook.lite", "com.facebook.orca", "com.facebook.mlite", "org.telegram.messenger" };
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
try {
Cursor query = new recentNumberDB.datadb(this.context).getReadableDatabase().query("table_packages", new String[] { "package" }, (String)null, (String[])null, (String)null, (String)null, (String)null);
boolean moveToNext;
while (true) {
moveToNext = query.moveToNext();
if (!moveToNext) {
break;
}
list.add(query.getString(0));
}
query.close();
int n = moveToNext ? 1 : 0;
int i;
while (true) {
i = (moveToNext ? 1 : 0);
if (n >= array.length) {
break;
}
if (list.contains(array[n])) {
list2.add(array[n]);
}
++n;
}
while (i < list.size()) {
if (!list2.contains(list.get(i))) {
list2.add(list.get(i));
}
++i;
}
return list2;
}
catch (Exception ex) {
return list2;
}
}
public void removePackageAndMsg(ArrayList<String> list) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
Iterator<String> iterator = list.iterator();
while (true) {
int hasNext = iterator.hasNext() ? 1 : 0;
if (hasNext == 0) {
break;
}
String s = iterator.next();
String[] array = new String[hasNext];
array[0] = s;
writableDatabase.delete("table_packages", "package=?", array);
String[] array2 = new String[hasNext];
array2[0] = s;
writableDatabase.delete("users", "package=?", array2);
String[] array3 = new String[hasNext];
array3[0] = s;
writableDatabase.delete("messeges", "package=?", array3);
}
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void remove(ArrayList<String> list) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
Iterator<String> iterator = list.iterator();
while (true) {
int hasNext = iterator.hasNext() ? 1 : 0;
if (hasNext == 0) {
break;
}
String s = iterator.next();
String[] array = new String[hasNext];
array[0] = s;
/// writableDatabase.delete("table_packages", "package=?", array);
String[] array2 = new String[hasNext];
array2[0] = s;
writableDatabase.delete("users", "package=?", array2);
String[] array3 = new String[hasNext];
array3[0] = s;
writableDatabase.delete("messeges", "package=?", array3);
}
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void deleteItem(UserModel position){
SQLiteDatabase db = new recentNumberDB.datadb(this.context).getWritableDatabase();
db.execSQL("DELETE FROM " + "users" + "package=?" + "username" + " = " + position + ";");
db.execSQL("DELETE FROM " + "messeges" + "package=?" + "small_time" + " = " + position + ";");
db.close();
}
}
And this is my adapter
`public class UsersAdapter extends RecyclerView.Adapter <UsersAdapter.RecyclerViewHolder> {
private Context context;
private ArrayList <UserModel> list;
private ArrayList<UserModel> selectedItems = new ArrayList<UserModel>();
private String pack;
private SparseBooleanArray mSelectedItemsIds;
LayoutInflater inflater;
private boolean multiSelect = false;
private ActionMode.Callback actionModeCallbacks = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
multiSelect = true;
menu.add("Delete");
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
for (UserModel intItem : selectedItems) {
list.remove(intItem);
notifyDataSetChanged ();
recentNumberDB recentNumberDB = new recentNumberDB(context);
recentNumberDB.deleteItem ( intItem );
}
switch (item.getItemId()) {
case R.id.action_delete:
return true;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
multiSelect = false;
selectedItems.clear();
notifyDataSetChanged();
}
};
public void itemRemoved(int position) {
recentNumberDB recentNumberDB = new recentNumberDB(context);
list.remove(position);
notifyItemRemoved(position);
recentNumberDB.deleteItem(position);
}
public UsersAdapter(Context context, ArrayList <UserModel> list, String str) {
this.context = context;
this.list = (ArrayList <UserModel>) list;
this.pack = str;
mSelectedItemsIds = new SparseBooleanArray();
this.inflater = LayoutInflater.from(context);
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder{
ConstraintLayout listt;
TextView msg;
TextView name;
TextView readunread;
TextView time;
public ImageButton btn_delete;
public CheckBox chkSelected;
public RecyclerViewHolder(#NonNull View itemView) {
super ( itemView );
name = (TextView) itemView.findViewById(R.id.name);
msg = (TextView) itemView.findViewById(R.id.msg);
time = (TextView) itemView.findViewById(R.id.time);
listt = (ConstraintLayout) itemView.findViewById(R.id.list);
readunread = (TextView) itemView.findViewById(R.id.unread);
btn_delete = (ImageButton) itemView.findViewById(R.id.btn_delete_unit);
chkSelected = (CheckBox) itemView.findViewById(R.id.chk_selected);
}
public void selectItem(UserModel list) {
if (multiSelect) {
if (selectedItems.contains(list)) {
selectedItems.remove(list);
itemView.setBackgroundColor(Color.WHITE);
} else {
selectedItems.add(list);
itemView.setBackgroundColor(Color.LTGRAY);
}
}
}
public void update(final UserModel value) {
// textView.setText(value + "");
if (selectedItems.contains(value)) {
itemView.setBackgroundColor(Color.LTGRAY);
} else {
itemView.setBackgroundColor( Color.WHITE);
}
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
((AppCompatActivity)view.getContext()).startSupportActionMode(actionModeCallbacks );
selectItem(value);
return true;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectItem(value);
}
});
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.users_home, parent, false);
RecyclerViewHolder viewHolder = new RecyclerViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
UserModel userModel = (UserModel) list.get(position);
holder.name.setText(userModel.getName());
holder.msg.setText(userModel.getLastmsg());
holder.time.setText(userModel.getTime());
holder.listt.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (adCount%4==0){
/// AdmobHelper.showInterstitialAd(context, AdmobHelper.ADSHOWN);
}
adCount++;
Intent intent = new Intent(context, MessegesActivity.class);
intent.putExtra("name", userModel.getName());
intent.putExtra("pack", pack);
context.startActivity(intent);
}
});
holder.update(list.get(position));
}
#Override
public int getItemCount() {
return list.size();
}
}`

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) {
}
}
});

Null pointer exception while uploading contacts to server

Here i am fetching the name,email,phone number from the mobile and trying to upload to server..Here if the contacts contains name,email and phone number the values will be inserted successfully..but if any of the field is empty it is throwing NULL pointer exception.How to avoid this one..i mean if the contact does not contain email it should atleast send name and phone number.
here is my code.
public class DisplayContact1 extends Activity {
private static String TAG = WorkDetails1.class.getSimpleName();
Button select;
private String vault;
List<AddressBookContact> list;
public static final String kvault = "vault_no";
public static final String kname = "name";
public static final String kphone = "phone";
public static final String kemail = "email";
public static final String kcontacts = "contacts";
public static final String SHARED_PREF_NAME = "myloginapp";
public static final String UPLOAD_URL = "http://oursite.com/contacts_1.php";
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
Cursor cursor;
LongSparseArray<AddressBookContact> array;
long start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.display);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
getAllContacts(this.getContentResolver());
}
public void getAllContacts(ContentResolver cr) {
int result = ContextCompat.checkSelfPermission(DisplayContact1.this, Manifest.permission.READ_CONTACTS);
if (result == PackageManager.PERMISSION_GRANTED){
//fetches contacts from the phone contact list and displays in ascending order
list = new LinkedList<AddressBookContact>();
array = new LongSparseArray<AddressBookContact>();
start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.Data.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
contactsdisplay();
} else {
requestForLocationPermission();
}
}
private void requestForLocationPermission()
{
if (ActivityCompat.shouldShowRequestPermissionRationale(DisplayContact1.this, Manifest.permission.READ_CONTACTS))
{
}
else {
ActivityCompat.requestPermissions(DisplayContact1.this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getAllContacts(DisplayContact1.this.getContentResolver());
contactsdisplay();
}
break;
}
}
public void contactsdisplay() {
//Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
ListView lv= (ListView) findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
uploadImage();
}
});
}
public void uploadImage(){
SharedPreferences sharedPreferences = getSharedPreferences(DisplayContact.SHARED_PREF_NAME, MODE_PRIVATE);
final String vault_no = vault;
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DisplayContact1.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("Successfully Saved")){
//Intent intent = new Intent(CollegeDetails.this,Work.class);
Toast.makeText(DisplayContact1.this, s, Toast.LENGTH_SHORT).show();
// startActivity(intent);
}else{
Toast.makeText(DisplayContact1.this,s,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
//RegisterUserClass rh = new RegisterUserClass();
HashMap<String,String> param = new HashMap<String,String>();
JSONArray contacts = new JSONArray();
int i = 1;
for (AddressBookContact addressBookContact : list) {
try {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
JSONObject contact = new JSONObject();
contact.put(kname, addressBookContact.name.toString());
contact.put(kvault, vault_no);
contact.put(kphone, addressBookContact.phone.toString());
if(addressBookContact.email.toString()!=null)
contact.put(kemail, addressBookContact.email.toString());
contacts.put(contact);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
param.put(kcontacts, contacts.toString());
System.out.println("param value.." + i++ +":"+ contacts.toString());
}
return rh.sendPostRequest(UPLOAD_URL, param);
}
}
UploadImage u = new UploadImage();
u.execute();
}
}
here is the AddressBookContact.class
public class AddressBookContact {
private long id;
private Resources res;
String name;
LongSparseArray<String> email;
LongSparseArray<String> phone;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
#Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append(name);
} else {
builder.append("name: ").append(name);
}
if (phone != null) {
builder.append("\nphone: ");
for (int i = 0; i < phone.size(); i++) {
int type = (int) phone.keyAt(i);
builder.append(phone.valueAt(i));
if (i + 1 < phone.size()) {
builder.append(", ");
}
}
}
if (email != null) {
builder.append("\nemail: ");
for (int i = 0; i < email.size(); i++) {
int type = (int) email.keyAt(i);
builder.append(email.valueAt(i));
if (i + 1 < email.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (email == null) {
email = new LongSparseArray<String>();
}
email.put(type, address);
}
public void addPhone(int type, String number) {
if (phone == null) {
phone = new LongSparseArray<String>();
}
phone.put(type, number);
}
}
if email field is empty, i am getting null pointer exception at this line..
contact.put(kemail, addressBookContact.email.toString());..so i have added if loop to check the null condition..but then also i am getting exception.
Here
if (addressBookContact.email.toString() != null)
you try to get String from 'email' variable that is null.
Correct comparing is:
if (addressBookContact.email != null)
Add two conditions as below your string might not be null but can be
empty ""
if(addressBookContact.email.toString() != null && !addressBookContact.email.toString().equalsIgnoreCase(""))
contact.put(kemail, addressBookContact.email.toString());
Use TextUtils.
if(!TextUtils.isEmpty(addressBookContact.email.toString())){
contact.put(kemail, addressBookContact.email.toString());
}
And if kemail is compulsory field then in else condition just pass "" empty value.

Error in displaying data in custom listView while scrolling

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();

How to retrieve one or more phone numbers of one contact from android phone?

I want to retrieve multiple numbers from one contacts which is already saved to phone.
So how to read numbers of one contact programmatically in android?
I have created my own custom class for doing this , it may help you :
package com.android.addressbook.result;
import java.util.HashMap;
import android.graphics.Bitmap;
public class Contact {
String id = "";
String displayName = "";
String dateOfBirth = "";
String dateOfAnniversary = "";
String nickName = "";
String note = "";
Bitmap image = null;
HashMap<Integer, String> emails;
HashMap<Integer, String> phones;
HashMap<Integer, Address> addresses;
HashMap<Integer, Organization> organizations;
HashMap<Integer, String> im;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDateOfAnniversary() {
return dateOfAnniversary;
}
public void setDateOfAnniversary(String dateOfAnniversary) {
this.dateOfAnniversary = dateOfAnniversary;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public HashMap<Integer, String> getEmails() {
return emails;
}
public void setEmails(HashMap<Integer, String> emails) {
this.emails = emails;
}
public HashMap<Integer, String> getPhones() {
return phones;
}
public void setPhones(HashMap<Integer, String> phones) {
this.phones = phones;
}
public HashMap<Integer, Address> getAddresses() {
return addresses;
}
public void setAddresses(HashMap<Integer, Address> addresses) {
this.addresses = addresses;
}
public HashMap<Integer, Organization> getOrganizations() {
return organizations;
}
public void setOrganizations(HashMap<Integer, Organization> organizations) {
this.organizations = organizations;
}
public HashMap<Integer, String> getIm() {
return im;
}
public void setIm(HashMap<Integer, String> im) {
this.im = im;
}
/******************************************************************************************/
static class Address {
private String postBox = "";
private String street = "";
private String city = "";
private String state = "";
private String postalCode = "";
private String country = "";
private String neighborhood = "";
public String getPostBox() {
return postBox;
}
public void setPostBox(String postBox) {
this.postBox = postBox;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getNeighborhood() {
return neighborhood;
}
public void setNeighborhood(String neighborhood) {
this.neighborhood = neighborhood;
}
#Override
public String toString() {
return "Address [postBox=" + postBox + "\n street=" + street
+ "\n city=" + city + "\n state=" + state + "\n postalCode="
+ postalCode + "\n country=" + country + "\n neighborhood="
+ neighborhood + "]";
}
}
/**********************************/
static class Organization {
private String company = "";
private String jobTitle = "";
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
#Override
public String toString() {
return "Organization [company=" + company + "\n jobTitle="
+ jobTitle + "]";
}
}
/**********************************/
public static class Email_TYPE {
// Email Type
public static final int HOME = 1;
public static final int WORK = 2;
public static final int OTHER = 3;
public static final int MOBILE = 4;
}
/**********************************/
public static class PHONE_TYPE {
// / Phone Type
public static final int HOME = 1;
public static final int MOBILE = 2;
public static final int WORK = 3;
public static final int FAX_WORK = 4;
public static final int FAX_HOME = 5;
public static final int PAGER = 6;
public static final int OTHER = 7;
}
/**********************************/
public static class ADDRESS_TYPE {
// / Address Type
public static final int HOME = 1;
public static final int WORK = 2;
public static final int OTHER = 3;
}
/**********************************/
public static class ORGANIZATION_TYPE {
// / Organization Type
public static final int WORK = 2;
public static final int OTHER = 3;
}
/**********************************/
public static class IM_TYPE {
public static final int CUSTOM = -1;
public static final int AIM = 0;
public static final int MSN = 1;
public static final int YAHOO = 2;
public static final int SKYPE = 3;
public static final int QQ = 4;
public static final int GOOGLE_TALK = 5;
public static final int ICQ = 6;
public static final int JABBER = 7;
public static final int NETMEETING = 8;
}
#Override
public String toString() {
return "Contact [id=" + id + "\n displayName=" + displayName
+ "\n dateOfBirth=" + dateOfBirth + "\n dateOfAnniversary="
+ dateOfAnniversary + "\n nickName=" + nickName + "\n note="
+ note + "\n image=" + image + "\n emails=" + emails
+ "\n phones=" + phones + "\n addresses=" + addresses
+ "\n organizations=" + organizations + "\n im=" + im + "]";
}
}
PhoneContact.java
package com.android.addressbook.result;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import com.android.addressbook.result.Contact.Address;
import com.android.addressbook.result.Contact.Organization;
public class PhoneContact {
ContentResolver cr;
List<Contact> contactList;
Context context;
public PhoneContact(Context context) {
this.context = context;
cr = context.getContentResolver();
contactList = new ArrayList<Contact>();
readContacts();
}
public void readContacts() {
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Contact contact = new Contact();
// Get contact id (id)
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
contact.setId(id);
// Get contact name (displayName)
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contact.setDisplayName(displayName);
// Get BirthDay (dateOfBirth)
Uri URI_DOB = ContactsContract.Data.CONTENT_URI;
String SELECTION_DOB = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE
+ "="
+ ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] SELECTION_ARRAY_DOB = new String[] {
id,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor currDOB = cr.query(URI_DOB, null, SELECTION_DOB,SELECTION_ARRAY_DOB, null);
int indexDob = currDOB.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
if (currDOB.moveToNext()) {
String dobStr = currDOB.getString(indexDob);
contact.setDateOfBirth(dobStr);
}
currDOB.close();
// Get Anniversary (dateOfAnniversary)
Uri URI_DOA = ContactsContract.Data.CONTENT_URI;
String SELECTION_DOA = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE
+ "="
+ ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY;
String[] SELECTION_ARRAY_DOA = new String[] {
id,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor currDOA = cr.query(URI_DOA, null, SELECTION_DOA,SELECTION_ARRAY_DOA, null);
int indexDoa = currDOA.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
if (currDOA.moveToNext()) {
String doaStr = currDOA.getString(indexDoa);
contact.setDateOfAnniversary(doaStr);
}
currDOA.close();
// Get Nick Nmae(nickName)
Uri URI_NICK_NAME = ContactsContract.Data.CONTENT_URI;
String SELECTION_NICK_NAME = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_NICK_NAME = new String[] {
id,
ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE };
Cursor currNickName = cr.query(URI_NICK_NAME, null,
SELECTION_NICK_NAME, SELECTION_ARRAY_NICK_NAME,
null);
int indexNickName = currNickName.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
if (currNickName.moveToNext()) {
String nickNameStr = currNickName
.getString(indexNickName);
contact.setNickName(nickNameStr);
}
currNickName.close();
// GetNote(note)
Uri URI_NOTE = ContactsContract.Data.CONTENT_URI;
String SELECTION_NOTE = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_NOTE = new String[] {
id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
Cursor currNote = cr.query(URI_NOTE, null, SELECTION_NOTE,SELECTION_ARRAY_NOTE, null);
int indexNote = currNote.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
if (currNote.moveToNext()) {
String noteStr = currNote.getString(indexNote);
contact.setNote(noteStr);
}
currNote.close();
// Get User Image (image)
Uri URI_PHOTO = ContactsContract.Data.CONTENT_URI;
String SELECTION_PHOTO = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_PHOTO = new String[] {
id,
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE };
Cursor currPhoto = cr.query(URI_PHOTO, null,SELECTION_PHOTO, SELECTION_ARRAY_PHOTO, null);
int indexPhoto = currPhoto.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO);
while (currPhoto.moveToNext()) {
byte[] photoByte = currPhoto.getBlob(indexPhoto);
if (photoByte != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = context.getCacheDir();
// Temporary file to store the contact image
// File tmpFile = new File(cacheDirectory.getPath()
// + "/image_"+id+".png");
File tmpFile = new File(cacheDirectory.getPath()+ "/image_.png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG, 100,fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// String photoPath = tmpFile.getPath();
contact.setImage(bitmap);
}
}
currPhoto.close();
// Get Email and Type.... (<HashMap<Integer, String> emails)
Uri URI_EMAIL = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String SELECTION_EMAIL = ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = ?";
String[] SELECTION_ARRAY_EMAIL = new String[] { id };
Cursor emailCur = cr.query(URI_EMAIL, null,SELECTION_EMAIL, SELECTION_ARRAY_EMAIL, null);
int indexEmail = emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
int indexEmailType = emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE);
if (emailCur.getCount() > 0) {
HashMap<Integer, String> emailMap = new HashMap<Integer, String>();
while (emailCur.moveToNext()) {
// This would allow you get several email addresses,
// if the email addresses were stored in an array
String emailStr = emailCur.getString(indexEmail);
String emailTypeStr = emailCur.getString(indexEmailType);
emailMap.put(Integer.parseInt(emailTypeStr),emailStr);
}
contact.setEmails(emailMap);
}
emailCur.close();
// Get Phone Number....(HashMap<Integer, String>phones)
Uri URI_PHONE = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String SELECTION_PHONE = ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?";
String[] SELECTION_ARRAY_PHONE = new String[] { id };
Cursor currPhone = cr.query(URI_PHONE, null,SELECTION_PHONE, SELECTION_ARRAY_PHONE, null);
int indexPhoneNo = currPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int indexPhoneType = currPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
if (currPhone.getCount() > 0) {
HashMap<Integer, String> phoneMap = new HashMap<Integer, String>();
while (currPhone.moveToNext()) {
String phoneNoStr = currPhone.getString(indexPhoneNo);
String phoneTypeStr = currPhone.getString(indexPhoneType);
phoneMap.put(Integer.parseInt(phoneTypeStr),phoneNoStr);
}
contact.setPhones(phoneMap);
}
currPhone.close();
// Get Postal Address....(HashMap<Integer, Address> addresses)
Uri URI_ADDRESS = ContactsContract.Data.CONTENT_URI;
String SELECTION_ADDRESS = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_ADDRESS = new String[] {
id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
Cursor currAddr = cr.query(URI_ADDRESS, null,SELECTION_ADDRESS, SELECTION_ARRAY_ADDRESS, null);
int indexAddType = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE);
int indexStreet = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET);
int indexPOBox = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX);
int indexNeighbor = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD);
int indexCity = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY);
int indexRegion = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION);
int indexPostCode = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
int indexCountry = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
if (currAddr.getCount() > 0) {
HashMap<Integer, Address> addressMap = new HashMap<Integer, Contact.Address>();
while (currAddr.moveToNext()) {
Contact.Address address = new Contact.Address();
String typeStr = currAddr.getString(indexAddType);
address.setStreet(currAddr.getString(indexStreet));
address.setNeighborhood(currAddr.getString(indexNeighbor));
address.setPostalCode(currAddr.getString(indexPostCode));
address.setPostBox(currAddr.getString(indexPOBox));
address.setCity(currAddr.getString(indexCity));
address.setState(currAddr.getString(indexRegion));
address.setCountry(currAddr.getString(indexCountry));
addressMap.put(Integer.parseInt(typeStr), address);
}
contact.setAddresses(addressMap);
}
currAddr.close();
// Get Organization (HashMap<Integer, Organization> organizations)
Uri URI_ORGNIZATION = ContactsContract.Data.CONTENT_URI;
String SELECTION_ORGNIZATION = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_ORGNIZATION = new String[] {
id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
Cursor currOrg = cr.query(URI_ORGNIZATION, null,
SELECTION_ORGNIZATION, SELECTION_ARRAY_ORGNIZATION,
null);
int indexOrgType = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE);
int indexOrgName = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA);
int indexOrgTitle = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE);
if (currOrg.getCount() > 0) {
HashMap<Integer, Organization> orgMap = new HashMap<Integer, Contact.Organization>();
while (currOrg.moveToNext()) {
Contact.Organization organization = new Organization();
String orgTypeStr = currOrg.getString(indexOrgType);
organization.setCompany(currOrg.getString(indexOrgName));
organization.setJobTitle(currOrg.getString(indexOrgTitle));
orgMap.put(Integer.parseInt(orgTypeStr),organization);
}
contact.setOrganizations(orgMap);
}
currOrg.close();
// Get Instant Messenger..... (HashMap<Integer, String> im)
Uri URI_IM = ContactsContract.Data.CONTENT_URI;
String SELECTION_IM = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_IM = new String[] {
id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
Cursor currIM = cr.query(URI_IM, null, SELECTION_IM,SELECTION_ARRAY_IM, null);
int indexName = currIM
.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA);
int indexType = currIM
.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL);
if (currIM.getCount() > 0) {
HashMap<Integer, String> imMap = new HashMap<Integer, String>();
while (currIM.moveToNext()) {
String imNameStr = currIM.getString(indexName);
String imTypeStr = currIM.getString(indexType);
imMap.put(Integer.parseInt(imTypeStr), imNameStr);
}
contact.setIm(imMap);
}
currIM.close();
/*****************************************/
contactList.add(contact);
}
}
}
cur.close();
}
public List<Contact> getAllContacts() {
return contactList;
}
}
and finally use this in your activity :
PhoneContact pCon = new PhoneContact(context);
List<Contact> conList = pCon.getAllContacts();
HashMap<Integer, String> phones = conList.get(0).getPhones();
String home = phones.get(Contact.PHONE_TYPE.HOME);
here is the tutorial. i think it may help you. check once
Working With Android Contacts
Hope this Snippet can help you out
String id , name;
ContentResolver cr = getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, sortOrder);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString( cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.i(tag, "Id is "+ id+"\t Name is"+name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0){
Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
// this second loop will retrieve all the contact numbers for a paricular contact id
while (pCur.moveToNext()) {
// Do something with phones
int phNumber = pCur.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
String phn = pCur.getString(phNumber);
Log.i("phn number", phn);
}
pCur.close();
}
}
}

Categories

Resources