Related
For some reason the only thing displayed in my RecyclerView is com.stu54259.plan2cook.Model.Shopping_list#5cb7482 repeated with various end codes not the contents of the ArrayList. Any suggestions must be something with the recylerview adapter. Can add xml etc if need be but i'm sure I've just missed something stupid.
Shopping_List class
package com.stu54259.plan2cook.Model;
public class Shopping_List {
private int id;
private String ingredient_type;
private String ingredient_name;
private Double quantity;
private String measurement_name;
public Shopping_List() {
}
public Shopping_List(String ingredient_type, String ingredient_name, Double quantity, String measurement_name) {
this.ingredient_type = ingredient_type;
this.ingredient_name = ingredient_name;
this.quantity = quantity;
this.measurement_name = measurement_name;
}
public Shopping_List(int id, String ingredient_type, String ingredient_name, Double quantity, String measurement_name) {
this.id = id;
this.ingredient_type = ingredient_type;
this.ingredient_name = ingredient_name;
this.quantity = quantity;
this.measurement_name = measurement_name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIngredient_type() {
return ingredient_type;
}
public void setIngredient_type(String ingredient_type) {
this.ingredient_type = ingredient_type;
}
public String getIngredient_name() {
return ingredient_name;
}
public void setIngredient_name(String ingredient_name) {
this.ingredient_name = ingredient_name;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public String getMeasurement_name() {
return measurement_name;
}
public void setMeasurement_name(String measurement_name) {
this.measurement_name = measurement_name;
}
}
Activity
public class ShoppingList extends MainActivity {
ShoppingListAdapter adapterRecipe;
List<Shopping_List> shopList = new ArrayList<>();
RecyclerView listIngredient;
SQLiteDatabase db;
Cursor c;
EditText edittext;
String search;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_list);
edittext = findViewById(R.id.editPlanName);
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
search = edittext.getText().toString();
Log.d("Search value", search);
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
loadIngredient();
adapterRecipe.notifyDataSetChanged();
return true;
}
return false;
}
});
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(ShoppingList.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(ShoppingList.this,RecipeSearch.class);
startActivity(b);
break;
case R.id.shoppingList:
Intent c = new Intent(ShoppingList.this, ShoppingList.class);
startActivity(c);
break;
case R.id.mealPlan:
Intent d = new Intent(ShoppingList.this, MenuPlan.class);
startActivity(d);
break;
case R.id.reminder:
Intent e = new Intent(ShoppingList.this, Reminders.class);
startActivity(e);
break;
}
return false;
}
});
adapterRecipe = new ShoppingListAdapter(this, shopList);
listIngredient = findViewById(R.id.listIngredient);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
listIngredient.setLayoutManager(mLayoutManager);
listIngredient.setItemAnimator(new DefaultItemAnimator());
listIngredient.setAdapter(adapterRecipe);
}
public void loadIngredient() {
shopList.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH =
"SELECT SUM(A.ingredient_quantity) quantity, A.ingredient ingredient_name, A.recipe, B.ingredient_type, B.measurement_name, C.id, D.plan_name " +
"FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS + " AS B ON A.ingredient = B.ingredient_name " +
"JOIN " + DatabaseManager.TABLE_PLAN_RECIPES + " AS C ON A.recipe = C.recipe_name " +
"JOIN " + DatabaseManager.TABLE_MEAL_PLAN + " AS D ON C.id = D.plan_recipe " +
"WHERE D.plan_name LIKE ? GROUP BY A.ingredient";
Log.d("Search query", RECIPE_SEARCH);
c = db.rawQuery(RECIPE_SEARCH, new String[]{"%" + search + "%"});
if (c.moveToFirst()) {
do {
Shopping_List shopping_list = new Shopping_List();
shopping_list.setQuantity(c.getDouble(c.getColumnIndex("quantity")));
shopping_list.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
shopping_list.setIngredient_type(c.getString(c.getColumnIndex("ingredient_type")));
shopping_list.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
shopList.add(shopping_list);
} while (c.moveToNext());
}
c.close();
db.close();
}
}
Adapter
public class ShoppingListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder> {
private List<Shopping_List> shopList;
private LayoutInflater mInflater;
private com.stu54259.plan2cook.Adapters.RecyclerViewAdapter.ItemClickListener mClickListener;
// data is passed into the constructor
public ShoppingListAdapter(Context context, List<Shopping_List> data) {
this.mInflater = LayoutInflater.from(context);
this.shopList = data;
}
// inflates the row layout from xml when needed
#Override
public com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.fragment_item, parent, false);
return new com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).toString());
}
}
// total number of rows
#Override
public int getItemCount() {
return shopList.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.quantity);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// allows clicks events to be caught
void setClickListener(com.stu54259.plan2cook.Adapters.RecyclerViewAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Add this method in your Shopping_List class, so when you use toString() for a Shopping_List instance you will get all its properties separated by spaces:
public String toString() {
return ingredient_name + " " + ingredient_type + " " + quantity + " " + measurement_name;
}
You can change the order of the properties.
You have wrong code in onBindViewHolder method. You should set text with some field from Shopping_List object:
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).toString());
}
}
You haven't put the Shopping_List object here, but if you have something like this:
public class Shopping_List {
public String title;
public String getTitle() {
return title;
}
}
Then you should do something like this:
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).getTitle());
}
}
Although it doesn't give a direct solution, I would suggest that you use the groupie library. It will most likely remove your error and reduce boilerplate code and complexity.
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 building an app for Udacity called popular movies app which will fetch movies info from movieDB and display posters in the first activity than if the user clicked any poster it will take him to detailActivity where all the Movie detail will be displayed.
Now I am done with stage 1, stage 2 I am supposed to give the user the ability to make a favorite movie list which will be displayed in the first activity and deatilActivity and will be fetched from and to a database.
I already created the database and I have data saved there but I do not no how to retrieve it and display it to user kindly help me to do it.
below is my code:
First Activity the gridView for posters:
public class PhotoGrid extends Fragment {
//Create a string array variable for every item that we are going to recive from
// the movieDB
String[] movieId, movieTitle, movieReleaseDate, movieVoteAverage, movieOverview, moviePosterPath;
//use string1 to attach the poster path for every poster with the url so we can call the image
static String[] string1;
// define gridView here so we can use it in onPostexecute()
GridView gridView;
//movieUrl is used for the sortby setting
String movieUrl;
SQLiteDatabase db;
databaseHelper databaseHelper;
Cursor cursor;
ContentProvider contentProvider;
public PhotoGrid() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
}
#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_refresh) {
updateMovie();
return true;
} else if (id == R.id.action_settings) {
//if action_setting clicked SettingActivity will start
Intent intent = new Intent(getActivity(), SettingActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateMovie() {
FetchMoviesPosters movieTask = new FetchMoviesPosters();
//make popularity as the default order or call for movieposters in settings
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sortby_key),
getString(R.string.pref_sortby_default));
movieTask.execute(sortBy);
}
#Override
public void onStart() {
super.onStart();
//update movies list on start
updateMovie();
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_photo_grid, container, false);
databaseHelper = new databaseHelper(getActivity(),MovieContract.MovieEntry.TABLE_NAME,null,2);
db = databaseHelper.getReadableDatabase();
gridView = (GridView) rootView.findViewById(R.id.grid_view);
updateMovie();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Here handle the on poster click action by assigning the clicked poster info
//to strings and send them to detail activity with different keys to be able to
// control each item alone
String movieIDText = movieId[i];
String movieTitleText = movieTitle[i];
String movieOverViewText = movieOverview[i];
String movieReleaseDateText = movieReleaseDate[i];
String movieRatingText = movieVoteAverage[i];
String movieDetailImage = moviePosterPath[i];
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("movie_id", movieIDText);
intent.putExtra("movie_overview", movieOverViewText);
intent.putExtra("movie_title", movieTitleText);
intent.putExtra("movie_release_date", movieReleaseDateText);
intent.putExtra("movie_rating", movieRatingText);
intent.putExtra("image_path", movieDetailImage);
startActivity(intent);
}
});
return rootView;
}
//ImageAdapter is used to control images dimensions and load them in the
// imageview using Picasso
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private String[] mThumbIds;
public ImageAdapter(Context c, String[] str2) {
mContext = c;
mThumbIds = str2;
}
#Override
public int getCount() {
if (mThumbIds != null) {
return mThumbIds.length;
} else {
return 0;
}
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(700, 1200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(mThumbIds[position]).into(imageView);
return imageView;
}
}
public class FetchMoviesPosters extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesPosters.class.getSimpleName();
//in this function the different order settings are defined
private String setOrder(String sortBy) {
if (sortBy.equals(getString(R.string.pref_sorting_popularity))) {
movieUrl = "https://api.themoviedb.org/3/movie/popular?";
} else if (sortBy.equals(getString(R.string.pref_sorting_highest_rating))) {
movieUrl = "https://api.themoviedb.org/3/movie/top_rated?";
}
else if (sortBy.equals(getString(R.string.pref_sorting_favorite))){
cursor = databaseHelper.retrieveData(db);
if (cursor.moveToFirst()){
do {
String id, title, overView, releaseDate, rating, posterPath;
id = cursor.getString(0);
title = cursor.getString(1);
overView = cursor.getString(2);
releaseDate = cursor.getString(3);
rating = cursor.getString(4);
posterPath = cursor.getString(5);
contentProvider = new ContentProvider(id , title , overView
, releaseDate, rating , posterPath);
}while (cursor.moveToNext());
}
}
return sortBy;
}
private String[] MoviesJasonPrase(String moviesPosterStr ) throws JSONException {
final String M_Result = "results";
final String M_ID = "id";
final String M_Title = "original_title";
final String M_Release = "release_date";
final String M_Vote = "vote_average";
final String M_OverV = "overview";
final String M_Poster = "poster_path";
JSONObject moviesJson = new JSONObject(moviesPosterStr);
JSONArray resultsArray = moviesJson.getJSONArray(M_Result);
movieId = new String[resultsArray.length()];
movieTitle = new String[resultsArray.length()];
movieReleaseDate = new String[resultsArray.length()];
movieVoteAverage = new String[resultsArray.length()];
movieOverview = new String[resultsArray.length()];
moviePosterPath = new String[resultsArray.length()];
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject movie = resultsArray.getJSONObject(i);
movieId[i] = movie.getString(M_ID);
movieTitle[i] = movie.getString(M_Title);
movieReleaseDate[i] = movie.getString(M_Release);
movieVoteAverage[i] = movie.getString(M_Vote);
movieOverview[i] = movie.getString(M_OverV);
moviePosterPath[i] = movie.getString(M_Poster);
}
return moviePosterPath;
}
#Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviePostersJsonStr = null;
try {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sortby_key),
getString(R.string.pref_sorting_popularity));
setOrder(sortBy);
final String APPID_PARAM = "api_key";
Uri builtUri = Uri.parse(movieUrl).buildUpon()
.appendQueryParameter(APPID_PARAM, BuildConfig.THE_MOVIE_DB)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to TheMovieDB, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
moviePostersJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PhotoGrid", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PhotoGrid", "Error closing stream", e);
}
}
}
try {
return MoviesJasonPrase(moviePostersJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] Strings) {
if (Strings != null) {
string1 = new String[Strings.length];
for (int i = 0; i < Strings.length; i++) {
//receive poster images path
String[] getImage = Strings[i].split("-");
//concatenate path to url "http://image.tmdb.org/t/p/w185/"
string1[i] = "http://image.tmdb.org/t/p/w185/" + getImage[0];
}
ImageAdapter imageAdapter = new ImageAdapter(getActivity(), string1);
//put images after going though the adapter in the gridview
gridView.setAdapter(imageAdapter);
}
}
}
}
The detailActivity:
public class DetailFragment extends Fragment {
String ID;
String title;
String overView;
String releaseDate;
String rating;
String posterPath;
String movieKey;
databaseHelper myDB ;
ImageButton favorite;
public DetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_detail, menu);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(getActivity(), SettingActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
myDB = new databaseHelper(getActivity(), MovieContract.MovieEntry.TABLE_NAME,null,2);
favorite = (ImageButton) rootView.findViewById(R.id.favorite);
final Intent intent = getActivity().getIntent();
// The detail Activity called via intent. Inspect the intent for
// movies data using movie ID.
if (intent != null && intent.hasExtra("movie_id")) {
//if true put each item in a textview and load the poster in imageView
ID = intent.getStringExtra("movie_id");
title = intent.getStringExtra("movie_title");
((TextView) rootView.findViewById(R.id.title_text))
.setText(title);
overView = intent.getStringExtra("movie_overview");
((TextView) rootView.findViewById(R.id.overview_text))
.setText(overView);
releaseDate = intent.getStringExtra("movie_release_date");
((TextView) rootView.findViewById(R.id.release_date_text))
.setText(releaseDate);
rating = intent.getStringExtra("movie_rating");
((TextView) rootView.findViewById(R.id.rating_text))
.setText(rating);
posterPath = intent.getStringExtra("image_path");
String posterImage = "http://image.tmdb.org/t/p/w185/" + posterPath;
ImageView imageView = (ImageView) rootView.findViewById(R.id.detail_image);
Picasso.with(getActivity()).load(posterImage).resize(500, 800).into(imageView);
}
Button button = (Button) rootView.findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playTrailer();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(String.valueOf("http://www.youtube.com/watch?v="+ movieKey)));
startActivity(intent);
}
});
Button button1 = (Button) rootView.findViewById(R.id.open_reviews);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = ID;
Intent intent1 = new Intent(getActivity(), ReviewActivity.class);
intent1.putExtra("movie_id", id);
startActivity(intent1);
}
});
addData();
return rootView;
}
public void playTrailer() {
FetchMoviesTrailer fetchMoviesTrailer = new FetchMoviesTrailer();
fetchMoviesTrailer.execute(ID);
}
public void addData(){
favorite.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInsearted = myDB.insert(ID, title, overView, releaseDate,
rating, posterPath);
if (isInsearted)
Toast.makeText(getActivity(),"Added to Favorite", Toast.LENGTH_SHORT)
.show();
else
Toast.makeText(getActivity(),"Not Added to Favorite", Toast.LENGTH_SHORT)
.show();
}
}
);
}
public class FetchMoviesTrailer extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesTrailer.class.getSimpleName();
//in this function the different order settings are defined
private String[] MoviesJasonPrase(String moviesTrailerStr) throws JSONException {
final String T_Result = "results";
final String T_key = "key";
JSONObject moviesJson = new JSONObject(moviesTrailerStr);
JSONArray resultsArray = moviesJson.getJSONArray(T_Result);
String[] strings = new String[resultsArray.length()];
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject movie = resultsArray.getJSONObject(i);
movieKey = movie.getString(T_key);
strings[i] = movieKey;
}
return strings;
}
#Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieTrailerJsonStr = null;
try {
final String APPID_PARAM = "api_key";
final String Traile_Url = "http://api.themoviedb.org/3/movie/" + ID
+ "/videos?";
Uri builtUri = Uri.parse(Traile_Url).buildUpon()
.appendQueryParameter(APPID_PARAM, BuildConfig.THE_MOVIE_DB)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to TheMovieDB, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieTrailerJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PhotoGrid", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PhotoGrid", "Error closing stream", e);
}
}
}
try {
return MoviesJasonPrase(movieTrailerJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
}
}
}
The DataBase Helper:
public class databaseHelper extends SQLiteOpenHelper{
SQLiteDatabase db ;
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "FavoriteMovies.db";
public databaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_Movie_TABLE = "CREATE TABLE " + MovieEntry.TABLE_NAME + " (" +
MovieEntry.ID_COLUMAN + " TEXT PRIMARY KEY," +
MovieEntry.TITLE_COLUMAN + " TEXT NOT NULL, " +
MovieEntry.OVERVIEW_COLUMAN + " TEXT NOT NULL, " +
MovieEntry.RELEASE_DATE_COLUMAN + " TEXT NOT NULL, " +
MovieEntry.RATING_COLUMAN + " TEXT NOT NULL, " +
MovieEntry.POSTAR_PATH_COLUMAN+ " TEXT NOT NULL " +
" );";
db.execSQL(SQL_CREATE_Movie_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + MovieEntry.TABLE_NAME);
onCreate(db);
}
public boolean insert(String id, String title , String overView , String date, String rating,
String poster){
db = super.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MovieEntry.ID_COLUMAN,id);
contentValues.put(MovieEntry.TITLE_COLUMAN,title);
contentValues.put(MovieEntry.OVERVIEW_COLUMAN,overView);
contentValues.put(MovieEntry.RELEASE_DATE_COLUMAN,date);
contentValues.put(MovieEntry.RATING_COLUMAN,rating);
contentValues.put(MovieEntry.POSTAR_PATH_COLUMAN, poster);
long isAdded = db.insert(MovieEntry.TABLE_NAME, null ,contentValues);
if (isAdded == -1) {
return false;
}
else
return true;
}
public Cursor retrieveData(SQLiteDatabase db){
Cursor cursor;
String[] projection = {MovieEntry.ID_COLUMAN, MovieEntry.TITLE_COLUMAN,
MovieEntry.OVERVIEW_COLUMAN, MovieEntry.RELEASE_DATE_COLUMAN, MovieEntry.RATING_COLUMAN,
MovieEntry.POSTAR_PATH_COLUMAN};
cursor = db.query(MovieEntry.TABLE_NAME, projection, null,null,null,null,null);
return cursor;
}
}
The DataBase Contract:
public class MovieContract {
public MovieContract(){}
public static abstract class MovieEntry implements BaseColumns{
public static final String TABLE_NAME = "favorite";
public static final String ID_COLUMAN = "ID";
public static final String TITLE_COLUMAN = "title";
public static final String OVERVIEW_COLUMAN = "overView";
public static final String RELEASE_DATE_COLUMAN = "releaseDate";
public static final String RATING_COLUMAN = "rating";
public static final String POSTAR_PATH_COLUMAN = "posterPath";
}
}
The content Provider:
public class ContentProvider {
private String id;
private String title;
private String overView;
private String releaseDate;
private String rating;
private String posterPath;
public ContentProvider(String ID, String Title,String OverView, String ReleaseDate,
String Rating, String PosterPath){
this.id = ID;
this.title = Title;
this.overView = OverView;
this.releaseDate = ReleaseDate;
this.rating = Rating;
this.posterPath = PosterPath;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOverView() {
return overView;
}
public void setOverView(String overView) {
this.overView = overView;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
}
This is all covered in the Udacity course. I would suggest reviewing those videos.
However, the basic idea is that you need to create a query() method in your content provider class. The Sunshine example from Udacity looks something like this:
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Here's the switch statement that, given a URI, will determine what kind of request it is,
// and query the database accordingly.
Cursor retCursor;
switch (sUriMatcher.match(uri)) {
// "weather/*/*"
case WEATHER_WITH_LOCATION_AND_DATE:
{
retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder);
break;
}
// "weather/*"
case WEATHER_WITH_LOCATION: {
retCursor = getWeatherByLocationSetting(uri, projection, sortOrder);
break;
}
// "weather"
case WEATHER: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.WeatherEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
// "location"
case LOCATION: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.LocationEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
From there, if you aren't using a CursorLoader, you need to call the query method on your Content Resolver and pass in your parameters.
Here is an example from Google:
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
I would also take a look at this link to read more about Content Providers.
I have problem with sqlite database adapter in my project.I'm new to android development so I don't have much idea to how can handle this problem. I want to save user information in data base .Although no error while execution,database doesn't create? can any one help.
DatabaseAdapter :
public class DatabaseAdapter {
private final String TAG = "DatabaseAdapter";
private DatabaseOpenHelper openHelper;
public static final String TBL_PERSONS = "persons";
public static final String PERSON_ID = "_id";
public static final String PERSON_USERNAME = "_username";
public static final String PERSON_HEIGHT = "_height";
public static final String PERSON_WEIGHT = "_weight";
public static final String PERSON_AGE = "_age";
public static final String PERSON_GENDER = "_gender";
public static final String PERSON_PA = "_pa";
public static final String PERSON_BMI = "_bmivalue";
public static final String PERSON_INTERPRETATION = "_bmiInterpretation";
public static final String PERSON_IDEALWEIGHT = "_idealweight";
public static final String PERSON_DAILYCALORIES = "_dailycalories";
// ???????????
public DatabaseAdapter(Context context) {
openHelper = new DatabaseOpenHelper(context, "Persons.db", null, 1);
}
// ====================insert in
// database===========================================================
public Long insertPerson(Person person) {
SQLiteDatabase db = null;
Long id = -1L;
try {
ContentValues values = new ContentValues();
values.put("PERSON_USERNAME", person.getUsername());
values.put("PERSON_HEIGHT", person.getHeight());
values.put("PERSON_WEIGHT", person.getWeight());
values.put("PERSON_AGE", person.getAge());
values.put("PERSON_GENDER", person.getGender());
values.put("PERSON_PA", person.getPa());
values.put("PERSON_BMI", person.getBmivalue());
values.put("PERSON_INTERPRETAION", person.getBmiInterpretation());
values.put("PERSON_IDEALWEIGHT", person.getIdealweight());
values.put("PERSON_DAILYCALORIES", person.getDailycalories());
db = openHelper.getWritableDatabase();
id = db.insert(TBL_PERSONS, null, values);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
if (db != null && db.isOpen())
db.close();
}
return id;
}
// ================delete from
// database=============================================================
public int deletePerson(long id) {
SQLiteDatabase db = null;
int count = -1;
try {
db = openHelper.getWritableDatabase();
count = db.delete(TBL_PERSONS, PERSON_ID + "=?",
new String[] { String.valueOf(id) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
db.close();
}
return count;
}
// ===============update
// database===================================================================
public int updatePerson(Person person) {
SQLiteDatabase db = null;
int count = -1;
try {
db = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PERSON_USERNAME, person.getUsername());
values.put(PERSON_HEIGHT, person.getHeight());
values.put(PERSON_WEIGHT, person.getWeight());
values.put(PERSON_AGE, person.getAge());
values.put(PERSON_GENDER, person.getGender());
values.put(PERSON_PA, person.getPa());
values.put(PERSON_BMI, person.getBmivalue());
values.put(PERSON_INTERPRETATION, person.getBmiInterpretation());
values.put(PERSON_IDEALWEIGHT, person.getIdealweight());
values.put(PERSON_DAILYCALORIES, person.getDailycalories());
count = db.update(TBL_PERSONS, values, PERSON_ID + "=?",
new String[] { String.valueOf(person.getId()) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
db.close();
}
return count;
}
// ===================================================================DATABASEOPENHELPER
// CLASS=========================
class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String
.format("create table %s(%$ integer primary key,%s text,%s text,%s text,%s text,%s text,%s tetx,%s text,%s text,%s text,%s text)",
TBL_PERSONS, PERSON_ID, PERSON_USERNAME,
PERSON_HEIGHT, PERSON_WEIGHT, PERSON_AGE,
PERSON_GENDER, PERSON_PA, PERSON_BMI,
PERSON_INTERPRETATION, PERSON_IDEALWEIGHT,
PERSON_DAILYCALORIES);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
person.java (I pass the user data to person.java)
package Databasedata;
public class Person {
private Long id;
private String username;
private float height;
private int weight;
private int age;
private String gender;
private String pa;
private int bmivalue;
private String bmiInterpretation;
private double idealweight;
private double dailycalories;
public double getIdealweight() {
return idealweight;
}
public void setIdealweight(double idealweight) {
this.idealweight = idealweight;
}
public double getDailycalories() {
return dailycalories;
}
public void setDailycalories(double dailycalories) {
this.dailycalories = dailycalories;
}
public int getBmivalue() {
return bmivalue;
}
public void setBmivalue(int bmivalue) {
this.bmivalue = bmivalue;
}
public String getBmiInterpretation() {
return bmiInterpretation;
}
public void setBmiInterpretation(String bmiInterpretation) {
this.bmiInterpretation = bmiInterpretation;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPa() {
return pa;
}
public void setPa(String pa) {
this.pa = pa;
}
}
MAIN ACTIVITY
public class MainActivity extends Activity {
String gender;
RadioButton maleRadioButton;
RadioButton femaleRadioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
maleRadioButton = (RadioButton) findViewById(R.id.maleselected);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleselected);
final RadioGroup genderselected = (RadioGroup) findViewById(R.id.selectgender);
genderselected.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int selectedId) {
selectedId=genderselected.getCheckedRadioButtonId();
RadioButton genderchoosed = (RadioButton) findViewById(selectedId);
gender= genderchoosed.getText().toString();
}
});
Button saveinformation = (Button) findViewById(R.id.saveinformation);
saveinformation.setOnClickListener(new View.OnClickListener() {
EditText weighttext = (EditText) findViewById(R.id.weighttext);
EditText heighttext = (EditText) findViewById(R.id.heighttext);
EditText usernametext = (EditText) findViewById(R.id.usernametext);
EditText agetext = (EditText) findViewById(R.id.agetext);
Spinner activitytext = (Spinner) findViewById(R.id.chooseactivity);
Button saveinformation = (Button) findViewById(R.id.saveinformation);
String pa = activitytext.getSelectedItem().toString();
#Override
public void onClick(View v) {
if(maleRadioButton.isChecked()) {
gender= maleRadioButton.getText().toString();
} else {
gender = femaleRadioButton.getText().toString();
}
int weight = (int) Float.parseFloat(weighttext.getText()
.toString());
float height = Float.parseFloat(heighttext.getText()
.toString());
String username = usernametext.getText().toString();
int age = (int) Float.parseFloat(agetext.getText().toString());
String pa = activitytext.getSelectedItem().toString();
// BMI
// ============================================================================================
int Bmivalue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(Bmivalue);
float idealweight = idealweight(weight, height, gender, pa, age);
double dailycalories=dailycalories(weight,height,gender,pa,age);
// insert in to
// db==================================================================================
Person person = new Person();
person.setUsername(username);
person.setHeight(height);
person.setWeight(weight);
person.setAge(age);
person.setGender(gender);
person.setPa(pa);
person.setBmivalue(Bmivalue);
person.setBmiInterpretation(bmiInterpretation);
person.setIdealweight(idealweight);
person.setDailycalories(dailycalories);
// ?????????????????????????????????????????/
Databasedata.DatabaseAdapter dbAdapter = new Databasedata.DatabaseAdapter(
MainActivity.this);
dbAdapter.insertPerson(person);
Toast.makeText(getApplicationContext(),
Bmivalue + "and you are" + bmiInterpretation,
Toast.LENGTH_LONG).show();
}
});
}
}
One Problem I see is in your insertPerson() method. Don't include the "" in the values.put()
try replacing below code
ContentValues values = new ContentValues();
values.put("PERSON_USERNAME", person.getUsername());
values.put("PERSON_HEIGHT", person.getHeight());
values.put("PERSON_WEIGHT", person.getWeight());
values.put("PERSON_AGE", person.getAge());
values.put("PERSON_GENDER", person.getGender());
values.put("PERSON_PA", person.getPa());
values.put("PERSON_BMI", person.getBmivalue());
values.put("PERSON_INTERPRETAION", person.getBmiInterpretation());
values.put("PERSON_IDEALWEIGHT", person.getIdealweight());
values.put("PERSON_DAILYCALORIES", person.getDailycalories());
with
ContentValues values = new ContentValues();
values.put(PERSON_USERNAME, person.getUsername());
values.put(PERSON_HEIGHT, person.getHeight());
values.put(PERSON_WEIGHT, person.getWeight());
values.put(PERSON_AGE, person.getAge());
values.put(PERSON_GENDER, person.getGender());
values.put(PERSON_PA, person.getPa());
values.put(PERSON_BMI, person.getBmivalue());
values.put(PERSON_INTERPRETATION, person.getBmiInterpretation());
values.put(PERSON_IDEALWEIGHT, person.getIdealweight());
values.put(PERSON_DAILYCALORIES, person.getDailycalories());
I am currently trying to add a deleting ability to a ListView onItemLongClick. Unfortunately, for some reason I cannot seem to do this. Whenever I long click, the dialog box appears correctly and when I press yes to delete, nothing at all happens. The item still remains in the Listview and in the database because I call the method to display all the items from the updated database right after I call my delete method. I have been trying to fix this problem for two days now and I have gotten nowhere. It seems as though it is unable to retrieve an Id from the database for each item, but I am not sure why it would be doing this.
Here is my habit object class:
public class Habit extends Object implements Serializable{
private int day_count;
private int _id;
private String habit_name, date_started, end_date, day_count_string, id_string;
public Habit(){
}
public Habit(int id, String name, String startDate, String endDate, int dayCount){
this._id = id;
this.habit_name = name;
this.date_started = startDate;
this.end_date = endDate;
this.day_count = dayCount;
}
public Habit(String name, String startDate, String endDate, int dayCount){
this.habit_name = name;
this.date_started = startDate;
this.end_date = endDate;
this.day_count = dayCount;
}
public int getID()
{
return _id;
}
public int setID(int id)
{
return this._id;
}
public String getIDString()
{
id_string = "" + this._id;
return id_string;
}
public int getDayCount()
{
return this.day_count;
}
public String getDayCountString()
{
day_count_string = "" + this.day_count;
return day_count_string;
}
public int setDayCount(int dayCount)
{
return this.day_count;
}
public String getName()
{
return this.habit_name;
}
public void setName(String name)
{
this.habit_name = name;
}
public String getStartDate()
{
return this.date_started;
}
public void setStartDate(String startDate)
{
this.date_started = startDate;
}
public String getEndDate()
{
return this.end_date;
}
public void setEndDate(String endDate)
{
this.end_date = endDate;
}
}
Here is my databaseHelper code where I call add habit to create one habit item in the database and I call deleteHabit to delete the habit at the location of the id that is in the habit object class:
public class HabitDbHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME="habits";
public static final String TABLE_HABITS = "habit_names";
public static final String KEY_NAME = "hname";
public static final String KEY_ID = "id";
public static final String KEY_STARTDATE = "start_date";
public static final String KEY_ENDDATE = "end_date";
public static final String KEY_DAYCOUNT = "day_count";
public HabitDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+TABLE_HABITS+" ("
+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+KEY_NAME+" TEXT, "
+KEY_STARTDATE+" TEXT, "
+KEY_ENDDATE+" TEXT, "
+KEY_DAYCOUNT+" INTEGER);");
}
// Upgrading Database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_HABITS);
onCreate(db);
}
//Adding new habit
public void addHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, habit.getName()); // Habit Name
values.put(KEY_STARTDATE, habit.getStartDate()); // Start Date
values.put(KEY_ENDDATE, habit.getEndDate()); // End Date
values.put(KEY_DAYCOUNT, habit.getDayCount());
// Inserting Row
db.insert(TABLE_HABITS, null, values);
db.close(); // Closing database connection
}
// Fetching 1 Habit
public Habit getHabit(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HABITS, new String[] { KEY_ID,
KEY_NAME, KEY_STARTDATE ,KEY_ENDDATE, KEY_DAYCOUNT }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Habit habit = new Habit(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), Integer.parseInt(cursor.getString(4)));
// return contact
return habit;
}
// Fetching all Habits
public ArrayList<Habit> getAllHabits() {
ArrayList<Habit> habitList = new ArrayList<Habit>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_HABITS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Habit habit = new Habit();
habit.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
habit.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
habit.setStartDate(cursor.getString(cursor.getColumnIndex(KEY_STARTDATE)));
habit.setEndDate(cursor.getString(cursor.getColumnIndex(KEY_ENDDATE)));
habit.setDayCount(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_DAYCOUNT))));
// Adding contact to list
habitList.add(habit);
} while (cursor.moveToNext());
}
return habitList;
}
// Deleting Single Habit
public void deleteHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HABITS, KEY_ID + " = ?",
new String[] { String.valueOf(habit.getID()) });
db.close();
}
}
Here is my Listview adapter where each item is put into a custom item layout:
public class HabitAdapter extends BaseAdapter {
private ArrayList<Habit> habits;
private Context context;
private int layoutId;
private long id1;
public HabitAdapter(Context c, int LayoutId,ArrayList<Habit> habits) {
this.context = c;
this.layoutId = LayoutId;
this.habits = habits;
}
#Override
public int getCount() {
return habits.size();
}
#Override
public Habit getItem(int position) {
return habits.get(position);
}
#Override
public long getItemId(int position) {
Habit habit = (Habit)habits.get(position);
id1 = Long.parseLong(habit.getIDString());
return id1;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
Habit habit = habits.get(pos);
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.fragment_start_habit_item, null);
mHolder = new Holder();
mHolder.title = (TextView)child.findViewById(R.id.fragment_title);
mHolder.dayCount = (TextView)child.findViewById(R.id.fragment_days_left);
mHolder.startDate = (TextView)child.findViewById(R.id.fragment_start_date);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.title.setText(habit.getName());
mHolder.dayCount.setText("Days Completed: " + habit.getDayCountString());
mHolder.startDate.setText("Date Started: " + habit.getStartDate());
return child;
}
public class Holder {
TextView title;
TextView dayCount;
TextView startDate;
}
}
And finally, my main activity where I delete the item that is selected onItemLongClick:
public class fourtyMain extends Activity
{
private HabitDbHelper mDB;
private ListView mList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fourty_main);
mList = (ListView)findViewById(R.id.habit_list);
mDB = new HabitDbHelper(this);
getActionBar().setDisplayShowTitleEnabled(false);
//Start new activity with click
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3)
{
Intent singleI = new Intent(fourtyMain.this, SingleHabitView.class);
final Habit habit = (Habit) parent.getAdapter().getItem(position);
singleI.putExtra("habit", habit);
startActivity(singleI);
}
});
//long click to delete data
mList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, final View view, int position, long id) {
final Habit habit = (Habit) parent.getAdapter().getItem(position);
deleteHabitInListView(habit);
return true;
}
private void deleteHabitInListView(final Habit habit){
Builder deleteDialog = new AlertDialog.Builder(fourtyMain.this);
deleteDialog.setTitle("Delete " + habit.getName() + "?");
deleteDialog.setMessage("Are you sure you want to delete this habit? All your progress will be lost!");
deleteDialog.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDB.deleteHabit(habit);
displayData();
}
});
deleteDialog.setNegativeButton("No", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
deleteDialog.show();
}
});
}
//Populate Listview
#Override
protected void onResume() {
displayData();
super.onResume();
}
private void displayData()
{
ArrayList<Habit> habitList = mDB.getAllHabits();
HabitAdapter disadpt = new HabitAdapter(fourtyMain.this, R.layout.fragment_start_habit_item, habitList);
mList.setAdapter(disadpt);
disadpt.notifyDataSetChanged();
}
}
I am absolutely lost on this one. I have been working for two days now to try and fix this problem and I have gotten nowhere. If I had to guess, I think I am going wrong on either retrieving the ID from the database or storing it incorrectly.
EDIT:
To add to this, I just found a way to write the id to a toast whenever the item is clicked. No matter what item in the list, it is returning 0 for the id. This makes me think that I am either fetching the id incorrectly or storing it incorrectly and my delete function is correct.
Insted of handling listview's setOnItemLongClickListener method, handl the perticuler cell's setOnItemLongClickListener
just like bleow :
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
Habit habit = habits.get(pos);
if (child == null) {
layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.fragment_start_habit_item, null);
mHolder = new Holder();
mHolder.llCellLayout = (LinearLayout)child.findViewById(R.id.llCellLayout);
mHolder.title = (TextView)child.findViewById(R.id.fragment_title);
mHolder.dayCount = (TextView)child.findViewById(R.id.fragment_days_left);
mHolder.startDate = (TextView)child.findViewById(R.id.fragment_start_date);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.title.setText(habit.getName());
mHolder.dayCount.setText("Days Completed: " + habit.getDayCountString());
mHolder.startDate.setText("Date Started: " + habit.getStartDate());
mHolder.llCellLayout.setOnItemLongClickListener(new OnItemLongClickListener(){
//** you can get id here and write code here for delete**
});
return child;
}
public class Holder {
TextView title;
TextView dayCount;
TextView startDate;
LinearLayout llCellLayout; //** this is the layout of cell**
}
try this code for delete operation
public float delete(String table,String colmName,String data) {
// TODO Auto-generated method stub
SQLiteDatabase db=dbhlpr.getWritableDatabase();
String[] arr={data};
colmName=colmName+"=?";
float res=db.delete(table, colmName,arr );
db.close();
return res;
}
Try to delete like below,
// Deleting Single Habit
public void deleteHabit(Habit habit) {
SQLiteDatabase database = this.getWritableDatabase();
{
database.execSQL("delete from " + "TABLE_HABITS"
+ " where KEY_ID='" + String.valueOf(habit.getID())+ "'");
}
database .close();
}
you could try the following:
1.Either change the query to a raw query like this:
public void deleteHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "delete from " + TABLE_HABITS + " where "
+ KEY_ID + "=" + habit.getID();
db.rawQuery(sql,null);
db.close();
}
2.Or you could also try this:
public void deleteHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HABITS, KEY_ID+ "=" + habit.getID(), null);
db.close();
}
Hope that helps!
I managed to figure it out and of course it was the simplest error possible. In my habit object class I had it written:
public int setID(int id)
{
return this._id;
}
When all I needed to do was change it to this:
public void setID(int id)
{
this._id = id;
}
Stupid rookie mistake on my part but luckily thanks to trial and error by everybody I finally figured out my screw up. Thanks to anybody that helped out!