NPE with custom adapter - java

I am making a custom adapter for list view and got NPE. I have already read other questions but none of them.
Here is the logcat
07-04 06:54:58.036: E/AndroidRuntime(1340): FATAL EXCEPTION: main
07-04 06:54:58.036: E/AndroidRuntime(1340): java.lang.NullPointerException
07-04 06:54:58.036: E/AndroidRuntime(1340): at com.example.amirkh.MainActivity$FastFoodAdapter.getView(MainActivity.java:166)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.AbsListView.obtainView(AbsListView.java:2159)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.ListView.measureHeightOfChildren(ListView.java:1246)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.ListView.onMeasure(ListView.java:1158)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.view.View.measure(View.java:15518)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
07-04 06:54:58.036: E/AndroidRuntime(1340): at android.widget.TableRow.measureChildBeforeLayout(TableRow.java:247)
the code works this way. there is a databasehandler that organize database, a fastfood class and main class. in main class the user enteres a fastfood name and it goes to data base. when user clicks on the"show data" tab whole data should be shown.
here is the main class:
package com.example.amirkh;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import android.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.ActionProvider;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem.OnActionExpandListener;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends TabActivity {
private TabHost myTabHost;
private FastFoodAdapter<String> adpter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTabHost = getTabHost();
TabHost.TabSpec spec;
// Adding First Tab
spec = myTabHost.newTabSpec("first");
spec.setContent(R.id.inputtab);
spec.setIndicator("Input data");
myTabHost.addTab(spec);
// Adding Second Tab
spec = myTabHost.newTabSpec("second");
spec.setContent(R.id.listView1);
spec.setIndicator("Show data");
myTabHost.addTab(spec);
myTabHost.setCurrentTab(0);
// final List<FastFood> fflist = new ArrayList<FastFood>();
final EditText etname = (EditText) findViewById(R.id.etname);
final EditText etaddress = (EditText) findViewById(R.id.etaddress);
final ListView lv = (ListView) findViewById(R.id.listView1);
final DataBaseHandeler dbh = new DataBaseHandeler(MainActivity.this);
final RadioGroup radiogroup = (RadioGroup) findViewById(R.id.radioGroup1);
final FastFood fastfood = new FastFood();
final RadioButton rbsit = (RadioButton) findViewById(R.id.rbsit);
final RadioButton rbdeli = (RadioButton) findViewById(R.id.rbdeliv);
final RadioButton rbtake = (RadioButton) findViewById(R.id.rbtake);
refreshComponents();
Button save = (Button) findViewById(R.id.btnsave);
Button remove = (Button) findViewById(R.id.btnremove);
// Create context menu
registerForContextMenu(lv);
// end of context menu
// start of save button
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
FastFood ffastfood = new FastFood("", "", "");
ffastfood.setName(etname.getText().toString());
ffastfood.setAddress(etaddress.getText().toString());
etname.setText("");
etaddress.setText("");
if (rbsit.isChecked()) {
ffastfood.setFlag("1");
} else if (rbtake.isChecked()) {
ffastfood.setFlag("2");
} else if (rbdeli.isChecked()) {
ffastfood.setFlag("3");
}
Toast toast = Toast.makeText(MainActivity.this,
"Fastfood is saved.", 2000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
dbh.addFastFood(ffastfood);
refreshComponents();
}
}); // end of save
// remove
remove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
EditText etrmvid = (EditText) findViewById(R.id.etrmvid);
dbh.removeFastFood(Integer.parseInt(etrmvid.getText()
.toString()));
etrmvid.setText("");
Toast toast = Toast.makeText(MainActivity.this,
"Fastfood is removed.", 2000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
refreshComponents();
}
});// end of remove
Context context = getApplicationContext();
// Adapter
}
class FastFoodAdapter<String> extends ArrayAdapter<String> {
public FastFood fastfood = new FastFood();
public FastFoodAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.listview_item_row, parent,
false);
}
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.listview_item_row, parent,
false);
TextView tv = (TextView) row.findViewById(R.id.txtTitle23);
TextView tv2 = (TextView) row.findViewById(R.id.txtTitle2);
ImageView iv = (ImageView) row.findViewById(R.id.imgIcon);
tv.setText(fastfood.getName());
tv2.setText(fastfood.getAddress());
if (fastfood.getFlag().equals("1"))
iv.setImageResource(R.drawable.sit);
else if (fastfood.getFlag().equals("2"))
iv.setImageResource(R.drawable.ta);
else if (fastfood.getFlag().equals("3"))
iv.setImageResource(R.drawable.deli);
return row;
}
}// /end of adapter
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.contexmenu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return super.onContextItemSelected(item);
}
private void refreshComponents() {
ListView lv = (ListView) findViewById(R.id.listView1);
TextView lblCount = (TextView) findViewById(R.id.lblcount);
DataBaseHandeler dbh = new DataBaseHandeler(MainActivity.this);
List<FastFood> fflist = dbh.getAllFastFoods();
// lv.setAdapter(new FastFoodAdapter<String>(context,
// textViewResourceId, objects))
lv.setAdapter(new FastFoodAdapter<FastFood>(MainActivity.this,
android.R.layout.simple_list_item_1, fflist));
lblCount.setText("Count of all FastFoods are " + dbh.getFastFoodCount());
}
}
here is fastfood class
package com.example.amirkh;
public class FastFood {
private String name;
private String address;
private String flag;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public FastFood(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
}
public FastFood() {
// TODO Auto-generated constructor stub
}
#Override
public String toString() {
return (String.format("%s %s ", getName(), getAddress()));
}
}
and the databasehandeler
package com.example.amirkh;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHandeler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "FastFoodManager";
private static final String TABALE_FASTFOODS = "fastfoods";
private static final String KEY_ID = "_id";
private static final String KEY_NAME = "name";
private static final String KEY_ADDRESS = "address";
private static final String KEY_FLAG = "flag";
public DataBaseHandeler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABALE_FASTFOODS + " ("
+ KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, "
+ KEY_ADDRESS + " TEXT, " + KEY_FLAG + " TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABALE_FASTFOODS);
onCreate(db);
}
// insert a record
public void addFastFood(FastFood fastfood) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, fastfood.getName());
values.put(KEY_ADDRESS, fastfood.getAddress());
values.put(KEY_FLAG, fastfood.getFlag());
db.insert(TABALE_FASTFOODS, null, values);
db.close();
}
// remove a record by ID
public void removeFastFood(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABALE_FASTFOODS, KEY_ID + " =?",
new String[] { String.valueOf(id) });
db.close();
}
// count
public int getFastFoodCount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABALE_FASTFOODS, null);
// db.close();
return cursor.getCount();
}
// get all contacts
public List<FastFood> getAllFastFoods() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABALE_FASTFOODS, null);
List<FastFood> fflist = new ArrayList<FastFood>();
if (cursor.moveToFirst()) {
do {
FastFood ff = new FastFood();
ff.setId(Integer.parseInt(cursor.getString(0)));
ff.setName(cursor.getString(1));
ff.setAddress(cursor.getString(2));
ff.setFlag(cursor.getString(3));
fflist.add(ff);
} while (cursor.moveToNext());
}
// db.close();
return fflist;
}
}
Thanks for helping

You are getting this NullPointerException because you are trying to compare a null String in this line
fastfood.getFlag().equals("1")
In your adapter you create an object of Food using
public FastFood fastfood = new FastFood();
In the empty constructor of Food class nothing is assigned to any of the member String so when you try to do
fastfood.getFlag().equals("1")
you are trying to call equals method on a null object.
So you get a NullPointerException.
You should use the Food objects from the List that you pass in the FastFoodAdapter constructor.

Your NPE come from:
if (fastfood.getFlag().equals("1"))
So fastfood.getFlag() seems null. You should use setFlag() before or try this comparison:
if ("1".equals(fastfood.getFlag()))

Related

recycler view does not refresh and show data

in my recycler view , when data get added , recycelr view does not show it until user close the activity and open it another time.
I think it has something to do with notifydataetchanger.
please help me with this
the only thing that worked by now was to creating an Intent .
but it makes app to loob very bad
my adaptor
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Rec_adaptor_aza extends RecyclerView.Adapter<Rec_adaptor_aza.ViewHolder> {
Context context;
public Rec_adaptor_aza(Context context, List<Model_aza> list_aza) {
this.context = context;
this.list_aza = list_aza;
}
List<Model_aza> list_aza;
#NonNull
#Override
public Rec_adaptor_aza.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.rec_row_aza,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Rec_adaptor_aza.ViewHolder holder, int position) {
Model_aza modelAza =list_aza.get(position);
holder.txt_name.setText(modelAza.getName_aza());
holder.txt_semat.setText(modelAza.getSemat_aza());
holder.txt_saat_voood.setText(modelAza.getSaaat_vorood_aza());
holder.txt_saat_khoroo.setText(modelAza.getSaat_khorooj_aza());
}
#Override
public int getItemCount() {
return list_aza.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_name,txt_semat,txt_saat_voood,txt_saat_khoroo;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txt_name=itemView.findViewById(R.id.txt__person__name);
txt_semat=itemView.findViewById(R.id.txt__person__semat);
txt_saat_voood=itemView.findViewById(R.id.txt__person__enter);
txt_saat_khoroo=itemView.findViewById(R.id.txt__person__out);
}
}
}
my model class
package com.example.myapplication;
public class Model_aza {
private String name_aza;
private String semat_aza;
private String saaat_vorood_aza;
public String getName_aza() {
return name_aza;
}
public void setName_aza(String name_aza) {
this.name_aza = name_aza;
}
public String getSemat_aza() {
return semat_aza;
}
public void setSemat_aza(String semat_aza) {
this.semat_aza = semat_aza;
}
public String getSaaat_vorood_aza() {
return saaat_vorood_aza;
}
public void setSaaat_vorood_aza(String saaat_vorood_aza) {
this.saaat_vorood_aza = saaat_vorood_aza;
}
public String getSaat_khorooj_aza() {
return saat_khorooj_aza;
}
public void setSaat_khorooj_aza(String saat_khorooj_aza) {
this.saat_khorooj_aza = saat_khorooj_aza;
}
private String saat_khorooj_aza;
}
My activity
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Activity_Gozaresh_giri extends AppCompatActivity {
private static final String TAG = "gozaresh_activity";
List<Model_aza> list_aza;
Rec_adaptor_aza rec_adaptor_aza;
public static Context context;
SQLiteDatabase sqLiteDatabase;
ImageButton btn__add__field, btn__add__field1;
final DataBase_aza dataBase_aza = new DataBase_aza(this);
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}
}
my data base
package com.example.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class DataBase_aza extends SQLiteOpenHelper {
public DataBase_aza(#Nullable Context context) {
super(context, "datbase_aza", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table if not exists database_aza (_id integer primary key autoincrement,_name varcher(55) not null,_semat varcher(55) not null, _vorood varcher(6) not null, _khorooj varchar(22) not null, id__item__gozaresh integer(55))");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long insert_info(String name, String semat, String vorood, String khorooj, int id) {
ContentValues cv = new ContentValues();
cv.put("_name", name);
cv.put("_semat", semat);
cv.put("_vorood", vorood);
cv.put("_khorooj", khorooj);
cv.put("id__item__gozaresh", id);
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
return sqLiteDatabase.insert("database_aza", null, cv);
}
public Cursor cursor(int id) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
return sqLiteDatabase.rawQuery("SELECT * FROM database_aza where id__item__gozaresh="+id, null);
}
}
I want recycler view to show data as soon as user clicks on add button
after adding entry just notify data set changed to adapter like below
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Log.d(TAG, "onCreate: onclicked");
rec_adaptor_aza = new Rec_adaptor_aza(this, list_aza);
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(rec_adaptor_aza);
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
rec_adaptor_aza.notifyDataSetChanged();
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
rec_adaptor_aza.notifyDataSetChanged(); // change here
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
}
Use it like below:-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gozaresh_giri);
btn__add__field1 = findViewById(R.id.btn__add__field1);
btn__add__field = findViewById(R.id.btn__add__field);
int id=getIntent().getIntExtra("id",0);
list_aza = new ArrayList<>();
Rec_adaptor_aza adapter = new Rec_adaptor_aza(this, list_aza); // Add
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
recyclerView_aza.setAdapter(adapter);
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Model_aza modelAza = new Model_aza(); // Add
modelAza.setName_aza(name_aza);// Add
modelAza.setSemat_aza(semat_aza);// Add
modelAza.setSaaat_vorood_aza(saat_vorood_aza);// Add
modelAza.setSaat_khorooj_aza(saat_khorooj_aza);// Add
list_aza.add(modelAza);// Add
adapter.notifyDataSetChanged();// Add
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
}
});
Cursor cursor1 = dataBase_aza.cursor(id);
for (cursor1.moveToFirst(); !cursor1.isAfterLast(); cursor1.moveToNext()) {
Model_aza modelAza = new Model_aza();
modelAza.setName_aza(cursor1.getString(1));
modelAza.setSemat_aza(cursor1.getString(2));
modelAza.setSaaat_vorood_aza(cursor1.getString(3));
modelAza.setSaat_khorooj_aza(cursor1.getString(4));
list_aza.add(modelAza);
}
adapter.notifyDataSetChanged();// Add
}
Just add the below code, in your clickListner, you need to add the same object in your list, and after adding you need to notify the adapter about the inserted item, by using notifyDataSetChanged().
btn__add__field.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText edtname = findViewById(R.id.edt__person__name);
EditText edt_semat_aza = findViewById(R.id.edt__person__semat);
EditText edt_vorood_aza = findViewById(R.id.edt__person__enter);
EditText edt_khorooj_aza = findViewById(R.id.edt__person__out);
String name_aza = edtname.getText().toString();
String semat_aza = edt_semat_aza.getText().toString();
String saat_vorood_aza = edt_vorood_aza.getText().toString();
String saat_khorooj_aza = edt_khorooj_aza.getText().toString();
long result = dataBase_aza.insert_info(name_aza, semat_aza, saat_vorood_aza, saat_khorooj_aza,id);
Toast.makeText(Activity_Gozaresh_giri.this, result + "", Toast.LENGTH_SHORT).show();
/*
* Adding entered data in list*/
Model_aza mm=new Model_aza();
mm.setName_aza(name_aza);
mm.setSemat_aza(semat_aza);
mm.setSaaat_vorood_aza(saat_vorood_aza);
mm.setSaat_khorooj_aza(saat_khorooj_aza);
list_aza.add(mm);
rec_adaptor_aza.notifyDataSetChanged();
}
});
Set layoutmanager before set the adapter to recylerview in your activity, like below
RecyclerView recyclerView_aza = findViewById(R.id.rec_aza);
// set layout manager before set adapter
recyclerView_aza.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView_aza.setAdapter(new Rec_adaptor_aza(this, list_aza));

Deleting an item from RecyclerView + SQLite

So I'm trying to delete an item on a cross button. Now it is being deleted from RecyclerView, but goes crazy with SQLite. If I delete one item, it's all good. But when I delete several items, it, as I said, goes crazy and gets deleted items back outta nowhere without deleting anything then.
Here's my DataAdapted.java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private LayoutInflater inflater;
private List<Booking> bookings;
private String time;
DBHelper dbHelper;
SQLiteDatabase dataBase;
DataAdapter(Context context, List<Booking> bookings) {
this.bookings = bookings;
this.inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public DataAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_view, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull DataAdapter.ViewHolder holder, int position) {
Booking booking = bookings.get(position);
holder.nameView.setText(booking.getName());
time = booking.getHours() + ":" + booking.getMinutes();
holder.timeView.setText(time);
}
#Override
public int getItemCount() {
return bookings.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameView;
TextView timeView;
ImageView crossImage;
ViewHolder(View view){
super(view);
timeView = view.findViewById(R.id.time_view);
nameView = view.findViewById(R.id.name_view);
crossImage = view.findViewById(R.id.crossImage);
crossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeAt(getAdapterPosition());
}
});
}
}
public void removeAt(int position) {
bookings.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, bookings.size());
DBHelper.delete(position);
}
}
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "bookingsDb";
public static final String TABLE_BOOKINGS = "bookings";
public static final String KEY_ID = "_id";
public static final String KEY_NUMBER = "_numbers";
public static final String KEY_NAME = "_names";
public static final String KEY_HOURS = "_hours";
public static final String KEY_MINUTES = "_minutes";
public static final String KEY_PHONE= "_phones";
Context myContext;
static DBHelper dbHelper;
static SQLiteDatabase database;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_BOOKINGS + "("
+ KEY_ID + " integer primary key,"
+ KEY_NUMBER + " integer,"
+ KEY_NAME + " text,"
+ KEY_HOURS + " text,"
+ KEY_MINUTES + " text,"
+ KEY_PHONE + " text" + ")");
dbHelper = new DBHelper(myContext);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_BOOKINGS);
onCreate(db);
}
public static void delete(int id){
database = dbHelper.getWritableDatabase();
database.delete(TABLE_BOOKINGS, KEY_ID + "=" + id, null);
}
}
And my TableActivity.java if needed
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class TableActivity extends AppCompatActivity {
int currentTable;
Button createNewBooking;
List<Booking> bookings;
TextView name;
TextView time;
DataAdapter adapter;
RecyclerView recyclerView;
DBHelper dbHelper;
View.OnClickListener createNewBookingListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TableActivity.this, BookingActivity.class);
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
currentTable = MainActivity.getCurrentTable();
createNewBooking = findViewById(R.id.createNewBooking);
createNewBooking.setOnClickListener(createNewBookingListener);
bookings = new ArrayList<>();
dbHelper = new DBHelper(this);
setInitialData();
recyclerView = findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new DataAdapter(this, bookings);
recyclerView.setAdapter(adapter);
}
private void setInitialData() {
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = database.query(DBHelper.TABLE_BOOKINGS, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(DBHelper.KEY_NAME);
int hoursIndex = cursor.getColumnIndex(DBHelper.KEY_HOURS);
int minutesIndex = cursor.getColumnIndex(DBHelper.KEY_MINUTES);
int phoneIndex = cursor.getColumnIndex(DBHelper.KEY_PHONE);
do {
bookings.add(new Booking(
currentTable,
cursor.getString(nameIndex),
cursor.getString(hoursIndex),
cursor.getString(minutesIndex),
cursor.getString(phoneIndex)
));
} while (cursor.moveToNext());
} else {
Toast.makeText(this, "Броней нет", Toast.LENGTH_SHORT).show();
}
cursor.close();
dbHelper.close();
}
}
Any ideas, please?
you are giving position for delete, it's not necessary to id will be same as per adapter position.
try this :
crossImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Booking booking = bookings.get(getAdapterPosition());
datatype id = booking.getId();
removeAt(getAdapterPosition(),id);
}
});
public void removeAt(int position, dataType id) {
bookings.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, bookings.size());
DBHelper.delete(id);
}

Can not delete the note from the list and from the database in my note app for Android

In my note app for Android, if I press long on a note then chose "Delete" to delete the note, the note still exists in the list, then after I close the app then return to it, the note is gone!
Hint: I am uses the onContextItemSelected method to show the "Delete" option.
How I can delete the note from the list and from the database?!
The MainActivity class which contains the onContextItemSelected method:
package com.twitter.i_droidi.mynotes;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
ListView lv;
NotesDataSource nDS;
List<NotesModel> notesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDS = new NotesDataSource(this);
lv = (ListView) findViewById(R.id.lv);
nDS.open();
notesList = nDS.getAllNotes();
nDS.close();
String[] notes = new String[notesList.size()];
for (int i = 0; i < notesList.size(); i++) {
notes[i] = notesList.get(i).getTitle();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
android.R.id.text1, notes);
lv.setAdapter(adapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent nView = new Intent(this, Second2.class);
nView.putExtra("id", notesList.get(position).getId());
nView.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(nView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_delete, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
nDS.open();
nDS.deleteNote("id"); // Check...!!!
nDS.close();
Toast nDelete = Toast.makeText(this, R.string.deleted, Toast.LENGTH_LONG);
nDelete.show();
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mainMenuNewNote:
Intent nNote = new Intent(this, Second.class);
startActivity(nNote);
return true;
case R.id.mainMenuAbout:
AlertDialog.Builder aboutDialog = new AlertDialog.Builder(this);
aboutDialog.setTitle(getString(R.string.about_title));
aboutDialog.setMessage(R.string.about_body);
aboutDialog.setIcon(R.drawable.my_notes);
aboutDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface aboutDialog, int witch) {
// Do Not Do Anything.
}
});
aboutDialog.show();
return true;
case R.id.mainMenuExit:
AlertDialog.Builder exDialog = new AlertDialog.Builder(this);
exDialog.setTitle(R.string.exit_title);
exDialog.setMessage(R.string.exit_body);
exDialog.setIcon(R.drawable.my_notes);
exDialog.setNegativeButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface exDialog, int which) {
finish();
}
});
exDialog.setPositiveButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface exDialog, int which) {
// Do Not Do Anything.
}
});
exDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The DB class:
package com.twitter.i_droidi.mynotes;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DB extends SQLiteOpenHelper {
private static final String DB_NAME = "MyNotes";
private static final int DB_VERSION = 1;
public static final String TABLE_NAME = "MyNotes";
public static final String ID = "id";
public static final String TITLE = "title";
public static final String BODY = "body";
private static final String DB_CREATE = "create table " + TABLE_NAME + " (" + ID + " integer primary key autoincrement, " +
TITLE + " text not null, " + BODY + " text not null)";
public DB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
The NotesDataSource class:
package com.twitter.i_droidi.mynotes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class NotesDataSource {
DB myDB;
SQLiteDatabase sql;
String[] getAllColumns = new String[]{DB.ID, DB.TITLE, DB.BODY};
public NotesDataSource(Context context) {
myDB = new DB(context);
}
public void open() {
try {
sql = myDB.getWritableDatabase();
} catch (Exception ex) {
Log.d("Error in your database!", ex.getMessage());
}
}
public void close() {
sql.close();
}
public void createNote(String title, String body) {
ContentValues note = new ContentValues();
note.put(myDB.TITLE, title);
note.put(myDB.BODY, body);
sql.insert(myDB.TABLE_NAME, null, note);
}
public NotesModel getNote(int id) {
NotesModel note = new NotesModel();
Cursor cursor = sql.rawQuery("SELECT * FROM " + DB.TABLE_NAME + " WHERE " + DB.ID + " = ?", new String[]{id + ""});
if (cursor.getCount() > 0) {
cursor.moveToFirst();
note.setId(cursor.getInt(0));
note.setTitle(cursor.getString(1));
note.setBody(cursor.getString(2));
cursor.close();
}
return note;
}
public void updateNote(int id, String title, String body) {
ContentValues note = new ContentValues();
note.put(myDB.TITLE, title);
note.put(myDB.BODY, body);
sql.update(myDB.TABLE_NAME, note, myDB.ID + " = " + id, null);
}
public void deleteNote(Object id) {
sql.delete(myDB.TABLE_NAME, myDB.ID + " = " + id, null);
}
public List<NotesModel> getAllNotes() {
List<NotesModel> notesList = new ArrayList<NotesModel>();
StringBuffer selectQuery = new StringBuffer();
selectQuery.append("SELECT * FROM "+ myDB.TABLE_NAME +"");
Cursor cursor = sql.rawQuery(selectQuery.toString(), null);
if(cursor != null && cursor.moveToFirst()) {
do {
NotesModel notes = new NotesModel();
notes.setId(cursor.getInt(0));
notes.setTitle(cursor.getString(1));
notes.setBody(cursor.getString(2));
notesList.add(notes);
} while (cursor.moveToNext());
}
cursor.close();
return notesList;
}
}
After removing item from database
Remove the deleted item from
String[] notes
by using
notes.remove(position);
nd call
adapter.notifyDataSetChanged();

How to display image to custom list view from database in android?

I have added some Data + Image to SQLite database, but now I want to display them into Custom List View. Just like below image(Image Link).
Image Link
I am unable to retrieve image from database and display it to custom list view. I have stored image to database in BLOB type.
MainActivity.java
package com.example.crudexamplerepeat;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button btn_add_new;
Button btn_old_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_add_new = (Button) findViewById(R.id.btn_add_new);
btn_add_new.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),
Add_new_activity.class);
startActivity(i);
}
});
btn_old_data = (Button) findViewById(R.id.btn_old_data);
btn_old_data.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i_new = new Intent(getApplicationContext(),
Old_data_activity.class);
startActivity(i_new);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Old_data_activity.java
package com.example.crudexamplerepeat;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Old_data_activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_old_data_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.old_data_activity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DatabaseHandler.java
package com.example.crudexamplerepeat;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import android.R.array;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DB_VERSION = 4;
private static final String DB_NAME = "usersInfo";
private static final String TABLE_NAME = "users";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PASS = "pass";
private static final String KEY_IMG = "pic";
public DatabaseHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID
+ " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT, " + KEY_PASS
+ " TEXT, " + KEY_IMG + " BLOB NOT NULL)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addNewUser(UserGetSet userGetSet) {
// TODO Auto-generated method stub
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, userGetSet.getName());
values.put(KEY_PASS, userGetSet.getPass());
values.put(KEY_IMG, userGetSet.getImage());
db.insert(TABLE_NAME, null, values);
db.close();
}
public List<UserGetSet> getAllUsers() {
List<UserGetSet> userList = new ArrayList<UserGetSet>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
{
do
{
UserGetSet userGetSetobj = new UserGetSet();
userGetSetobj.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
userGetSetobj.setPass(cursor.getString(cursor.getColumnIndex(KEY_PASS)));
userGetSetobj.setImage(cursor.getBlob(cursor.getColumnIndex(KEY_IMG)));
userList.add(userGetSetobj);
} while (cursor.moveToNext());
}
return userList;
}
}
UserListCustomAdapter.java
package com.example.crudexamplerepeat;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class UserListCustomAdapter extends BaseAdapter {
Context context;
protected List<UserGetSet> listUsers;
LayoutInflater inflater;
public UserListCustomAdapter(Context context, List<UserGetSet> listUsers) {
// TODO Auto-generated constructor stub
super();
this.listUsers = listUsers;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listUsers.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listUsers.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return listUsers.get(position).getUserId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// TODO Auto-generated method stub
ViewHolder viewHolder = new ViewHolder();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.user_list_view, null);
TextView name = (TextView) v.findViewById(R.id.txt_data_name);
TextView pass = (TextView) v.findViewById(R.id.txt_data_pass);
ImageView photo = (ImageView) v.findViewById(R.id.img_photo);
viewHolder.txt_name = name;
viewHolder.txt_pass = pass;
viewHolder.img_pic = photo;
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) v.getTag();
}
UserGetSet uGetSet = listUsers.get(position);
viewHolder.txt_name.setText(uGetSet.getName());
viewHolder.txt_pass.setText(uGetSet.getPass());
viewHolder.img_pic.setImageResource(uGetSet.getUserId());
return convertView;
}
private class ViewHolder {
TextView txt_name;
TextView txt_pass;
ImageView img_pic;
}
}
You have to convert the blog data before setting it to image view
byte[] byteArray = DBcursor.getBlob(columnIndex);
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0 ,byteArray.length);
now you may set the bitmap to your image view.
We don't need to store bytes of image in db, just store Uri of that image into DB and fetch that Uri and set on imageView.
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
imageView.setImageBitmap(bitmap);
I hope it'll help you

show data from database to listView Android

I am trying to show all my data from my database into the listview
Code to create database:
DataHander.java
package com.example.testingforstack;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataHandler {
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String TABLE_NAME = "mytable";
public static final String DATA_BASE_NAME = "mydatabase";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_CREATE = "create table mytable (name text not null, email text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
}
public static class DataBaseHelper extends SQLiteOpenHelper{
public DataBaseHelper(Context ctx) {
super(ctx, DATA_BASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
try{
db.execSQL(TABLE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getReadableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String name, String email){
ContentValues content = new ContentValues();
content.put(NAME, name);
content.put(EMAIL, email);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[] {NAME, EMAIL}, null, null, null, null, null);
}
}
mainActivity.java
package com.example.testingforstack;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save, load;
EditText name, email;
DataHandler handler;
String getName, getEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button) findViewById(R.id.save);
load = (Button) findViewById(R.id.load);
name = (EditText) findViewById(R.id.name);
email = (EditText) findViewById(R.id.email);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getName = name.getText().toString();
String getEmail = email.getText().toString();
handler = new DataHandler(getBaseContext());
handler.open();
long id = handler.insertData(getName, getEmail);
insertSuccess();
//Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getName = "";
getEmail = "";
handler = new DataHandler(getBaseContext());
handler.open();
Cursor C = handler.returnData();
if(C.moveToFirst()){
do{
getName = C.getString(0);
getEmail = C.getString(1);
}while(C.moveToNext());
}
handler.close();
loadSuccess();
//Toast.makeText(getBaseContext(), "Name: "+getName+", Email: "+getEmail, Toast.LENGTH_LONG).show();
}
});
}
public void insertSuccess()
{
AlertDialog.Builder insertData = new AlertDialog.Builder(this);
insertData.setTitle("Info");
insertData.setMessage("Data Inserted");
insertData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
insertData.show();
}
public void loadSuccess()
{
AlertDialog.Builder loadData = new AlertDialog.Builder(this);
loadData.setTitle("Info");
loadData.setMessage("Name: "+getName+" & your email: "+getEmail);
loadData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
loadData.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I have two button save and load. I have successfully implemented the save button to save the user name and email. However, I don't really know to load the data into the listview. How to do that?
In listview you can use different types of adapters. For database, most appropriate is to use cursorAdapter where you tell which cursor to use. You can also manually walk through elements in DB and save them in some other object in array and then you can have arrayAddapter in which you pass your array of object. In each case you must set binder or override method onCreateView where you tell which parameter go in which child.
You can look this http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html example for more information.

Categories

Resources