Read Data from SQLite Databse in Another Activity using ID - android

I have already Read Data from Sqlite database in recyclerview
But when user click next_button it fetch more data from same row using BANK_ID
In First Activity I have read some data from sqlite database in recyclerView And When user click next_button its fetch more data from sqlite database using same row I've already pass BANK_ID which is autoIncrement
Here is my code...
DataModel Class
public class DataModel {
public String BANK_ID;
public String id;
public String farmer_insure_name;
public String farmer_bank_hypo;
public String farmer_name;
public String village;
public String taluka;
public String district;
public String tagging_date;
public String tag_no;
public String animal_species;
public String animal_breed;
public String body_color;
public String shape_right;
public String shape_left;
public String tail_switch;
public String other_marks;
public String prag_status;
public String lactations;
public String milk_qty;
public String sum_insured;
public String tag_photo;
public String head_photo;
public String left_photo;
public String right_photo;
public String farmer_photo;
public String getBANK_ID() {
return BANK_ID;
}
public void setBANK_ID(String BANK_ID) {
this.BANK_ID = BANK_ID;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFarmer_insure_name() {
return farmer_insure_name;
}
public void setFarmer_insure_name(String farmer_insure_name) {
this.farmer_insure_name = farmer_insure_name;
}
public String getFarmer_bank_hypo() {
return farmer_bank_hypo;
}
public void setFarmer_bank_hypo(String farmer_bank_hypo) {
this.farmer_bank_hypo = farmer_bank_hypo;
}
public String getFarmer_name() {
return farmer_name;
}
public void setFarmer_name(String farmer_name) {
this.farmer_name = farmer_name;
}
public String getVillage() {
return village;
}
public void setVillage(String village) {
this.village = village;
}
public String getTaluka() {
return taluka;
}
public void setTaluka(String taluka) {
this.taluka = taluka;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getTagging_date() {
return tagging_date;
}
public void setTagging_date(String tagging_date) {
this.tagging_date = tagging_date;
}
public String getTag_no() {
return tag_no;
}
public void setTag_no(String tag_no) {
this.tag_no = tag_no;
}
public String getAnimal_species() {
return animal_species;
}
public void setAnimal_species(String animal_species) {
this.animal_species = animal_species;
}
public String getAnimal_breed() {
return animal_breed;
}
public void setAnimal_breed(String animal_breed) {
this.animal_breed = animal_breed;
}
public String getBody_color() {
return body_color;
}
public void setBody_color(String body_color) {
this.body_color = body_color;
}
public String getShape_right() {
return shape_right;
}
public void setShape_right(String shape_right) {
this.shape_right = shape_right;
}
public String getShape_left() {
return shape_left;
}
public void setShape_left(String shape_left) {
this.shape_left = shape_left;
}
public String getTail_switch() {
return tail_switch;
}
public void setTail_switch(String tail_switch) {
this.tail_switch = tail_switch;
}
public String getOther_marks() {
return other_marks;
}
public void setOther_marks(String other_marks) {
this.other_marks = other_marks;
}
public String getPrag_status() {
return prag_status;
}
public void setPrag_status(String prag_status) {
this.prag_status = prag_status;
}
public String getLactations() {
return lactations;
}
public void setLactations(String lactations) {
this.lactations = lactations;
}
public String getMilk_qty() {
return milk_qty;
}
public void setMilk_qty(String milk_qty) {
this.milk_qty = milk_qty;
}
public String getSum_insured() {
return sum_insured;
}
public void setSum_insured(String sum_insured) {
this.sum_insured = sum_insured;
}
public String getTag_photo() {
return tag_photo;
}
public void setTag_photo(String tag_photo) {
this.tag_photo = tag_photo;
}
public String getHead_photo() {
return head_photo;
}
public void setHead_photo(String head_photo) {
this.head_photo = head_photo;
}
public String getLeft_photo() {
return left_photo;
}
public void setLeft_photo(String left_photo) {
this.left_photo = left_photo;
}
public String getRight_photo() {
return right_photo;
}
public void setRight_photo(String right_photo) {
this.right_photo = right_photo;
}
public String getFarmer_photo() {
return farmer_photo;
}
public void setFarmer_photo(String farmer_photo) {
this.farmer_photo = farmer_photo;
}
}
DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper {
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String DATABASE_NAME = "SNVINSURANCE.db";
public static final String TABLE_NAME_IMAGES = "images_table";
private static final int DATABASE_VERSION = 1;
private static final String IMAGES_TABLE = "ImagesTable";
public static final String COLUMN_ID = "ID";
public static final String BANK_COLUMN = "BANK_NAME";
public static final String INSURED_COLUMN = "INSURED_NAME";
public static final String BNAKHYPO_COLUMN = "BANKHYPO_NAME";
public static final String COLUMN_STATUS = "status";
public static final String FARMERNAME_ID = "ID";
public static final String SNV_ID = "SNV";
public static final String FARMERNAME_COLUMN = "FARMER_NAME";
public static final String VILLAGE_COLUMN = "VILLAGE";
public static final String TALUKA_COLUMN = "TALUKA";
public static final String DISTRICT_COLUMN = "DISTRICT";
public static final String TAGGING_DATE_COLUMN = "TAGGING_DATE";
public static final String ANIMAL_ID = "ID";
public static final String TAG_COLUMN = "TAG";
public static final String ANIMAL_SPECIES_COLUMN = "ANIMAL_SPECIES";
public static final String ANIMAL_BREED_COLUMN = "ANIMAL_BREED";
public static final String ANIMAL_BODY_COLOR_COLUMN = "ANIMAL_BODY_COLOR";
public static final String ANIMAL_SHAPE_RIGHT_COLUMN = "ANIMAL_SHAPE_RIGHT";
public static final String ANIMAL_SHAPE_LEFT_COLUMN = "ANIMAL_SHAPE_LEFT";
public static final String ANIMAL_SWITCH_OF_TAIL_COLUMN = "ANIMAL_SWITCH_OF_TAIL";
public static final String AGE_COLUMN = "AGE";
public static final String ANIMAL_OTHER_MARKS_COLUMN = "ANIMAL_OTHER_MARKS";
public static final String PRAG_STATUS_COLUMN = "PRAG_STATUS";
public static final String NUMBER_OF_LACTATION_COLUMN = "NUMBER_OF_LACTATION";
public static final String CURRENT_MILK_COLUMN = "CURRENT_MILK";
public static final String SUM_INSURED_COLUMN = "SUM_INSURED";
public static final String TAG_IMAGE_COLUMN = "TAG_IMAGE";
public static final String HEAD_IMAGE_COLUMN = "HEAD_IMAGE";
public static final String LEFT_SIDE_IMAGE_COLUMN = "LEFT_SIDE_IMAGE";
public static final String RIGHT_SIDE_IMAGE_COLUMN = "RIGHT_SIDE_IMAGE";
public static final String TAIL_IMAGE_COLUMN = "TAIL_IMAGE";
public static final String IDPROOF_IMAGE_COLUMN = "IDPROOF_IMAGE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME_IMAGES + "(BANK_ID INTEGER PRIMARY KEY AUTOINCREMENT,BANK_NAME TEXT,INSURED_NAME TEXT,BANKHYPO_NAME TEXT,FARMER_NAME TEXT,VILLAGE TEXT,TALUKA TEXT,DISTRICT TEXT,TAGGING_DATE DATE, TAG NUMBER,ANIMAL_SPECIES TEXT,ANIMAL_BREED TEXT,ANIMAL_BODY_COLOR TEXT,ANIMAL_SHAPE_RIGHT TEXT,ANIMAL_SHAPE_LEFT TEXT,ANIMAL_SWITCH_OF_TAIL TEXT,AGE NUMBER,ANIMAL_OTHER_MARKS TEXT,PRAG_STATUS TEXT,NUMBER_OF_LACTATION NUMBER,CURRENT_MILK NUMBER,SUM_INSURED NUMBER,TAG_IMAGE BLOB NOT NULL,HEAD_IMAGE BLOB NOT NULL,LEFT_SIDE_IMAGE BLOB NOT NULL,RIGHT_SIDE_IMAGE BLOB NOT NULL,TAIL_IMAGE BLOB NOT NULL,IDPROOF_IMAGE BLOB NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_IMAGES);
onCreate(db);
}
public boolean insertImage(String bank, String insurename, String bankhypo, String farmername, String village, String taluka, String district, String tagging_date, String tag, String animal_species, String animal_breeds, String animal_body_color, String shape_right, String shape_left, String tail, String age, String marks_other, String prag, String lactation, String current_milk, String sum, byte[] tag_image, byte[] head_image, byte[] left_image, byte[] right_image, byte[] tail_image, byte[] id_proof_image) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BANK_COLUMN, bank);
contentValues.put(INSURED_COLUMN, insurename);
contentValues.put(BNAKHYPO_COLUMN, bankhypo);
contentValues.put(FARMERNAME_COLUMN, farmername);
contentValues.put(VILLAGE_COLUMN, village);
contentValues.put(TALUKA_COLUMN, taluka);
contentValues.put(DISTRICT_COLUMN, district);
contentValues.put(TAGGING_DATE_COLUMN, tagging_date);
contentValues.put(TAG_COLUMN, tag);
contentValues.put(ANIMAL_SPECIES_COLUMN, animal_species);
contentValues.put(ANIMAL_BREED_COLUMN, animal_breeds);
contentValues.put(ANIMAL_BODY_COLOR_COLUMN, animal_body_color);
contentValues.put(ANIMAL_SHAPE_RIGHT_COLUMN, shape_right);
contentValues.put(ANIMAL_SHAPE_LEFT_COLUMN, shape_left);
contentValues.put(ANIMAL_SWITCH_OF_TAIL_COLUMN, tail);
contentValues.put(AGE_COLUMN, age);
contentValues.put(ANIMAL_OTHER_MARKS_COLUMN, marks_other);
contentValues.put(PRAG_STATUS_COLUMN, prag);
contentValues.put(NUMBER_OF_LACTATION_COLUMN, lactation);
contentValues.put(CURRENT_MILK_COLUMN, current_milk);
contentValues.put(SUM_INSURED_COLUMN, sum);
contentValues.put(TAG_IMAGE_COLUMN, tag_image);
contentValues.put(HEAD_IMAGE_COLUMN, head_image);
contentValues.put(LEFT_SIDE_IMAGE_COLUMN, left_image);
contentValues.put(RIGHT_SIDE_IMAGE_COLUMN, right_image);
contentValues.put(TAIL_IMAGE_COLUMN, tail_image);
contentValues.put(IDPROOF_IMAGE_COLUMN, id_proof_image);
long result = db.insert(TABLE_NAME_IMAGES, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public DatabaseHelper open() throws SQLException {
SQLiteDatabase db = this.getWritableDatabase();
return this;
}
public List<DataModel> getdata() {
// DataModel dataModel = new DataModel();
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select BANK_ID,BANK_NAME,INSURED_NAME,BANKHYPO_NAME,FARMER_NAME,VILLAGE,TALUKA,DISTRICT,TAGGING_DATE from " + TABLE_NAME_IMAGES + " ;", null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
dataModel = new DataModel();
String BANK_ID = cursor.getString(cursor.getColumnIndexOrThrow("BANK_ID"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("BANK_NAME"));
String country = cursor.getString(cursor.getColumnIndexOrThrow("INSURED_NAME"));
String city = cursor.getString(cursor.getColumnIndexOrThrow("BANKHYPO_NAME"));
String FARMER_NAME = cursor.getString(cursor.getColumnIndexOrThrow("FARMER_NAME"));
String VILLAGE = cursor.getString(cursor.getColumnIndexOrThrow("VILLAGE"));
String TALUKA = cursor.getString(cursor.getColumnIndexOrThrow("TALUKA"));
String DISTRICT = cursor.getString(cursor.getColumnIndexOrThrow("DISTRICT"));
String TAGGING_DATE = cursor.getString(cursor.getColumnIndexOrThrow("TAGGING_DATE"));
dataModel.setBANK_ID(BANK_ID);
dataModel.setId(name);
dataModel.setFarmer_insure_name(city);
dataModel.setFarmer_bank_hypo(country);
dataModel.setFarmer_name(FARMER_NAME);
dataModel.setVillage(VILLAGE);
dataModel.setTaluka(TALUKA);
dataModel.setDistrict(DISTRICT);
dataModel.setTagging_date(TAGGING_DATE);
stringBuffer.append(dataModel);
// stringBuffer.append(dataModel);
data.add(dataModel);
}
for (DataModel mo : data) {
Log.e("Hellomo", "" + mo.getFarmer_insure_name());
}
//
return data;
}
}
First Activity Class
public class SyncAllActivity extends AppCompatActivity {
Cursor model = null;
Cursor mode = null;
MyCustomAdapter adapter = null;
Button show;
DatabaseHelper database;
private RecyclerView recyclerview;
RecycleAdapter recycler;
List<DataModel> datamodel;
private ProgressDialog pdialog;
Context context;
private RecyclerView.LayoutManager mLayoutManager;
private MyCustomAdapter myCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sync_all_activity);
context = this;
datamodel = new ArrayList<DataModel>();
recyclerview = findViewById(R.id.recycle);
database = new DatabaseHelper(SyncAllActivity.this);
datamodel = database.getdata();
recycler = new RecycleAdapter(datamodel);
Log.e("data", "" + datamodel);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView bank_company, insured_name, bank_hypo;
CardView cardView;
MaterialRippleLayout next_button_main_activity;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
bank_company = itemView.findViewById(R.id.tvInsuranceList);
insured_name = itemView.findViewById(R.id.tvInsuredName);
bank_hypo = itemView.findViewById(R.id.tvBankHypo);
cardView = itemView.findViewById(R.id.cardViewMain);
next_button_main_activity = itemView.findViewById(R.id.next_button_main_activity);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.sam1
, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(final MyCustomAdapter.MyViewHolder holder, final int position) {
final DataModel dataModel = moviesList.get(position);
holder.bank_company.setText(dataModel.getId());
holder.insured_name.setText(dataModel.getFarmer_insure_name());
holder.bank_hypo.setText(dataModel.getFarmer_bank_hypo());
holder.cardView.setVisibility(View.VISIBLE);
holder.next_button_main_activity.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, SyncFarmerActivity.class);
intent.putExtra("BANK_ID", moviesList.get(position).getBANK_ID() + "");
Log.e("id", moviesList.get(position).getBANK_ID() + "");
startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
}
Second Activity Class
public class SyncFarmerActivity extends AppCompatActivity {
Button show;
DatabaseHelper database;
private RecyclerView recyclerview;
RecycleAdapter recycler;
List<DataModel> datamodel;
String id;
Context context;
private RecyclerView.LayoutManager mLayoutManager;
private MyCustomAdapter myCustomAdapter;
DataModel dataModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_farmer);
context = this;
Intent i = getIntent();
id = i.getStringExtra("BANK_ID");
Log.e("BANK_ID", id + "");
datamodel = new ArrayList<DataModel>();
recyclerview = findViewById(R.id.recycle);
database = new DatabaseHelper(SyncFarmerActivity.this);
datamodel = database.getdata();
recycler = new RecycleAdapter(datamodel);
Log.e("HIteshdata", "" + datamodel);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvFarmerName, tvCity, tvTaluka, farmer_name, tvDistrict, tvTaggingDate, district, tagging_date;
CardView cardView;
MaterialRippleLayout next_button_main_activity;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
tvFarmerName = itemView.findViewById(R.id.tvFarmerName);
tvCity = itemView.findViewById(R.id.tvCity);
tvTaluka = itemView.findViewById(R.id.tvTaluka);
tvDistrict = itemView.findViewById(R.id.tvDistrict);
tvTaggingDate = itemView.findViewById(R.id.tvTaggingDate);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.sam
, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(MyCustomAdapter.MyViewHolder holder, final int position) {
DataModel dataModel = moviesList.get(position);
holder.tvFarmerName.setText(dataModel.getFarmer_name());
holder.tvCity.setText(dataModel.getVillage());
holder.tvTaluka.setText(dataModel.getTaluka());
holder.tvDistrict.setText(dataModel.getDistrict());
holder.tvTaggingDate.setText(dataModel.getTagging_date());
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
}
Can anyone help me..
Thank You in advance.

You have to create another method in your Database class to select values from specific id that you are passing from first activity like:
DatabaseHelper Class
public List<DataModel> getSpecificData(String id) {
// DataModel dataModel = new DataModel();
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select BANK_ID,BANK_NAME,INSURED_NAME,BANKHYPO_NAME,FARMER_NAME,VILLAGE,TALUKA,DISTRICT,TAGGING_DATE from " + TABLE_NAME_IMAGES + "WHERE BANK_ID = " + id + ";", null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
//Rest of your code
return data;
}
And use this method in your second activity like
Intent i = getIntent();
id = i.getStringExtra("BANK_ID");
database = new DatabaseHelper(SyncFarmerActivity.this);
datamodel = database.getSpecificData(id);

Related

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

views not populating in gridlayout recyclerview

I am trying to load data from an api online but am having an issue with the views loading. When I try to run the emulator, a blank screen shows up. Any idea why? I am guessing my issue is somewhere within how I am loading the gridview but I have not been able to figure it out.
MainActivity
public class MainActivity extends AppCompatActivity {
String SEARCH_TERM = "popular";
private RecyclerView mRecyclerView;
private MovieAdapter mMovieAdapter;
private GridLayoutManager gridLayoutManager;
private List<Movie> movieData;
/*
API KEY
https://api.themoviedb.org/3/movie/550?api_key=1f5029b7d824dee72f4d4a156dac90ed
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
gridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
mMovieAdapter = new MovieAdapter(this, movieData);
mRecyclerView.setAdapter(mMovieAdapter);
movieData = new ArrayList<>();
loadMovieData();
}
private void loadMovieData() {
new FetchMovieTask().execute(SEARCH_TERM);
}
public class FetchMovieTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
final String MOVIES_RESULTS = "results";
final String MOVIES_POSTER_IMAGE = "poster_path";
final String MOVIES_TITLE = "title";
final String RELEASE_DATE = "release_date";
URL moviesUrl = NetworkUtils.buildUrl(SEARCH_TERM);
try {
String jsonMoviesResponse = NetworkUtils.getReponseFromHttpUrl(moviesUrl);
JSONObject moviesJson = new JSONObject(jsonMoviesResponse);
JSONArray moviesArray = moviesJson.getJSONArray(MOVIES_RESULTS);
for (int i = 0; i < moviesArray.length(); i++) {
String moviePoster;
String movieTitle;
String movieReleaseDate;
JSONObject movie = moviesArray.getJSONObject(i);
moviePoster = ("http://image.tmdb.org/t/p/w185/" + movie.getString(MOVIES_POSTER_IMAGE));
movieTitle = movie.getString(MOVIES_TITLE);
movieReleaseDate = movie.getString(RELEASE_DATE);
Log.i("MoviteTitle", movieTitle);
Log.i("ReleaseDate", movieReleaseDate);
Log.i("Image", moviePoster);
Movie data = new Movie(movieTitle, movieReleaseDate, moviePoster);
movieData.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
mMovieAdapter.notifyDataSetChanged();
}
}
}
Adapter Class
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieAdapterViewHolder>{
private List<Movie> mMovieData;
private Context context;
public MovieAdapter(Context context, List<Movie> movieData) {
this.context = context;
this.mMovieData = movieData;
}
#Override
public void onBindViewHolder(#NonNull MovieAdapterViewHolder holder, int position) {
holder.mTitleTextView.setText(mMovieData.get(position).getTitle());
holder.mReleaseDateTextView.setText(mMovieData.get(position).getDate());
Picasso.with(context).load(mMovieData.get(position).getMoviePoster()).into(holder.mImageView);
}
#NonNull
#Override
public MovieAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.cardview_item, parent, false);
return new MovieAdapterViewHolder(view);
}
#Override
public int getItemCount() {
if (null == mMovieData)
return 0;
return mMovieData.size();
}
public class MovieAdapterViewHolder extends RecyclerView.ViewHolder {
public final TextView mTitleTextView;
public final TextView mReleaseDateTextView;
public final ImageView mImageView;
public MovieAdapterViewHolder(View itemView) {
super(itemView);
mTitleTextView = itemView.findViewById(R.id.title_text_view);
mReleaseDateTextView = itemView.findViewById(R.id.release_date_text_view);
mImageView = itemView.findViewById(R.id.image_data);
}
}
}
Movie Class
public class Movie {
private String Title;
private String Date;
private String MoviePoster;
public Movie(String title, String date, String moviePoster) {
Title = title;
Date = date;
MoviePoster = moviePoster;
}
public Movie() {
}
public String getTitle() {
return Title;
}
public String getDate() {
return Date;
}
public String getMoviePoster() {
return MoviePoster;
}
public void setTitle(String title) {
Title = title;
}
public void setDate(String date) {
Date = date;
}
public void setMoviePoster(String moviePoster) {
MoviePoster = moviePoster;
}
}
Info : Java is all pass by value.
Issue : you are passing empty list reference to adapter and later initialising the list but in adapter it is still null so adapter will never receive the added value in list so do
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
gridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(gridLayoutManager);
movieData = new ArrayList<>();
//^^^^^^^^^^^^^^^^^^^^^^^^^ do it before
mMovieAdapter = new MovieAdapter(this, movieData);
mRecyclerView.setAdapter(mMovieAdapter);
loadMovieData();

display json data letest record as per user id

i wont to display the list of chats of clients.the data is come from json,
the last message of chat is display on chat.but it displays all message of all clients in list.like
here is my ListMessage.class activity
public class ListMessage extends AppCompatActivity implements View.OnClickListener {
ImageButton btnFooter_Home, btnFooter_Message, btnFooter_Notification, btnFooter_More;
EditText textUser;
List<Msg_data> msgList;
ListView lv;
String uri = "http://staging.talentslist.com/api/user/23/chat";
LinearLayout linear_Home, linear_Message, linear_Notification, linear_More;
GlobalClass myGlog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_message);
myGlog = new GlobalClass(getApplicationContext());
setFooter();
lv = (ListView) findViewById(R.id.listView);
textUser = (EditText) findViewById(R.id.textUser);
// textUser.isFocused()
boolean inConnected = myGlog.isNetworkConnected();
if (inConnected) {
requestData(uri);
}
}
public void requestData(String uri) {
StringRequest request = new StringRequest(uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
lv.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ListMessage.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
}
MsgAdapter.java class
public class MsgAdapter extends BaseAdapter{
private Context context;
private List<Msg_data> nList;
private LayoutInflater inflater = null;
private LruCache<Integer, Bitmap> imageCache;
private RequestQueue queue;
String isread;
public MsgAdapter(Context context, List<Msg_data> list) {
this.context = context;
this.nList = list;
inflater = LayoutInflater.from(context);
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
imageCache = new LruCache<>(cacheSize);
queue = Volley.newRequestQueue(context);
}
public class ViewHolder {
TextView __isread;
TextView _username;
TextView _detais;
TextView _time;
ImageView _image;
}
#Override
public int getCount() {
return nList.size();
}
#Override
public Object getItem(int position) {
return nList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
final Msg_data msg = nList.get(position);
final ViewHolder holder;
isread = msg.getIs_read();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_notification, null);
if (isread.equals("0")) {
convertView.setBackgroundColor(Color.parseColor("#009999"));
}
holder = new ViewHolder();
holder._username = (TextView) convertView.findViewById(R.id.tvtitle);
holder._detais = (TextView) convertView.findViewById(R.id.tvdesc);
holder.__isread = (TextView) convertView.findViewById(R.id.tvplateform);
holder._time = (TextView) convertView.findViewById(R.id.createdTime);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder._username.setText(msg.getUser_name().toString());
holder._detais.setText(msg.getMessage().toString());
holder._time.setText(msg.getCreated_at().toString());
// holder.__isread.setText(notifi.getIs_read().toString());
holder._image = (ImageView) convertView.findViewById(R.id.gameImage);
Glide.with(context)
.load(msg.getImage_link().toString()) // Set image url
.diskCacheStrategy(DiskCacheStrategy.ALL) // Cache for image
.into(holder._image);
return convertView;
}
}
Msg_data.java class
public class Msg_data {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
}
MsgJSONParser.java class
public class MsgJSONParser {
static List<Msg_data> notiList;
public static List<Msg_data> parseData(String content) {
JSONArray noti_arry = null;
Msg_data noti = null;
try {
JSONObject jsonObject = new JSONObject(content);
noti_arry = jsonObject.getJSONArray("data");
notiList = new ArrayList<>();
for (int i = 0; i < noti_arry.length(); i++) {
JSONObject obj = noti_arry.getJSONObject(i);
//JSONObject obj = noti_arry.getJSONObject(i);
noti = new Msg_data();
noti.setId(obj.getInt("id"));
noti.setMessage(obj.getString("message"));
noti.setUser_name(obj.getString("user_name"));
noti.setFrom(obj.getString("from"));
noti.setTo(obj.getString("to"));
noti.setCreated_at(obj.getString("created_at"));
noti.setImage_link(obj.getString("image_link"));
noti.setIs_read(obj.getString("is_read"));
notiList.add(noti);
}
return notiList;
} catch (JSONException ex) {
ex.printStackTrace();
return null;
}
}
}
please give me some idea what to do and how to do
i guess, you should replace
msgList = MsgJSONParser.parseData(response);
MsgAdapter adapter = new MsgAdapter(ListMessage.this, msgList);
with
msgList = MsgJSONParser.parseData(response);
ArrayList<Msg_data> userList=new ArrayList();
for (int i=0;i<msgList.size();i++){
if (!userList.contains(msgList.get(i)))
userList.add(msgList.get(i));
else {
int index=userList.indexOf(msgList.get(i));
if (userList.get(index).compareTo(msgList.get(i))>0)
userList.add(msgList.get(i));
}
}
MsgAdapter adapter = new MsgAdapter(ListMessage.this, userList);`
and implement Comparable and override equals method in your Msg_data class
public class Msg_data implements Comparable {
public int id;
public String user_id;
public String user_name;
public String message;
public String is_read;
public String image_link;
public String created_at;
public String from;
public String to;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIs_read() {
return is_read;
}
public void setIs_read(String is_read) {
this.is_read = is_read;
}
public String getImage_link() {
return image_link;
}
public void setImage_link(String image_link) {
this.image_link = image_link;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public Msg_data() {
}
public Msg_data(int id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
try
{
return (this.getUser_id().equals(( (Msg_data)obj).getUser_id()));
}
catch(NullPointerException e){
return false;
}
}
#Override
public int compareTo(#NonNull Object o) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("your pattern here");
try {
Date date=simpleDateFormat.parse(created_at);
Date dateOtherObject=simpleDateFormat.parse(((Msg_data)o).getCreated_at());
return date.compareTo(dateOtherObject);
}
catch (ParseException e){
return -1;
}
}
something like this:) Dont forget replace simple date format in compare method

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..

Endless pagination listview Android with database

I need to implement an endless pagination listview in my code, I've searched online and I saw a lot of examples, but none of them is using database, my app does the following:
it connects to an API and retrieves the data with json and show it in a listview, ok that works fine, but I want that listview to have an infinite scroll, like the facebook one.
I don't want anyone to write the code for me, I'm asking to someone guide me on wich is the better way to achieve that, I'll share some of my code, so you can understand:
try {
//Repositorio is my database
Repositorio mRepositorio = new Repositorio(getActivity());
List listaDeClientes = mRepositorio.getClientes();
System.out.println(listaDeClientes);
TextView total = (TextView) rootView.findViewById(R.id.totalClientes);
total.setText(getTotalClientes(mRepositorio.getTotalRegistros("clientes")));
final ArrayAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item, listaDeClientes);
ListView lv = (ListView) rootView.findViewById(R.id.listaClientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setAdapter(ad);
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
ClienteViewAdapter:
public class ClienteViewAdapter extends ArrayAdapter<ClienteModel> {
private final LayoutInflater inflater;
private final int resourceId;
public ClienteViewAdapter(Context context, int resource, List<ClienteModel> objects) {
super(context, resource, objects);
this.inflater = LayoutInflater.from(context);
this.resourceId = resource;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ClienteModel mClienteModel = getItem(position);
view = inflater.inflate(resourceId, parent, false);
TextView tvId = (TextView) view.findViewById(R.id.clienteId);
TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);
tvId.setText(String.valueOf(mClienteModel.getClientes_id()));
tvNome.setText(mClienteModel.getNome());
tvTipo.setText(mClienteModel.getTipo());
return view;
}
}
Model:
public class ClienteModel implements Serializable {
private static final long serialVersionUID = 1L;
private Integer clientes_id;
private Integer id_rm;
private Integer credencial_id;
private String nome;
private String tipo;
private String informacao_adicional;
private String _criado;
private String _modificado;
private String _status;
public Integer getClientes_id() {
return clientes_id;
}
public void setClientes_id(Integer clientes_id) {
this.clientes_id = clientes_id;
}
public Integer getId_rm() {
return id_rm;
}
public void setId_rm(Integer id_rm) {
this.id_rm = id_rm;
}
public Integer getCredencial_id() {
return credencial_id;
}
public void setCredencial_id(Integer credencial_id) {
this.credencial_id = credencial_id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getInformacao_adicional() {
return informacao_adicional;
}
public void setInformacao_adicional(String informacao_adicional) {
this.informacao_adicional = informacao_adicional;
}
public String get_criado() {
return _criado;
}
public void set_criado(String _criado) {
this._criado = _criado;
}
public String get_modificado() {
return _modificado;
}
public void set_modificado(String _modificado) {
this._modificado = _modificado;
}
public String get_status() {
return _status;
}
public void set_status(String _status) {
this._status = _status;
}
public static String[] getColunas() {
return Colunas;
}
public static void setColunas(String[] colunas) {
Colunas = colunas;
}
public static String[] Colunas = new String[]{
Coluna.CLIENTES_ID,
Coluna.ID_RM,
Coluna.CREDENCIAL_ID,
Coluna.NOME,
Coluna.TIPO,
Coluna.INFORMACAO_ADICIONAL,
Coluna._CRIADO,
Coluna._MODIFICADO,
Coluna._STATUS
};

Categories

Resources