How to share a post's content in android? - android

I have a recycelerview that get JSON data from mySQl database online and I want to have a share button for each post that can share each post's content ,as you see i used "ACTION_SEND" codes but it doesn't share my content and just share the body sentence(the exact sentence that is in sharedBodyText),please tell me how can i share my post?here is my codes:
codes for the page that shows full post:
public class full_post extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_post);
Intent intent=getIntent();
int id=intent.getIntExtra(koreDatabaseOpenHelper.COL_ID,0);
String title=intent.getStringExtra(koreDatabaseOpenHelper.COL_TITLE);
String content=intent.getStringExtra(koreDatabaseOpenHelper.COL_CONTENT);
String date=intent.getStringExtra(koreDatabaseOpenHelper.COL_DATE);
TextView titleTextView=(TextView)findViewById(R.id.post_title);
TextView contentTextView=(TextView)findViewById(R.id.post_content);
TextView dateTextView=(TextView)findViewById(R.id.post_date);
titleTextView.setText(title);
contentTextView.setText(content);
dateTextView.setText(date);
}
public void shareText(View view) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
String shareBodyText =(koreDatabaseOpenHelper.COL_CONTENT) ;
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject/Title");
intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(intent, "Choose sharing method"));
}}
codes of my DatabaseHelper :
public class koreDatabaseOpenHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseOpenHelper";
private static final String DATABASE_NAME="db_kdramadl";
private static final int DATABASE_VERSION=1;
private static final String POST_TABLE_NAME="tbl_posts";
public static final String COL_ID="col_id";
public static final String COL_TITLE="col_title";
public static final String COL_CONTENT="col_content";
public static final String COL_DATE="col_date";
private static final String SQL_COMMAND_CREATE_POST_TABLE="CREATE TABLE IF NOT EXISTS "+POST_TABLE_NAME+"("+
COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
COL_TITLE+" TEXT,"+
COL_CONTENT+" TEXT, "+
" INTEGER DEFAULT 0, "+
COL_DATE+" TEXT);";
Context context;
public koreDatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(SQL_COMMAND_CREATE_POST_TABLE);
}catch (SQLException e){
Log.e(TAG, "onCreate: "+e.toString() );
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addPost(Post post){
ContentValues cv=new ContentValues();
cv.put(COL_ID,post.getId());
cv.put(COL_TITLE,post.getTitle());
cv.put(COL_CONTENT,post.getContent());
cv.put(COL_DATE,post.getDate());
SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
long isInserted=sqLiteDatabase.insert(POST_TABLE_NAME,null,cv);
Log.i(TAG, "addPost: "+isInserted);
if (isInserted>0){
return true;
}else{
return false;
}
}
public void addPosts(List<Post> posts){
for (int i = 0; i < posts.size(); i++) {
if (!checkPostExists(posts.get(i).getId())) {
addPost(posts.get(i));
}
}
}
and this is my adapter :
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
private Context context;
private List<Post> posts;
public PostAdapter (Context context, List<Post> posts){
this.context = context;
this.posts = posts;
}
#Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.postha,parent,false);
Typeface morvaridTypeface=Typeface.createFromAsset(context.getAssets(),"fonts/morvarid.ttf");
return new PostViewHolder(view,morvaridTypeface);
}
#Override
public void onBindViewHolder(PostViewHolder holder, int position) {
final Post post=posts.get(position);
holder.title.setText(post.getTitle());
holder.content.setText(post.getContent());
holder.date.setText(post.getDate());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,full_post.class);
intent.putExtra(koreDatabaseOpenHelper.COL_ID,post.getId());
intent.putExtra(koreDatabaseOpenHelper.COL_TITLE,post.getTitle());
intent.putExtra(koreDatabaseOpenHelper.COL_CONTENT,post.getContent());
intent.putExtra(koreDatabaseOpenHelper.COL_DATE,post.getDate());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return posts.size();
}
public class PostViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private TextView content;
private TextView date;
public PostViewHolder(View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.post_title);
content=(TextView)itemView.findViewById(R.id.post_content);
date=(TextView)itemView.findViewById(R.id.post_date);
}
}}

I have used below code to share post URL.You can use mUrl as your content.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,**mUrl**);
startActivity(Intent.createChooser(intent,getString("your apps title")));
mUrl(String) replace with Your post content (String)...

In your full_post.class, receive the extra passed from adapter,then create a button as share and then add this
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent what = new Intent();
what.setAction(Intent.ACTION_SEND);
what.putExtra(Intent.EXTRA_TEXT, "Post Id:" + postId+ "\nPost
Title:" +postTitle);
what.setType("text/plain");
startActivity(Intent.createChooser(what, "Share with"));
}
});
where postId,postTitle are received as axtra from adapter class

Related

I am getting a nullpointer for my RecyclerView Possibly because of my context

I am writing this code in my RecyclerViewAdapter and I have a separate Java File from which I want to set an ItemOnClickListener and Context for my adapter class. However, they come out as null. This is the method from the Java File for the recyclerView.
public void update(){
userRef.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
String imageUrl;
String name;
String extra;
String ready;
String ingredients;
String id;
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for( int i = 0; i < list.size(); i++){
DocumentSnapshot documentSnapshot = list.get(i);
if(documentSnapshot.exists()){
Map<String, Object> favFood = documentSnapshot.getData();
name = favFood.get(KEY_NAME).toString();
imageUrl = favFood.get(KEY_URL).toString();
extra = favFood.get(KEY_XTRAINFO).toString();
ready = favFood.get(KEY_READY).toString();
Log.d("TAGG", ready);
ingredients = favFood.get(KEY_INGREDIENTS).toString();
id = favFood.get(KEY_ID).toString();
allFavoritedFoods.add(new FoodItem(imageUrl, name, ready, extra, ingredients, id, FirebaseAuth.getInstance().getCurrentUser().getUid()));
}
}
foodAdapter = new FoodAdapter(allFavoritedFoods, FavItem.this);
recyclerView.setAdapter(foodAdapter);
foodAdapter.setOnItemClickListener(FavItem.this);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
This is for the relevant code from the Adapter Class:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
private ArrayList<FoodItem> foodItems;
private Context context;
static String id;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
#Override
public int getItemCount() {
return foodItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView name, readyTime, ingredients, extraInfo;
public ImageView picture;
Button favBtn;
FirebaseFirestore db = FirebaseFirestore.getInstance();
public static final String KEY_URL = "imageUrl", KEY_INGREDIENTS = "ingredients", KEY_READY = "ready";
public static final String KEY_NAME = "name";
public static final String KEY_XTRAINFO = "info";
public static final String KEY_ID = "id";
public static final String KEY_FAV = "favorited";
//public Button favBtn;
public ViewHolder(View itemView){
super(itemView);
name = itemView.findViewById(R.id.title);
picture = itemView.findViewById(R.id.thumbnail);
readyTime = itemView.findViewById(R.id.readyInMinutes);
ingredients = itemView.findViewById(R.id.ingredients);
extraInfo = itemView.findViewById(R.id.extraInfo);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(mListener!=null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
mListener.onItemClick(position);
}
}
}
});
favBtn = itemView.findViewById(R.id.favBtn);
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
FoodItem foodItem = foodItems.get(position);
Map<String, Object> favFood = new HashMap<>();
favFood.put(KEY_NAME, foodItem.getTitle());
favFood.put(KEY_URL, foodItem.getImageUrl());
favFood.put(KEY_ID, foodItem.getId());
favFood.put(KEY_INGREDIENTS, foodItem.getIngredients());
favFood.put(KEY_READY, foodItem.getReadyTime());
favFood.put(KEY_XTRAINFO, foodItem.getExtraInfo());
db.collection(FirebaseAuth.getInstance().getCurrentUser().getEmail()).document(id+"").set(favFood)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(itemView.getContext(), "Added to Favorites", Toast.LENGTH_SHORT);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(itemView.getContext(), "Deleted From Favorites", Toast.LENGTH_SHORT);
Log.d("Error in Storing", e.toString());
}
});
}
});
}
}
public FoodAdapter(ArrayList<FoodItem> foodItems, Context context){
this.foodItems = foodItems;
this.context = context;
}
For the MainActivity.java, this worked, but foodAdapter.setOnItemClickListener(MainActivity.this);. But it isn't working similarly to the other Java File.
For the context what would I put and what would I put for the onItemClickListener for the method from the other Java File?
If you are writing update() method inside a fragment, pass context as follows.
foodAdapter = new FoodAdapter(allFavoritedFoods, getActivity());
If you are writing update() method inside an activity, pass context as follows.(assume activity name is MainActivity)
foodAdapter = new FoodAdapter(allFavoritedFoods, MainActivity.this);

Save Data from RecyclerView into SQLite DataBase

I'm making an app that gets image , text, url from json url in recyclerview and display the text and image in cardview. and when the user will click on the item it will open new webview activity and pass the url to this activity . everything work fine . but now i want to make a favorite list. when user click on button on the recyclerview item it will save this item data into the SQLite Database . I did everything as in Tutorials but it's not working
when i click on favbtn it's saying Failed . it means the data isn't saved in the database.
please any idea where is my mistake , I'm stuck on this for 3 days and can't find answer
here is my code
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context mContext;
private List<Model> modelList;
public RecyclerAdapter(Context context, List<Model> listData) {
this.modelList = listData;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Model model = modelList.get(position);
holder.title.setText(modelList.get(position).getTitle());
Picasso.get().load(modelList.get(position).getImage()).into(holder.imageView);
}
#Override
public int getItemCount() {
return modelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView imageView;
Button favBtn;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.Title);
imageView = itemView.findViewById(R.id.ImageView);
favBtn = itemView.findViewById(R.id.favBtn);
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHandler favDB = new DatabaseHandler(mContext);
int position = getAdapterPosition();
Model model = modelList.get(position);
favDB.insertIntoTheDataBase(model.getTitle(),
model.getImage().trim(),model.getUrl().trim());
}
});
itemView.setClickable(true);
mContext = itemView.getContext();
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Url = modelList.get(getAdapterPosition()).getUrl();
Intent i = new Intent(mContext, WebViewActivity.class);
i.putExtra("url1", modelList.get(getAdapterPosition()).getUrl());
mContext.startActivity(i);
}
});
}
}
}
DataBaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
Context context;
private static final String DATABASE_NAME = "Library.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_Demo = "Favorites";
private static final String KEY_ID = "id";
private static final String KEY_TITLE= "title";
private static final String KEY_IMAGE= "image";
private static final String KEY_URL= "url";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DEMO_TABLE = "CREATE TABLE " + TABLE_Demo +
" (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_TITLE + " TEXT, " +
KEY_IMAGE + " TEXT, " +
KEY_URL + " TEXT);";
db.execSQL(CREATE_DEMO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Demo);
onCreate(db);
}
public void insertIntoTheDataBase(String title, String image, String url){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, title);
values.put(KEY_IMAGE,image);
values.put(KEY_URL, url);
Long result = db.insert(TABLE_Demo , null, values);
if (result == -1){
Toast.makeText(context,"Failed", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context,"Added Successfully", Toast.LENGTH_LONG).show();
}
}
}
Model.java
public class Model {
String title, image, url ;
public Model() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public String getImage() {
return image;
}
public void setTitle(String title) {
this.title = title;
}
public void setImage(String image) {
this.image = image;
}
}
HomeFragment.java
public class HomeFragment extends Fragment {
private final String Data = "https://medicalibrary.net/wp-content/uploads/Allergy.json";
private RecyclerView recyclerView;
private JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
private ArrayList<Model> modelList = new ArrayList<>();
private RecyclerAdapter recyclerAdapter;
public static HomeFragment newInstans() {
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment_acivity, container, false);
recyclerView = view.findViewById(R.id.recyclerview2);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
httpGet();
return view;
}
private void httpGet() {
requestQueue = Volley.newRequestQueue(getContext());
jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Data, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
DatabaseHandler db = new DatabaseHandler (getContext());
try {
JSONObject jsonObject = response.getJSONObject(i);
Model model = new Model();
model.setTitle(jsonObject.getString("title"));
model.setImage(jsonObject.getString("image"));
model.setUrl(jsonObject.getString("url"));
modelList.add(model);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerAdapter = new RecyclerAdapter(getContext(), modelList);
recyclerView.setAdapter(recyclerAdapter);
// context of your activity or fragment
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Tag", "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(jsonArrayRequest);
}
}

I have one issue on ListView

I want to implement refine on my app where the item will come from server but in the below Custom_List class code only one item is coming and another item is shown as null.This is screenshot of items.
On this item I am retrieving id,age,height,communities,caste,occupation,education,income,location,pics.
public class RefineCustomList extends ArrayAdapter<String> {
private NetworkImageView imageView;
private ImageLoader imageLoader;
private final String[] ids;
private String[] ages;
private String[] heights;
public String[] communities;
public String[] castes;
public String[] educations;
public String[] occupations;
public String[] incomes;
public String[] pics;
public String[] locations;
public String[] shortlist;
public String[] expressinterest;
private Activity context;
public RefineCustomList(Activity context, String[] ids, String[] ages, String[] heights, String[] communities, String[] castes,
String[] educations, String[] occupations, String[]incomes, String[]pics, String[] locations,
String[] shortlist, String[] expressinterest) {
super(context, R.layout.list_view_layout,ids);
this.ids = ids;
this.ages = ages;
this.heights = heights;
this.communities = communities;
this.castes = castes;
this.educations = educations;
this.occupations = occupations;
this.incomes = incomes;
this.pics = pics;
this.locations = locations;
this.context = context;
this.shortlist = shortlist;
this.expressinterest = expressinterest;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.refine_custom_list, null, true);
String url1 = "https://www.maangal.com/thumb/thumb_";
String url =url1+pics[position];
imageView = (NetworkImageView) listViewItem.findViewById(R.id.offer_image);
imageLoader = CustomVolleyRequest.getInstance(this.getContext()).getImageLoader();
imageLoader.get(url, ImageLoader.getImageListener(imageView,R.drawable.image,android.R.drawable.ic_dialog_alert));
imageView.setImageUrl(url,imageLoader);
TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
textViewId.setText(ids[position]);
textViewName.setText( ages[position]+" years"+" , "+heights[position]+" cm"+", "+communities[position]+" : "+castes[position]+" , "+educations[position]+" , "+occupations[position]+" , "+incomes[position]+", "+locations[position]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), BlankActivity.class);
Toast.makeText(getContext(), ids[position], Toast.LENGTH_LONG).show();
i.putExtra("id", ids[position]);
v.getContext().startActivity(i);
}
});
Button btnSort =(Button) listViewItem.findViewById(R.id.btnshort);
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Shortlisted",Toast.LENGTH_LONG).show();
}
});
Button btnChat =(Button) listViewItem.findViewById(R.id.btnchat);
btnChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Chatting",Toast.LENGTH_LONG).show();
}
});
Button declineButton = (Button)listViewItem.findViewById(R.id.declineButton);
declineButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Decline",Toast.LENGTH_LONG).show();
}
});
return listViewItem;
}
}
This is the parsing code
public class RefineActivity extends FragmentActivity {
SessionManager session;
String email;
public String JSON_URL;
private ListView listView;
Button rfb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.refine_activity);
// Session class instance
session = new SessionManager(this);
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
Log.e("email==========>", email);
//JSON_URL = "http://10.0.2.2/xp/ei_sent_pending.php?matri_id="+email;
listView = (ListView) findViewById(R.id.listView);
rfb = (Button) findViewById(R.id.refineBtn);
rfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
RefineFragment ls_fragment = new RefineFragment();
ls_fragment.show(fragmentManager, "simple fragment");
}
});
Intent intent = getIntent();
final String response = getIntent().getExtras().getString("res");
Log.e("responde rfi", response);
showJSON(response);
}
protected void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
RefineCustomList cl = new RefineCustomList(this, ParseJSON.ids, ParseJSON.ages, ParseJSON.heights, ParseJSON.communities, ParseJSON.castes, ParseJSON.educations, ParseJSON.occupations, ParseJSON.incomes, ParseJSON.pics, ParseJSON.locations, ParseJSON.shortlist, ParseJSON.expressinterest);
listView.setAdapter(cl);
}
}
This is the Log where the item data is showing
responde rfi: {"result":[{"id":"Mgl11638","age":"21","height":"160","caste":"Brahmin","community":"Kumaoni","education":"MA","occupation":"Not Working","income":"Will tell later","pic":"Mgl11638.jpg","location":"Almora"},{"id":"Mgl16111","age":"22","height":"160","caste":"Brahmin","community":"Kumaoni","education":"B.Sc","occupation":"Student","income":"Will tell later","pic":"","location":"Almora"},{"id":"Mgl11658","age":"22","height":"154","caste":"Brahmin","community":"Kumaoni","education":"Undergraduate","occupation":"Student","income":"Will tell later","pic":"","location":"Lucknow"},{"id":"Mgl11621","age":"21","height":"134","caste":"Brahmin","community":"Kumaoni","education":"MA","occupation":"Not Working","income":"No income","pic":"","location":"Bareilly"}]}
Why do you use too much of Arrays inside an adapter? Just follow these steps.
Put all your strings inside an Object as single fields.
Pass that object as a parameter into your adapter from your Activity.
Fetch the details from that object in your adapter.
Then the adapter will automatically fetch you multiple data and populate into the list view. And my kind advice is to extend the class as BaseAdapter instead of ArrayAdapter
This is your object. I created it exclusively for you. Create a new java class(not an activity, just a .java file) and put this code inside.
public class DetailsObject implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String age;
private String height;
public String community;
public String caste;
public String education;
public String occupation;
public String income;
public byte[] pic;
public String location;
public String shortlist;
public String expressinterest;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getCommunity() {
return community;
}
public void setCommunity(String community) {
this.community = community;
}
public String getCaste() {
return caste;
}
public void setCaste(String caste) {
this.caste = caste;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getIncome() {
return income;
}
public void setIncome(String income) {
this.income = income;
}
public byte[] getPic() {
return pic;
}
public void setPic(byte[] pic) {
this.pic = pic;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getShortlist() {
return shortlist;
}
public void setShortlist(String shortlist) {
this.shortlist = shortlist;
}
public String getExpressinterest() {
return expressinterest;
}
public void setExpressinterest(String expressinterest) {
this.expressinterest = expressinterest;
}
}
In your adapter class change extends ArrayAdapter<String> to extends BaseAdapter, change all the String[] to String and in the constructor, juzt pass (Context context, DetailsObject detailObject) as parameter. And in your activity call the adapter like below:
RefineCustomList refineCustomList;
refineCustomList = new RefineCustomList(MainActivity.this,detailObject);
yourListView.setAdapter(refineCustomList);
Thats it..

recyclerView doesn't show the 'real' data for my list items

I have implemented a recyclerView and a SQLite database to save/retrieve data for the recylerview, but the data I get on the recyclerView is not the data that should show. The recyclerView worked as it should without the SQLite db.
When the plus sign is clicked, a dialog will popup with editext fields, where the user can type the information:
Here is the DialogFragment class where the user shall write their information:
public class DialogAdd extends DialogFragment {
private Button okButton;
private EditText name, quantity, location, normalPrice, offerPrice;
private List<ShopListItem> shopListItem;
private Context context;
DatabaseHelper dbHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbHelper = new DatabaseHelper(getContext());
shopListItem = new ArrayList<>();
context = getActivity();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.add_productdialog,container, false);
getDialog().setCanceledOnTouchOutside(false);
getDialog().setTitle("Add to shoplist");
name = (EditText) rootView.findViewById(R.id.dialog_productname);
quantity = (EditText) rootView.findViewById(R.id.dialog_qantity);
location = (EditText) rootView.findViewById(R.id.dialog_location);
normalPrice = (EditText) rootView.findViewById(R.id.dialog_normalPrice);
offerPrice = (EditText) rootView.findViewById(R.id.dialog_offerPrice);
okButton = (Button) rootView.findViewById(R.id.dialog_okButton);
okButton.getBackground().setColorFilter(Color.parseColor("#2fbd4b"), PorterDuff.Mode.MULTIPLY);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (name.getText().toString().isEmpty()) {
Toast.makeText(context, "You must add a name", Toast.LENGTH_LONG).show();
} else {
dbHelper.insertData(name.toString() ,quantity.toString(),location.toString(),normalPrice.toString(),offerPrice.toString());
getDialog().dismiss();
}
}
});
return rootView;
}
This is the mainActivity class where I create the recylerview, adapters and Database:
public class MainActivity extends AppCompatActivity{
private ImageButton addbutton;
private DialogAdd dialogAdd;
public static RecyclerView recyclerView;
private List<ShopListItem> shopListItems;
private SQLiteDatabase db;
private Cursor cursor;
private DatabaseHelper databaseHelper;
private ShoplistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppinglist_mainactivity);
databaseHelper = new DatabaseHelper(this);
addbutton = (ImageButton) findViewById(R.id.addbtn);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogAdd = new DialogAdd();
dialogAdd.show(getSupportFragmentManager(), "addDialog");
}
});
//RecyclerView
recyclerView = (RecyclerView)findViewById(R.id.rv_shoppinglist);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(App.getAppContex());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
initializeData();
adapter = new ShoplistAdapter(shopListItems);
recyclerView.setAdapter(adapter);
}
private void initializeData(){
shopListItems = new ArrayList<>();
Cursor resultset = databaseHelper.getAllData();
if (resultset.moveToFirst()){
while(!resultset.isAfterLast()){
shopListItems.add(new ShopListItem(resultset.getString(1), resultset.getString(2), resultset.getString(3), resultset.getString(4), resultset.getString(5)));
resultset.moveToNext();
}
}
resultset.close();
shopListItems.add(new ShopListItem("Potato", "2 KG", "MALL", "7 kr", ""));
}
This class is where the database is defined:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="dbshoplist.db";
public static final String TABLE_NAME ="product_table";
public static final String COL_ID = "ID";
public static final String COL_NAME ="NAME";
public static final String COL_QTY ="QUANTITY";
public static final String COL_LOCATION ="LOCATION";
public static final String COL_PRICE1 ="PRICE1";
public static final String COL_PRICE2 ="PRICE2";
/*
This constructor creates the database
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,QUANTITY TEXT,LOCATION TEXT,PRICE1 TEXT,PRICE2 TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String qty, String location, String price1, String price2){
SQLiteDatabase db = this.getWritableDatabase();
// content value is a row, and we fill it with the put();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_QTY, qty);
contentValues.put(COL_LOCATION, location);
contentValues.put(COL_PRICE1, price1);
contentValues.put(COL_PRICE2, price2);
long result = db.insert(TABLE_NAME, null,contentValues);
if(result == -1) {
return false;
}else{
return true;
}
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursorResults = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return cursorResults;
}
My recyclerView adapter class:
public class ShoplistAdapter extends RecyclerView.Adapter<ShoplistAdapter.ViewHolder>{
List<ShopListItem> shopListItems;
public ShoplistAdapter(List<ShopListItem> shopListItems) {
this.shopListItems = shopListItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View shoplist_itemView = inflater.inflate(R.layout.shop_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(shoplist_itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.location.setText(shopListItems.get(position).location.toString());
holder.normalPrice.setText(shopListItems.get(position).normalprice.toString());
holder.offerPrice.setText(shopListItems.get(position).offerprice.toString());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(shopListItems.get(position).quantity + " " + shopListItems.get(position).name);
holder.productname.setText(stringBuilder);
if(!shopListItems.get(position).offerprice.toString().isEmpty()){
holder.normalPrice.setPaintFlags(holder.normalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
if(shopListItems.get(position).normalprice.isEmpty()){
holder.normalPrice.setVisibility(View.GONE);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
holder.productname.setPaintFlags(holder.productname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.productname.setTextColor(Color.parseColor("#40000000"));
}else{
holder.productname.setPaintFlags(0 | Paint.ANTI_ALIAS_FLAG);
holder.productname.setTextColor(Color.BLACK);
}
}
});
}
#Override
public int getItemCount() {
return shopListItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private CheckBox checkBox;
private TextView productname, quantity, location, normalPrice, offerPrice;
private ImageButton edit_icon, delete_icon;
public ViewHolder(View itemView) {
super(itemView);
productname = (TextView)itemView.findViewById(R.id.product_name);
location = (TextView)itemView.findViewById(R.id.product_location);
normalPrice = (TextView)itemView.findViewById(R.id.product_price);
offerPrice = (TextView)itemView.findViewById(R.id.product_offer_price);
edit_icon = (ImageButton)itemView.findViewById(R.id.editShopItem_Icon);
delete_icon = (ImageButton)itemView.findViewById(R.id.shopitem_delete_icon);
checkBox = (CheckBox) itemView.findViewById(R.id.bought_checkbox);
}
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
This is happening because you're calling the toString() method of fields of the ShopListItem object: shopListItems.get(position).location.toString().
Instead, create getter methods for the fields of your ShopListItem class, e.g.
public getLocation() {
return location;
}
and just call these to get the data.

Hi i tried to add some details to android database. I created the table but i cant retrive the details in to list view

My Mainactivity is
public class MainActivity extends Activity {
private EditText title_name,head_name,content;
private Button saveButton;
private DatabaseHandler dba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dba=new DatabaseHandler(MainActivity.this);
title_name=(EditText)findViewById(R.id.editText_Title);
head_name=(EditText)findViewById(R.id.ediText_Name);
content=(EditText)findViewById(R.id.editText_Content);
saveButton=(Button)findViewById(R.id.button_Save);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveTodb();
}
});
}
private void saveTodb() {
Mywish wish=new Mywish();
wish.setTitle(title_name.getText().toString().trim());
wish.setHeadingName(head_name.getText().toString().trim());
wish.setContent(content.getText().toString().trim());
dba.addWishes(wish);
dba.close();
title_name.setText("");
head_name.setText("");
content.setText("");
Intent i =new Intent(MainActivity.this,DisplayItem.class);
startActivity(i);
}
}
and my Consatnts.java ,here i declared my Database variables and details`
public class Constants {
public static final String DATABASE_NAME="diary";
public static final int DATABASE_VERSION=1;
public static final String TABLE_NAME="details";
public static final String TITLE_NAME="title";
public static final String HEAD_NAME="headingname";
public static final String CONTENT_NAME ="content";
public static final String DATE_NAME="date";
public static final String KEY_ID="_id";
}
My DatabaseHandler class is
public class DatabaseHandler extends SQLiteOpenHelper{
private final ArrayList wishList=new ArrayList<>();
public DatabaseHandler(Context context ) {
super(context,Constants.DATABASE_NAME,null,Constants.DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DIARY_TABLE="CREATE TABLE "+Constants.TABLE_NAME + "("+Constants.KEY_ID +" INTEGER PRIMARY KEY,"+
Constants.TITLE_NAME + " TEXT,"+Constants.HEAD_NAME +" TEXT,"+ Constants.CONTENT_NAME+" TEXT,"+Constants.DATE_NAME +" INTEGER)";
db.execSQL(CREATE_DIARY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+Constants.TABLE_NAME);
onCreate(db);
}
public void addWishes(Mywish wish)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(Constants.TITLE_NAME,wish.getTitle());
values.put(Constants.HEAD_NAME,wish.getHeadingName());
values.put(Constants.CONTENT_NAME,wish.getContent());
values.put(Constants.DATE_NAME,java.lang.System.currentTimeMillis());
db.insert(Constants.TABLE_NAME, null, values);
Log.v("WISH SUCCESfuHOOO"," Hoo");
db.close();
}
public ArrayList<Mywish> getWishes()
{
String selectQuery="SELECT * FROM"+Constants.TABLE_NAME;
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query(Constants.TABLE_NAME,new String[]{Constants.KEY_ID,Constants.TITLE_NAME,Constants.HEAD_NAME,Constants.CONTENT_NAME,
Constants.DATE_NAME },null,null,null,null,null,Constants.DATE_NAME+"DESC" );
if (cursor.moveToFirst())
{
do {
Mywish wish=new Mywish();
wish.setTitle(cursor.getString(cursor.getColumnIndex(Constants.TITLE_NAME)));
wish.setHeadingName(cursor.getString(cursor.getColumnIndex(Constants.HEAD_NAME)));
wish.setContent(cursor.getString(cursor.getColumnIndex(Constants.CONTENT_NAME)));
java.text.DateFormat dateFormat=java.text.DateFormat.getDateInstance();
String datedata=dateFormat.format(new Date(cursor.getLong(cursor.getColumnIndex(Constants.DATE_NAME))).getTime());
wish.setDateRecorded(datedata);
wishList.add(wish);
}while (cursor.moveToNext());
}
return wishList;
}
}
Mywish class is used to declare data variables used in my app
public class Mywish {
public String Title;
public String DateRecorded;
public String Content;
public String HeadingName;
public String getContent() {
return Content;
}
public void setContent(String content) {
this.Content = content;
}
public String getDateRecorded() {
return DateRecorded;
}
public void setDateRecorded(String dateRecorded) {
this.DateRecorded = dateRecorded;
}
public String getHeadingName() {
return HeadingName;
}
public void setHeadingName(String headingName) {
this.HeadingName = headingName;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
this.Title = title;
}
}
Displayitem Class is used to display the details in to List view.I setup the adapter and everything but the values didnt get in to the List view.
public class DisplayItem extends Activity {
private DatabaseHandler dba;
private ArrayList<Mywish> dbwishes=new ArrayList<>();
private WishAdapter wishAdapter;
private ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_item);
Log.v("Dispaly act","DiSPLAYAVTIVIT");
listview=(ListView)findViewById(R.id.List);
referesData();
}
private void referesData() {
dbwishes.clear();
dba=new DatabaseHandler(getApplicationContext());
ArrayList<Mywish> wishesfrmDb=dba.getWishes();
for (int i=0;i<wishesfrmDb.size();i++)
{
String title=wishesfrmDb.get(i).getTitle() ;
String headname=wishesfrmDb.get(i).getHeadingName();
String content=wishesfrmDb.get(i).getContent();
String date=wishesfrmDb.get(i).getDateRecorded();
Mywish myWish=new Mywish();
myWish.setTitle(title);
myWish.setContent(content);
myWish.setHeadingName(headname);
myWish.setDateRecorded(date);
dbwishes.add(myWish);
}
dba.close();
wishAdapter =new WishAdapter(DisplayItem.this,R.layout.wish_row,dbwishes);
listview.setAdapter(wishAdapter);
}
public class WishAdapter extends ArrayAdapter<Mywish>
{
Activity activity;
int layoutResource;
Mywish wish;
ArrayList<Mywish> mData=new ArrayList<>();
public WishAdapter(Activity act, int resource, ArrayList<Mywish> data) {
super(act, resource, data);
activity=act;
layoutResource=resource;
mData=data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Mywish getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getPosition(Mywish item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row= convertView;
ViewHolder holder=null;
if (row==null ||(row.getTag()==null))
{
LayoutInflater inflater=LayoutInflater.from(activity);
row=inflater.inflate(layoutResource,null);
holder=new ViewHolder();
holder.mTitle=(TextView)row.findViewById(R.id.textView_listTitle);
holder.mHead=(TextView)row.findViewById(R.id.textView_listName);
holder.mDate=(TextView)row.findViewById(R.id.textView_listDate);
row.setTag(holder);
} else {
holder=(ViewHolder) row.getTag();
}
holder.myWish=getItem(position);
holder.mTitle.setText(holder.myWish.getTitle());
holder.mHead.setText(holder.myWish.getHeadingName());
holder.mDate.setText(holder.myWish.getDateRecorded());
return row;
}
class ViewHolder{
TextView mTitle;
TextView mHead;
TextView mDate;
TextView mId;
TextView mContent;
Mywish myWish;
}
}
}
My log is
Process: harico.databaseex, PID: 6329
java.lang.RuntimeException: Unable to start activity ComponentInfo{harico.databaseex/harico.databaseex.DisplayItem}: java.lang.IllegalArgumentException: invalid LIMIT clauses:date DESC
The same as Waqar Ahmed:
"Constants.DATE_NAME+"DESC", you didnt put space before "DESC"
And the parameters of your cursor are not well ordered, should be something like:
Cursor cursor=db.query(Constants.TABLE_NAME,new String[]{Constants.KEY_ID,Constants.TITLE_NAME,Constants.HEAD_NAME,Constants.CONTENT_NAME,Constants.DATE_NAME },null,null,null,null,Constants.DATE_NAME+" DESC", null);

Categories

Resources