I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.
Any insight would be appreciated as I am lost here. Thanks in advance.
Here is where I initialise the class:
public ArrayList<GameStats> getAllData() {
ArrayList<GameStats> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String lName = cursor.getString(1);
int lScore = cursor.getInt(2);
String rName = cursor.getString(3);
int rScore = cursor.getInt(4);
String notes = cursor.getString(5);
GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
arrayList.add(gameStats);
}
return arrayList;
}
Here is where I am trying to use the getters:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_saved_games, null);
TextView lName = convertView.findViewById(R.id.lName);
TextView lScore = convertView.findViewById(R.id.lScore);
TextView rName = convertView.findViewById(R.id.rName);
TextView rScore = convertView.findViewById(R.id.rScore);
TextView notes = convertView.findViewById(R.id.notes);
GameStats gameStats = arrayList.get(position);
testVar = gameStats.getlName();
Log.d("MyAdaptor","gameStats = " + var);
lName.setText(gameStats.getlName());
lScore.setText(String.valueOf(gameStats.getlScore()));
rName.setText(gameStats.getrName());
rScore.setText(String.valueOf(gameStats.getrScore()));
notes.setText(gameStats.getNotes());
return convertView;
}
Here is the model class:
public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getlScore() {
return lScore;
}
public void setlScore(int lScore) {
this.lScore = lScore;
}
public int getrScore() {
return rScore;
}
public void setrScore(int rScore) {
this.rScore = rScore;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
and here is where I am calling the methods:
public class SavedGameScreen extends AppCompatActivity {
ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_game_screen);
lv1 = findViewById(R.id.lv1);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
loadData();
}
private void loadData() {
arrayList = databaseHelper.getAllData();
myAdaptor = new MyAdaptor(this, arrayList);
lv1.setAdapter(myAdaptor);
myAdaptor.notifyDataSetChanged();
}
}
Please change the constructor as below and see if that works,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
In your model class initialize the variables using constrtuctor. I guess that is the problem. Since you are not initializing the model class properties, it the getters will return "null" or any garbage value
You are passing the values to the model constructor but you are not assigning it to the model variables. You need to change the code as below,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
Else initialise each variable through setter() method.
My project used to save products information into shoppingCart on a database with dbSqlite. But, for now it should save information of product from server. According to web service, one variable type is List Array. It was String before. And one of them is double, it was String also. I changed real in dbSqlite but what I should do for Array? How can save it on dbSqlite again?
error: no suitable method found for put(String,List) method
ContentValues.put(String,String) is not applicable
Cart.java
public class Cart {
private List<String> Image;
private String Title;
private double Cost;
private String Market;
public List<String> getImage() {
return Image;
}
public void setImage(List<String> image) {
Image = image;
}
public double getCost() {
return Cost;
}
public void setCost(double cost) {
Cost = cost;
}
private String TotalCost;
private String Description;
public boolean boolExpand = false;
boolean isExpanded;
public boolean isExpanded() {
return this.isExpanded;
}
public void setExpanded(boolean expanded) {
this.isExpanded = expanded;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getMarket() {
return Market;
}
public void setMarket(String market) {
Market = market;
}
public String getTotalCost() {
return TotalCost;
}
public void setTotalCost(String totalCost) {
TotalCost = totalCost;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
ProductDetailAdapter.java
public class ProductDetailAdapter extends RecyclerView.Adapter<ProductDetailAdapter.ViewHolder> {
btnProductDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
// isLogined bilgisi shared preferences'tan alınıyor. eğer true ise username ve password bilgileri alınıyor.
// değil ise empty olarak giriliyor.
isLogined = sharedPreferences.getBoolean("isLogined", false);
if (isLogined) {
saveCartAmount();
db = new DatabaseHelper(mContext);
List<String> img;
double cost;
String title;
String total;
String market;
String description;
img = productPageList.get(position).getProductImages();
cost = productPageList.get(position).getProductPrices().get(position).getShopProductPrice();
title = productPageList.get(position).getProductName();
market = productPageList.get(position).getProductPrices().get(position).getShopName();
total = "";
description = productPageList.get(position).getProductDescription();
// Log.e("amountdb","dasdsa");
// amount = amountdb++;
db.AddToCart(img, title, cost, market, total, description);
cartListener.onProductSelect(productPageList.get(position));
Toast.makeText(mContext, "Ürün sepetinize eklendi.", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(mContext, "Sepete ürün eklemek için üye girişi yapmanız gerekmektedir.", Toast.LENGTH_SHORT).show();
}
}
});
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "Login.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table cart(Image text, Title text, Cost real, Market text, TotalCost text, Description text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists cart");
}
public void deleteCart(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete("cart", null,null);
}
public void AddToCart(List<String> Image, String Title, Double Cost, String Market, String TotalCost, String Descritpion){
SQLiteDatabase db = getWritableDatabase();
ContentValues data = new ContentValues();
data.put("Image",Image );
data.put("Title",Title);
data.put("Cost",Cost);
data.put("Market",Market);
data.put("TotalCost", TotalCost);
data.put("Description", Descritpion);
db.insert("cart",null,data);
}
public List<Cart> getdata(){
// DataModel dataModel = new DataModel();
List<Cart> data=new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor rs = db.rawQuery( "select * from cart",null);
StringBuffer stringBuffer = new StringBuffer();
Cart dataModel = null;
while (rs.moveToNext()) {
dataModel= new Cart();
List<String> image = Collections.singletonList(rs.getString(rs.getColumnIndexOrThrow("Image")));
String title = rs.getString(rs.getColumnIndexOrThrow("Title"));
Double cost = (rs.getDouble(rs.getColumnIndexOrThrow("Cost")));
String market = rs.getString(rs.getColumnIndexOrThrow("Market"));
String totalCost = rs.getString(rs.getColumnIndexOrThrow("TotalCost"));
String description = rs.getString(rs.getColumnIndexOrThrow("Description"));
dataModel.setImage(image);
dataModel.setTitle(title);
dataModel.setCost(cost);
dataModel.setMarket(market);
dataModel.setTotalCost(totalCost);
dataModel.setDescription(description);
stringBuffer.append(dataModel);
data.add(dataModel);
}
return data;
}
}
You can read the array like this :
String[] myArray = `put your array here`
for (int i = 0; i < myArray.size(); i++)
{
//Here u insert the data by getting what u need from the array
data.put("Cost",myArray.get(i).Cost);
}
You should be fine serializing the list to string. I. e. you could serialize it to json and deserialize it if you need it again.
Here is a small code example for two functions you could use in your DatabaseHelper.
private String serialize(List<String) list) {
JSONArray jsonArray = new JSONArray();
for (String s : list) {
jsonArray.put(s);
}
return jsonArray.toString();
}
private List<String> deserialize(String json) {
JSONArray jsonArray = new JSONArray(json);
List<String> list = new ArrayList<>();
for (int i=0; i<jsonArray.getLength(); ++i) {
list.add(jsonArray.getString(i));
}
return list;
}
And then you can use these functions:
data.put("Image",serialize(Image));
List<String> image = deserialize(rs.getString(rs.getColumnIndexOrThrow("Image")));
(This is only pseudo-code. Maybe you need to adjust it. Furthermore the functions don't handle null-parameters and may throw NullPointerExceptions!)
I am creating an android app (still the basic structure, without any design) from an Job site through XML feed using REST api.
Till now, I could managed to parse the XML data, displaying the List View with an POP UP menu item on each row. I am passing Data from PostBaseAdapter to MarkAsFav class. Could You please tell me if I am doing right or not? coz, I am getting no any data saved in database
Now, I have a problems:
I have 3 pop up menu item:
1. Set as Favourite
2. Share on Fb
3. email to Your friend
I am working on point number-1.
For now,I would be saving the data in SQLite Database itself. so, I am passing all the data (all the details about the job with all rows) to another activity, more over I am accepting a user given name to save the details through insertDB() in my Database.
But, unfortunately , nothing is getting saved in the database .
Can you tell me, if the data is getting passed or not and if the datas are being saved in database or not?
Please help me out. Please tell me where and how to modify the code?
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
MarkAsFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
Intent extras = getIntent();
if (extras != null) {
int Value = extras.getIntExtra("id",0);
if (Value > 0) {
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.JOBS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText((CharSequence) nam);
header.setFocusable(false);
header.setClickable(false);
}
}
}
public void run(View view) {
Intent extras = getIntent();
if (extras != null) {
int val = extras.getIntExtra("id",0);
String value1 = extras.getStringExtra("title");
String value2= extras.getStringExtra("company");
String value3= extras.getStringExtra("city");
String value4= extras.getStringExtra("state");
String value5= extras.getStringExtra("country");
String value6= extras.getStringExtra("formattedLocation");
String value7= extras.getStringExtra("source");
String value8= extras.getStringExtra("date");
String value9= extras.getStringExtra("snippet");
String value10= extras.getStringExtra("url");
String value11= extras.getStringExtra("onmousedown");
String value12= extras.getStringExtra("lattitude");
String value13= extras.getStringExtra("longitude");
String value14= extras.getStringExtra("jobkey");
String value15= extras.getStringExtra("sponsored");
String value16= extras.getStringExtra("expired");
String value17= extras.getStringExtra("formattedLocationFull");
String value18= extras.getStringExtra("formattedRelativeTime");
String headerValue = header.getText().toString();
Log.e("ERROR", "Inside run and checking Value and val");
if (val > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)) {
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
PostBaseAdapter.java
public class PostBaseAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ArrayList<Result> resultList;
private MainActivity mActivity;
private Context mContext;
String TAG="";
public PostBaseAdapter(Context context, ArrayList<Result> resultList) {
this.layoutInflater = LayoutInflater.from(context);
this.resultList = resultList;
this.mContext= context;
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Result getItem(int i) {
return resultList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int j=i;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_post, null);
//viewHolder = new ViewHolder(convertView);
viewHolder= new ViewHolder();
//View overFlow = convertView.findViewById(R.id.id_overflow);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.imageClick= (ImageView) convertView.findViewById(R.id.id_overflow);
convertView.setTag(viewHolder);
//overFlow.setOnClickListener(new OverflowSelectedListener(mContext, mActivity));
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Result result = resultList.get(i);
viewHolder.tvTitle.setText(result.getJobtitle());
final String jobTitle=resultList.get(i).getJobtitle();
final String company= resultList.get(i).getCompany();
final String city= resultList.get(i).getCity();
final String state= resultList.get(i).getState();
final String country= resultList.get(i).getCountry();
final String formattedLocation= resultList.get(i).getFormattedLocation();
final String source=resultList.get(i).getSource();
final String date= resultList.get(i).getDate();
final String snippet= resultList.get(i).getSnippet();
final String url= resultList.get(i).getUrl();
final String onmousedown= resultList.get(i).getOnmousedown();
final String lattitude= resultList.get(i).getLattitude();
final String longitude= resultList.get(i).getLongitude();
final String jobkey= resultList.get(i).getJobkey();
final String sponsored= resultList.get(i).getSponsored();
final String expired= resultList.get(i).getExpired();
final String formattedLocaionfull= resultList.get(i).getFormattedLocation();
final String formattedRelativeTime= resultList.get(i).getFormattedRelativeTime();
try {
viewHolder.imageClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.id_overflow:
final PopupMenu popup = new PopupMenu(mContext, v);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
// Force icons to show
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int id_To_Search = j + 1;
/*Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtras(dataBundle);
mContext.startActivity(intent);*/
switch (item.getItemId()) {
case R.id.email_whatsapp:
doEmailOrWhatsapp(mActivity);
return true;
case R.id.share_on_fb:
shareOnFb(mActivity);
return true;
case R.id.mark_as_fav:
//viewHolder.
//dataBundle.putString("name", result.getJobtitle());
Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtra("id",0);
intent.putExtra("title", jobTitle );
intent.putExtra("company",company );
intent.putExtra("city", city);
intent.putExtra("state",state );
intent.putExtra("country",country );
intent.putExtra("formattedLocation",formattedLocation );
intent.putExtra("source",source );
intent.putExtra("date", date);
intent.putExtra("snippet", snippet);
intent.putExtra("url", url);
intent.putExtra("onmousedown",onmousedown );
intent.putExtra("lattitude", lattitude);
intent.putExtra("longitude",longitude );
intent.putExtra("jobkey", jobkey);
intent.putExtra("sponsored",sponsored );
intent.putExtra("expired", expired);
intent.putExtra("formattedLocationFull",formattedLocaionfull );
intent.putExtra("formattedRelativeTime",formattedRelativeTime );
//intent.putExtras(dataBundle);
mContext.startActivity(intent);
return true;
default:
break;
}
return true;
}
});
//popup.show();
break;
default:
break;
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
TextView tvTitle;//, tvPublishDate;
ImageView imageClick;
/* public ViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);*/
// imageClick=(ImageView)item.findViewById(R.id.id_overflow);
// tvPublishDate = (TextView) item.findViewById(R.id.tvPublishDate);
}
}
mark-fav-layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<EditText
android:id="#+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="text" >
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="#string/save" />
</LinearLayout>
Result.java
public class Result {
public String jobtitle;
public String company;
public String city;
public String state;
public String country;
public String formattedLocation;
public String source;
public String date;
public String snippet;
public String url;
public String onmousedown;
public String lattitude;
public String longitude;
public String jobkey;
public String sponsored;
public String expired;
public String formattedLocationFull;
public String formattedRelativeTime;
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
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 getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFormattedLocation() {
return formattedLocation;
}
public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getJobkey() {
return jobkey;
}
public void setJobkey(String jobkey) {
this.jobkey = jobkey;
}
public String getSponsored() {
return sponsored;
}
public void setSponsored(String sponsored) {
this.sponsored = sponsored;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getFormattedLocationFull() {
return formattedLocationFull;
}
public void setFormattedLocationFull(String formattedLocationFull) {
this.formattedLocationFull = formattedLocationFull;
}
public String getFormattedRelativeTime() {
return formattedRelativeTime;
}
public void setFormattedRelativeTime(String formattedRelativeTime) {
this.formattedRelativeTime = formattedRelativeTime;
}
public String getDetails() {
String result = jobtitle + ": " + company + "\n" + city + "-" + state
+ "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
"\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
+jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
return result;
}
}
I have just updated my code and its working fine for me. I am posting it here ,so that anyone can use if needed.
MarkFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
mydb.getWritableDatabase();
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
if (value > 0) {
//means this is the view part not the add contact part.
/* Cursor rs = mydb.getData(value);
id_To_Update = value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText( nam);
header.setFocusable(false);
header.setClickable(false);*/
}
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
String headerValue = header.getText().toString();
String value1 = extras.getString("title");
String value2 = extras.getString("company");
String value3 = extras.getString("city");
String value4 = extras.getString("state");
String value5 = extras.getString("country");
String value6 = extras.getString("formattedLocation");
String value7 = extras.getString("source");
String value8 = extras.getString("date");
String value9 = extras.getString("snippet");
String value10= extras.getString("url");
String value11= extras.getString("onmousedown");
String value12= extras.getString("lattitude");
String value13= extras.getString("longitude");
String value14= extras.getString("jobkey");
String value15= extras.getString("sponsored");
String value16= extras.getString("expired");
String value17= extras.getString("formattedLocationFull");
String value18= extras.getString("formattedRelativeTime");
Log.e("ERROR", "Inside run and checking Value and val");
if (value > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
/* public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);*/
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" Text, "+JOBS_COLUMN_NAME+" Text,"+JOBS_COLUMN_COMPANY+" Text, "+JOBS_COLUMN_CITY+" Text, "+JOBS_COLUMN_STATE+" Text, "+JOBS_COLUMN_COUNTRY+" Text,"+JOBS_COLUMN_FORMATEDLOCATION+" Text,"+JOBS_COLUMN_SOURCE+" Text,"+JOBS_COLUMN_DATE+" Text,"+JOBS_COLUMN_SNIPPET+" Text,"+JOBS_COLUMN_COMPANY+" Text,"+JOBS_COLUMN_URL+"Text,"+JOBS_COLUMN_ONMOUSEDOWN+" Text,"+JOBS_COLUMN_LATTITUDE+" Text,"+JOBS_COLUMN_LONGITUDE+"Text,"+JOBS_COLUMN_JOBKEY+" Text,"+JOBS_COLUMN_SPONSORED+" Text,"+JOBS_COLUMN_EXPIRED+" Text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" Text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" Text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
/* public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}*/
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
I am trying to display data from SQLite database to custom listview but it is not displaying. When I am using simple list view with single data then it's working but not working when I am trying to display on custom listview.
MainActivity.java
package com.example.addressbook;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.AddressBook.MESSAGE";
private ListView lv;
List<Listcollection> collectionlist;
DBHelper mydb;
private Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
mydb = new DBHelper(this);
// CustomListAdapter customListAdapter = new
// CustomListAdapter(MainActivity.this, );
lv.setAdapter(new ViewAdapter(mydb.listfromdb()));
// lv.setAdapter(ViewAdapter);
// adding it to the list view.
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.Display.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
List<Listcollection> collectionlist;
public ViewAdapter(List<Listcollection> c) {
collectionlist = c;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return collectionlist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#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);
convertView = mInflater.inflate(R.layout.list_item, null);
}
Listcollection o = collectionlist.get(position);
if (o != null) {
TextView idText = (TextView) convertView
.findViewById(R.id.lvid);
TextView nameText = (TextView) convertView
.findViewById(R.id.lvname);
TextView dateText = (TextView) convertView
.findViewById(R.id.lvdate);
TextView phoneText = (TextView) convertView
.findViewById(R.id.lvphone);
if (idText != null) {
idText.setText(Integer.toString(o.getId()));
}
if (nameText != null) {
nameText.setText("Name : "
+ collectionlist.get(position).getName());
}
if (dateText != null) {
dateText.setText("Date: "
+ collectionlist.get(position).getDate());
}
if (phoneText != null) {
phoneText.setText("Phone: "
+ collectionlist.get(position).getPhone());
}
}
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.item1:
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.Display.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String C_NAME = "name";
public static final String C_TYPE = "type";
public static final String C_ADDRESS = "address";
public static final String C_DATE = "date";
public static final String C_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table contacts "
+ "(id integer primary key, name text,phone text,type text, address text,date text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact(String name, String phone, String type,
String address, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("type", type);
contentValues.put("address", address);
contentValues.put("date", date);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from contacts where id=" + id + "",
null);
return res;
}
public int numberOfRows() {
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db,
CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact(Integer id, String name, String phone,
String type, String address, String date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("type", type);
contentValues.put("address", address);
contentValues.put("date", date);
db.update("contacts", contentValues, "id = ? ",
new String[] { Integer.toString(id) });
return true;
}
public Integer deleteContact(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<Listcollection> listfromdb() {
SQLiteDatabase db = this.getReadableDatabase();
Listcollection lcollection;
Listcollection list = new Listcollection();
ArrayList<Listcollection> results = new ArrayList<Listcollection>();
Cursor crs = db.rawQuery("select * from contacts", null);
crs.moveToFirst();
list.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID)));
list.setName(crs.getString(crs.getColumnIndex(C_NAME)));
list.setDate(crs.getString(crs.getColumnIndex(C_DATE)));
list.setPhone(crs.getString(crs.getColumnIndex(C_PHONE)));
db.close();
return results;
}
}
enter code here
Listcollection.java
public class Listcollection {
// private variables
int id;
String name;
String type;
String address;
String date;
String phone;
// Empty constructor
public Listcollection(Parcel in) {
}
// constructor
public Listcollection(int id, String name, String type, String address,
String date, String phone) {
this.id = id;
this.name = name;
this.type = type;
this.address = address;
this.phone = phone;
this.date = date;
}
public Listcollection() {
// TODO Auto-generated constructor stub
}
// getting id
public int getId() {
return this.id;
}
// setting id
public void setId(int id) {
this.id = id;
}
// getting name
public String getName() {
return this.name;
}
// setting name
public void setName(String name) {
this.name = name;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return "Complain [id=" + id + ", name=" + name + ", type=" + type
+ ", address=" + address + ", date=" + date + ", phone="
+ phone + ",";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Listcollection other = (Listcollection) obj;
if (id != other.id)
return false;
return true;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(getId());
parcel.writeString(getName());
parcel.writeString(getType());
parcel.writeString(getAddress());
parcel.writeString(getPhone());
parcel.writeString(getDate());
}
public static final Parcelable.Creator<Listcollection> CREATOR = new Parcelable.Creator<Listcollection>() {
public Listcollection createFromParcel(Parcel in) {
return new Listcollection(in);
}
public Listcollection[] newArray(int size) {
return new Listcollection[size];
}
};
}
You're not actually adding the database records to the results collection in listfromdb().
Should be something like:
public ArrayList<Listcollection> listfromdb() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Listcollection> results = new ArrayList<Listcollection>();
Cursor crs = db.rawQuery("select * from contacts", null);
while (crs.moveToNext()) {
Listcollection item = new Listcollection();
item.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID)));
item.setName(crs.getString(crs.getColumnIndex(C_NAME)));
item.setDate(crs.getString(crs.getColumnIndex(C_DATE)));
list.setPhone(crs.getString(crs.getColumnIndex(C_PHONE)));
results.add(item);
}
db.close();
return results;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to SQLite. I have an activity in which I have different fields like Name,Email,Date of Birth etc. When user fill the information and clicks the save button I want it to get saved to the database. But I am stuck in mid way and don't know what to do.How to save the data from Edit Text Views to the database on Save Button click.Please help me.
I am sharing my code.
DataBaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "NewUserDb.db";
private static final String TABLE_INFO = "info";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_GOAL = "userGOAL";
public static final String COLUMN_NAME = "userName";
public static final String COLUMN_EMAIL = "userEmail";
public static final String COLUMN_DOB = "userDOB";
public static final String COLUMN_HEIGHT = "userHeight";
public static final String COLUMN_WEIGHT = "userWeight";
public static final String COLUMN_GENGER = "userGender";;
public static final String COLUMN_ZIP = "userZIP";
private static final String[] COLUMNS = { COLUMN_ID, COLUMN_GOAL,
COLUMN_NAME, COLUMN_EMAIL, COLUMN_DOB, COLUMN_HEIGHT,
COLUMN_WEIGHT, COLUMN_GENGER, COLUMN_ZIP };
// http://www.techotopia.com/index.php/An_Android_SQLite_Database_Tutorial
/*
* public DatabaseHelper(Context context, String name, CursorFactory
* factory, int version) { super(context, name, factory, version); // TODO
* Auto-generated constructor stub
*
* }
*/
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_USER_TABLE = "CREATE TABLE User ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "gaol TEXT, "
+ "name TEXT )";
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS users");
// create fresh books table
this.onCreate(db);
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void addUser(NewUserDb newuserdb) {
// for logging
// Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(COLUMN_GOAL, newuserdb.getGoal()); // get title
values.put(COLUMN_NAME, newuserdb.getName()); // get author
values.put(COLUMN_EMAIL, newuserdb.getEmail());
values.put(COLUMN_DOB, newuserdb.getDob());
values.put(COLUMN_HEIGHT, newuserdb.getHeight());
values.put(COLUMN_WEIGHT, newuserdb.getWeight());
values.put(COLUMN_GENGER, newuserdb.getGender());
values.put(COLUMN_ZIP, newuserdb.getZip());
// 3. insert
db.insert(TABLE_INFO, // table
null, // nullColumnHack
values); // key/value -> keys = column names/ values = column
// values
// 4. close
db.close();
}
public NewUserDb getNewUserDb(int id) {
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor = db.query(TABLE_INFO, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
NewUserDb newUserdb = new NewUserDb();
newUserdb.setId(Integer.parseInt(cursor.getString(0)));
newUserdb.setGoal(cursor.getString(1));
newUserdb.setName(cursor.getString(2));
newUserdb.setEmail(cursor.getString(3));
newUserdb.setDob(cursor.getString(4));
newUserdb.setHeight(cursor.getString(5));
newUserdb.setWeight(cursor.getString(6));
newUserdb.setGender(cursor.getString(7));
newUserdb.setZip(cursor.getString(8));
// Log.d("getBook("+id+")", book.toString());
// 5. return book
return newUserdb;
}
// Deleting single book
public void deleteUser(NewUserDb newuserDB) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_INFO, COLUMN_ID + " = ?",
new String[] { String.valueOf(newuserDB.getId()) });
// 3. close
db.close();
Log.d("deleteBook", newuserDB.toString());
}
}
NewUserDb.java
public class NewUserDb {
private int id;
private String goal;
private String name;
private String email;
private String dob;
private String height;
private String weight;
private String gender;
private String zip;
public NewUserDb() {
}
public NewUserDb(int id, String goal, String name, String email,
String dob, String height, String weight, String gender, String zip) {
super();
this.id = id;
this.goal = goal;
this.name = name;
this.email = email;
this.dob = dob;
this.height = height;
this.weight = weight;
this.gender = gender;
this.zip = zip;
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGoal() {
return goal;
}
public void setGoal(String goal) {
this.goal = goal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String toString() {
return "User [id=" + id + ", goal=" + goal + ", name=" + name
+ ", email=" + email + ", dob=" + dob + ", height=" + height
+ ", weight=" + weight + ", gender=" + gender + ", zip =" + zip
+ "]";
}
}
AccountActivity.java
public class AccountActivity extends Activity {
private EditText et_weight, et_height, et_email, et_dob, et_name;
private Button btn_uploadPhoto, btn_shootPhoto, btn_del, btn_save;
private Switch genderSwitch;
private DatePickerDialog datePickerDialog;
private String year;
private String month;
private String day;
DatabaseHelper dbh = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accounts);
btn_shootPhoto = (Button) findViewById(R.id.button1);
btn_uploadPhoto = (Button) findViewById(R.id.button2);
btn_del = (Button) findViewById(R.id.btn_del);
btn_save = (Button) findViewById(R.id.btn_save);
et_dob = (EditText) findViewById(R.id.et_dob);
genderSwitch = (Switch) findViewById(R.id.mySwitch);
et_name = (EditText) findViewById(R.id.et_name);
et_email = (EditText) findViewById(R.id.et_email);
et_height = (EditText) findViewById(R.id.et_height);
et_height.setInputType(InputType.TYPE_CLASS_NUMBER);
et_weight = (EditText) findViewById(R.id.et_weight);
et_weight.setInputType(InputType.TYPE_CLASS_NUMBER);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//what to do here ??
}
});
}
try .getText() on your EditText
like yourEditText.getText(); and set it into your NewUserDb and pass the NewUserDb object into addUser method of your DatabaseHelper class
First you declare database create table query string in your DatabaseHelper class like this:
private static final String DATABASE_CREATE_USER = "create table UserInfo("
+ "_id VARCHAR(20)," + "userGOAL VARCHAR(20),"
+ "userName VARCHAR(20)," + "userEmail VARCHAR(20),"
+ "userDOB VARCHAR(20)," + "userHeight VARCHAR(10),"
+ "userWeight VARCHAR(10)," + "userGender VARCHAR(10),"
+ "userZIP VARCHAR(10) "+ ")";
Then write inside onCreate method of DatabaseHelper
db.execSQL(DATABASE_CREATE_USER);
Then declare object of SqliteDatabase and DatabseHelper in your AcountActivity like this:
DatabaseHelper dbHelper;
SQLiteDatabase db;
Afer this write following code inside your button onClick method:
dbHelper= new DatabaseHelper(ActountActivity.this);
db = dbHelper.getWritableDatabase();
ContentValues insertValues = new ContentValues();
insertValues.put("_id", "User_Id");
insertValues.put("userGOAL", "User_Goal");
insertValues.put("userName", "User_Name");
insertValues.put("userEmail", "User_Email");
insertValues.put("userDOB", "User_DOB");
insertValues.put("userHeight", "User_Height");
insertValues.put("userWeight", "User_Weight");
insertValues.put("userGender", "User_Gender");
insertValues.put("userZIP", "User_Zip");
db.insert("UserInfo", null, insertValues);
db.close();
May this help you.