I have database 1 contains all books data (name,id,description , and so on)
and i have another database contains id of books i added to favorite
i get the data in asynctask
first i get all books data from the first database and add them in Arraylist<Book> then i get the ids of favorite books ids from the second database and add them in Arraylist<Integer> and then compare and add a parameter in books to 1 if it's in favourite
#Override
protected ArrayList<Book> doInBackground(Void... params) {
ArrayList<Book> bookList = new ArrayList<>();
ArrayList<Integer> favlist = new ArrayList<>();
ArrayList<Integer> downlist = new ArrayList<>();
try {
if (mDBAdapter != null) {
mDBAdapter.createDataBase();
mDBAdapter.openDataBase();
bookList = mDBAdapter.selectAllBooks();
}
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
if (mAnnotationDBAdapter!=null) {
favlist = mAnnotationDBAdapter.selectAllFavourite();
}
for (int j = 0; j <bookList.size() ; j++) {
for (int i = 0; i <favlist.size() ; i++) {
if (bookList.get(j).getId()==favlist.get(i))
bookList.get(j).setInFavourite(1);
}
}
return bookList;
}
#Override
protected void onPostExecute(ArrayList<Book> books) {
super.onPostExecute(books);
if (books != null && books.size() > 0) {
Intent mainActivityintent = new Intent(mContext, Main2Activity.class);
mainActivityintent.putExtra(AppConstance.ALL_BOOKS_KEY,books);
mContext.startActivity(mainActivityintent);
}
}
here books list is ok and has infavourite parameter = 1 if the book is in favorite table
but when i receive it in main activity
i got infavourite = 0
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
PublicMethod.mDBAdapter = new AnnotationDBAdapter(this);
Intent intent = getIntent();
if (intent != null) {
if (intent.hasExtra(AppConstance.ALL_BOOKS_KEY)) {
mBooks = intent.getParcelableArrayListExtra(AppConstance.ALL_BOOKS_KEY) ;
//here all book have infavourite = 0
}
}
I think you need to use Intent.putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)
Related
I'm trying to compare two lists. First list has values from switches of class1 and the other list I'm trying to retreive it from a site (class2). I'm trying to compare those two lists but if statement returns no. For example
I'm checking the soy switch and when I scan a barcode the fetched list has soy in it but text returns no. Help me please!
Here is the code that I wrote.
Class1
public ArrayList<String> soy2= new ArrayList<String>();
Switch soy;
.....................
if (soy.isChecked()) {
checked();
}
else {
textView.setText("blahblah");
}
public void checked() {
soy2.add("Soy");
soy2.add("Σόγια");
soy2.add("soja");
soy2.add("Soybeans");
soy2.add("soybeans");
soy2.add("en:soybeans");
//checkedAllergens.add(soy2);
}
public ArrayList<String> getList() {
return soy2;
}
Class2
public Manage checkd;
String fetchedAllergens=new String();
List<String> fetchedAllergensList = new ArrayList<String>();
.......................
public void test() {
checkd = new Manage();
ArrayList<String> list = checkd.getList();
System.out.println(list);
System.out.println(fetchedAllergensList);
if(fetchedAllergensList.contains(list))
{
testtxt.setText("yes");
}
else
{
testtxt.setText("no");
}
//Test method is calling by a click listener and i get the list from class 2 with the code below
protected String doInBackground(String... strings) {
final String barcode = strings[0];
#Nullable
String allergens = null;
try {
final String jsonStr = Jsoup.connect(
"https://world.openfoodfacts.org/api/v0/product/" + barcode + ".json")
.ignoreContentType(true)
.execute()
.body();
final JSONObject jsonObj = new JSONObject(jsonStr);
if (jsonObj.has("product")) {
JSONObject productNode = jsonObj.getJSONObject("product");
allergens = productNode.getString("allergens");
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
fetchedAllergens=allergens;
fetchedAllergensList = Arrays.asList(fetchedAllergens.split(","));
System.out.print(fetchedAllergensList);
return allergens;
}
Here if(fetchedAllergensList.contains(list))
.contains() is expecting an element of your list not an arraylist
ex.
fetchedAllergensList.contains("Soy")
If you want to compare two list, try this
listA.containsAll(listB) && listB.containsAll(listA)
compare lists if equal
To check if list2 contains element that is also present in list1
public boolean elementExist(ArrayList<String> list1, ArrayList<String> list2) {
for (int i= 0; i < list2.length() i++) {
if (list1.contains(list2[i])) {
// element list2[i] exist in list1
return true;
}
}
return false;
}
This method will return true if list2 has element that is also in list1
Hi Now I'm retrieving data to spinner dynamically, but now it displaying some id's but those Id details are stored in other table, I want display those details in the spinner instead of id. And if I select particular product in spinner according that product details should display in list.
I'm using Retrofit method for retrieving data from server
package cfirst.live.com.activity;
public class Pos_outlet extends AppCompatActivity implements RestCallback,View.OnClickListener{
Spinner spinner;
ArrayList<String> products;
String numberAsString, product_name;
int i;
private int cartProductNumber = 0;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pos_outlet);
sharedPreference = new MySharedPreference(Pos_outlet.this);
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
initViews();
}
private void initViews() {
row1 =(TableRow)findViewById(R.id.row1);
spinner=(Spinner)findViewById(R.id.spinner);
POSStoreID = (TextView) findViewById(R.id.POSStoreID);
POSLocationID = (TextView) findViewById(R.id.POSLocationID);
Intent intent = getIntent();
id = intent.getStringExtra("id");
index_id= intent.getStringExtra("index_id");
callStoreDetaislsAPI();
callSmbProductsAPI();
getProductAPI();
}
// **Using this api I'm setting id'd to spinner**
private void getProductAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("store", index_id);
Toast.makeText(getApplicationContext(),index_id, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getproductlist(map, new MyCallback<List<PosmultistoresModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Finding products....", GlobalVariables.SERVICE_MODE.GET_PRODUCTS));
}
// **this API have product Id's Details**
private void callSmbProductsAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("index_id", product);
//Toast.makeText(getApplicationContext(),added_by, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getSmbProduct(map, new MyCallback<List<PosSmbProductModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Fetching details....", GlobalVariables.SERVICE_MODE.SMB_PRODUCT));
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.AddtoBasket:
callPosProductsAPI();
callSmbProductsAPI();
break;
}
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
//Toast.makeText(getApplication(),"failure",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode) {
switch (mode) {
//** I'm setting data to spinner **
case GET_PRODUCTS:
try {
List<PosmultistoresModel> businessgroups = (List<PosmultistoresModel>) response.body();
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
ArrayAdapter<String> adapter1;
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, items);
//setting adapter to spinner
spinner.setAdapter(adapter1);
} catch (Exception e) {
e.printStackTrace();
}
break;**
// ** Product id details (title, image, etc) Api
case SMB_PRODUCT:
try {
ArrayList<PosSmbProductModel> products = (ArrayList<PosSmbProductModel>) response.body();
//Product_id = products.get(0).getProduct();
// for (int i = 0; i < products(); i++) {
Title = products.get(0).getTitle();
productname1.setText(Title);
imageid12 = products.get(0).getMain_image();
Picasso.with(this).load("https://www.consumer1st.in/pre_production/uploads/" + imageid12).into(imageid1);
}
// }
catch(Exception e)
{
e.printStackTrace();
}
break;
}
}
}
I am assuming that your product_name = businessgroups.get(0).getProduct(); is getting a pruduct.
First of all please remove this part
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
then can you try
ArrayList<String> productList = new ArrayList<>();
for (int i = 0; i < businessgroups.size(); i++) {
productList.add(businessgroups.get(i).getProduct());
}
And finally
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, productList);
im trying to get data from a server inform of JSON and im storing the data to my offline database ( in this case : Realm ), whenever i try to retrieve the data, nothing is displayed in the listview.
public class MainActivity extends AppCompatActivity {
public static ListView myList;
public static ListAdapter myAdapter;
public static Realm realm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm.init(this);
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Recipe> dRecipies = realm.where(Recipe.class).findAll();
if(dRecipies!= null)dRecipies.deleteAllFromRealm();
}
});
DownloadTask newTask = new DownloadTask();
newTask.execute("hi");
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.Recipe_list);
// getData();
setDisplay();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String p = String.valueOf(position);
Intent in = new Intent(MainActivity.this, SecondScreenDetails.class);
in.putExtra("Position", p);
startActivity(in);
}
});
}
public void setDisplay(){
ArrayList<Recipe> finalRecipies = new ArrayList<>();
RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();
for(Recipe r: rrRecipies){
finalRecipies.add(r);
Toast.makeText(this, r.getName(), Toast.LENGTH_SHORT).show();
}
myAdapter = new ListViewAdapter(this, finalRecipies);
myList.setAdapter(myAdapter);
}
#Override
protected void onDestroy() {
realm.close();
super.onDestroy();
}
}
im doing this because, if i dont, the data keeps getting repeatedly stored, resulting in repetition.
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Recipe> dRecipies = realm.where(Recipe.class).findAll();
if(dRecipies!= null)dRecipies.deleteAllFromRealm();
}
});
when i tried without actually deleting the data, then the Toast in the
setDisplay() method is working and the data is being shown.(Toasts are repeated as i open the app second time, it gets twice... etc)
When i insert this, even the toasts dont show up.
My download activity
public class DownloadTask extends AsyncTask<String,Void,String> {
private RealmList<Recipe> realmRecipe = new RealmList<>();
String result;
#Override
protected String doInBackground(String... params) {
result = "";
Realm realm = null;
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json").build();
try {
result = client.newCall(request).execute().body().string();
Log.i("RESULT", result);
JSONArray rootArray = new JSONArray(result);
for (int i = 0; i < rootArray.length(); i++) {
JSONObject tempObject = rootArray.getJSONObject(i);
JSONArray jIngredients = tempObject.getJSONArray("ingredients");
JSONArray jSteps = tempObject.getJSONArray("steps");
// Get the ingredients
List<Ingredients> ingredients = new ArrayList<>();
for (int j = 0; j < jIngredients.length(); j++) {
JSONObject tempIngredient = jIngredients.getJSONObject(j);
Ingredients nIngredient = realm.createObject(Ingredients.class);
nIngredient.setIngredient(tempIngredient.getString("ingredient"));
nIngredient.setMeasure(tempIngredient.getString("measure"));
nIngredient.setQuantity(tempIngredient.getString("quantity"));
// Ingredients newIngredient = new Ingredients(tempIngredient.getString("quantity"),
// tempIngredient.getString("measure"),
// tempIngredient.getString("ingredient"));
// ingredients.add(newIngredient);
ingredients.add(nIngredient);
}
// Get the steps
List<Steps> steps = new ArrayList<>();
for (int j = 0; j < jSteps.length(); j++) {
JSONObject tempStep = jSteps.getJSONObject(j);
Steps nStep = realm.createObject(Steps.class);
nStep.setDescription(tempStep.getString("description"));
nStep.setId(tempStep.getString("id"));
nStep.setShortDescription(tempStep.getString("shortDescription"));
nStep.setVideoURL(tempStep.getString("videoURL"));
steps.add(nStep);
// Steps newStep = new Steps(tempStep.getString("id"), tempStep.getString("shortDescription"),
// tempStep.getString("description"), tempStep.getString("videoURL"));
// steps.add(newStep);
}
// Create the recipe
Recipe nRecipe = realm.createObject(Recipe.class);
nRecipe.setId(tempObject.getString("id"));
nRecipe.setName(tempObject.getString("name"));
nRecipe.setServings(tempObject.getString("servings"));
nRecipe.setIngredients(ingredients);
nRecipe.setSteps(steps);
realmRecipe.add(nRecipe);
// Recipe newRecipe = new Recipe(tempObject.getString("id"), tempObject.getString("name"), tempObject.getString("servings"), ingredients, steps);
// MainActivity.mRecipies.add(newRecipe);
}
}catch (Exception e){
Log.i("Error Message", e.getMessage());
}
}
});
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
I am trying to implement swipe to refresh in my app. When swipe to refresh is triggered, first all the data is fetched from JSON and then stored in the database. After storing the data, all the new data will be added to the top of the recyclerview. I read a few articles and only managed to find out about adding a single item at the top of the list. But in the case of my app, where more than one item may be available to show, what should I do?
Here is my code for the database table where first new post is fetched with the last post id which is shown in recyclerview:
#Override
public ArrayList<Post> getAllNewPost(int T) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Post> postList = null;
try {
postList = new ArrayList<Post>();
String QUERY = "SELECT * FROM " + TABLE_NAME + " INNER JOIN "+TABLE_FOLLOWER+
" ON post_table.user_id = follower.user_id WHERE follower.follow = '1' AND post_table.post_id > "+T+" ORDER BY "+POST_ID+" DESC";
Cursor cursor = db.rawQuery(QUERY, null);
if (!cursor.isLast()) {
while (cursor.moveToNext()) {
Post post = new Post();
post.setPost_id(cursor.getString(0));
Log.d("post_id",cursor.getString(0));
post.setUser_id(cursor.getString(1));
post.setUser_name(cursor.getString(2));
post.setImg_link(cursor.getString(3));
post.setPost_title(cursor.getString(4));
post.setPost_cat(cursor.getString(6));
post.setPost_time(cursor.getString(8));
postList.add(post);
}
}
db.close();
} catch (Exception e) {
Log.e("error", e + "");
}
return postList;
}
Here is array adapter of recyclerview:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> listData = new ArrayList<>();
String rpostid,ruserid,rname,rcat,rdate,rtittle,urlThumnail;
private VolleySingleton volleySingleton;
ImageLoader imageLoader = VolleySingleton.getsInstance().getImageLoad();
public PostAdapter(ArrayList<Post> postList) {
this.listData=postList;
}
public PostAdapter(Context context){
this.context = context;
}
#Override
public PostAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.post_item, viewGroup, false);
return new posts(v);
}
public class posts extends ViewHolder {
TextView tvTittle,tvPostId,tvUseId,tvName,tvCat,tvDate;
ImageView row_img;
public posts(View v) {
super(v);
tvTittle = (TextView) v.findViewById(R.id.row_cmnt);
tvPostId = (TextView) v.findViewById(R.id.row_postid);
tvUseId = (TextView) v.findViewById(R.id.row_userid);
tvName = (TextView) v.findViewById(R.id.row_name);
tvCat = (TextView) v.findViewById(R.id.row_cat);
tvDate = (TextView) v.findViewById(R.id.row_date);
row_img = (ImageView) v.findViewById(R.id.row_img);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
TextView text = (TextView) v.findViewById(R.id.row_postid);
String lst_txt = text.getText().toString().trim();
intent = new Intent(v.getContext(), PostView.class);
intent.putExtra("post_id", lst_txt);
v.getContext().startActivity(intent);
}
});
}
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final posts holder = (posts) viewHolder;
Post post = listData.get(position);
rpostid = post.getPost_id();
ruserid = post.getUser_id();
rname = post.getUser_name();
rcat = post.getPost_cat();
rdate = post.getPost_time();
rtittle = post.getPost_title();
holder.tvPostId.setText(rpostid);
holder.tvUseId.setText(ruserid);
holder.tvName.setText(rname);
holder.tvCat.setText(rcat);
holder.tvDate.setText(rdate);
holder.tvTittle.setText(rtittle);
urlThumnail = post.getImg_link();
Log.d("qwerty","link of image lru: "+ urlThumnail);
if (urlThumnail != null){
imageLoader.get(urlThumnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.row_img.setImageBitmap(response.getBitmap());
Log.d("qwerty","post attached 2");
}
#Override
public void onErrorResponse(VolleyError error) {
Log.d("qwerty","post attached 3");
}
});
}
}
#Override
public int getItemCount() {
return (null != listData ? listData.size() : 0);
}
}
And here is the code by which all the new posts will be fetched from the DB:
private ArrayList<Post> parseJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Log.d("response",post_id+" "+user_id+" "+user_name+" "+img_link);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllPost();
t = Integer.parseInt(postList.get(1).getPost_id().toString().trim());
Log.d("Check", "postid: "+t);
Hpbar.setVisibility(View.INVISIBLE);
Log.d("jsonCount", String.valueOf(postList));
String AdapterData = String.valueOf(postList);
if(AdapterData.equals("[]")){
Htvnopostfound.setVisibility(View.VISIBLE);
}else{
adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
}
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
private ArrayList<Post> swipeJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllNewPost(t);
adapter.notifyItemInserted(1);
Log.d("check","post_id "+t+" hello");
/*adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
Log.d("check","post_id "+t+" hello 2");*/
Log.d("check","post_id "+t+" hello 2");
Hpbar.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
On startup parseJSONResponse is used and for swipeToRefresh swipeJSONResponse is used. In parseJSONResponse, the last displayed post's id is stored in int t and then this int t is passed to swipeJSONResponse to get the new post.
But after refreshing, new data will not show in the list. SO, please tell me how to do so. I've read a few articles where add is used, as such:
listview.add(0, item);
But I don't know how to implement this with multiple rows of data at same time. Thanks in advance.
The correct way to update data in a listView should be:
1) create an update data method in your adapter. In your case could be like this:
public updateData(ArrayList<Post> postList) {
this.listData=postList;
notifyDataSetChanged();
}
or, if you want just append data on the top:
public addNewDataOnTop(ArrayList<Post> postList) {
this.listData.addAll(0,postList);
notifyDataSetChanged();
}
2) When you have new data to add, do not create a new adapter but just update the data
When you create the listView at the beginning you set the empty adapter:
adapter = new PostAdapter(new ArrayList());
listView.setAdapter(adapter);
When you receive the new data, you just update the adapter:
adapter.addNewDataOnTop(postList);
I hope it helped
I would insert each item at the top using:
mArrayList.add(0, item1);
notifyItemInserted(0);
mArrayList.add(0, item2);
notifyItemInserted(0);
Do the following for all your items.
So I'm new to Android and I'm using Parse as my backend. I have an Array column in Parse called PrescriptionArray. I want to take the contents of this array (String values) and populate a listView with them. I think I'm only missing a couple of lines but not sure where? Any help would be greatly appreciated.. Thanks in advance!
public class PrescriptionsArrayActivity extends AppCompatActivity {
private ListView lvPrescriptions;
private EditText etMedicalID;
private ArrayAdapter<String> adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prescriptions_array);
lvPrescriptions = (ListView) findViewById(R.id.lvPrescriptions);
etMedicalID = (EditText) findViewById(R.id.etMedicalID);
//Get the Medical ID number from previous activity
Bundle bundle = getIntent().getExtras();
String str = bundle.getString("MedicalID");
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
etMedicalID.setText(str);
final List<String> arrayprescription = new ArrayList<String>();
final ArrayAdapter adapter = new ArrayAdapter(PrescriptionsArrayActivity.this, android.R.layout.simple_list_item_1, arrayprescription);
final ParseQuery<ParseObject> query = ParseQuery.getQuery("PrescriptionObject");
query.whereEqualTo("MedicalID", etMedicalID.getText().toString());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> prescriptionList, ParseException e) {
if (e == null) {
for (int i = 0; i < prescriptionList.size(); i++) {
ParseObject p = prescriptionList.get(i);
if (p.getList("PrescriptionArray") != null) {
String s = arrayprescription.toString();
adapter.addAll(Arrays.asList(s));
}
}
lvPrescriptions.setAdapter(adapter);
}
}
});
}
}