How to implement a listview using volley android - android

I'm developing an app that grabs a list of clients of an API, and I need to show it in a listview, I'm using volley and what I tried to do is the following, but it's not working:
public ListView txtDisplay;
#Override
protected Boolean doInBackground(Void... params) {
try {
txtDisplay = (Listview) findViewById(R.id.listView);
String url = "http://192.168.1.1/rep-mais-api/api";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
})
The ActivityMain.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager" />
<TextView
android:id="#+id/txtDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true" android:layout_alignParentLeft="true"/>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>

Using this example, solved my case
import android.app.ProgressDialog;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends Activity {
private String TAG = this.getClass().getSimpleName();
private ListView lstView;
private RequestQueue mRequestQueue;
private ArrayList<NewsModel> arrNews ;
private LayoutInflater lf;
private VolleyAdapter va;
private ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lf = LayoutInflater.from(this);
arrNews = new ArrayList<NewsModel>();
va = new VolleyAdapter();
lstView = (ListView) findViewById(R.id.listView);
lstView.setAdapter(va);
mRequestQueue = Volley.newRequestQueue(this);
String url = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json";
pd = ProgressDialog.show(this,"Please Wait...","Please Wait...");
try{
Thread.sleep(2000);
}catch(Exception e){
}
JsonObjectRequest jr = new JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
parseJSON(response);
va.notifyDataSetChanged();
pd.dismiss();
; }
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.getMessage());
}
});
mRequestQueue.add(jr);
}
private void parseJSON(JSONObject json){
try{
JSONObject value = json.getJSONObject("value");
JSONArray items = value.getJSONArray("items");
for(int i=0;i<items.length();i++){
JSONObject item = items.getJSONObject(i);
NewsModel nm = new NewsModel();
nm.setTitle(item.optString("title"));
nm.setDescription(item.optString("description"));
nm.setLink(item.optString("link"));
nm.setPubDate(item.optString("pubDate"));
arrNews.add(nm);
}
}
catch(Exception e){
e.printStackTrace();
}
}
class NewsModel{
private String title;
private String link;
private String description;
private String pubDate;
void setTitle(String title) {
this.title = title;
}
void setLink(String link) {
this.link = link;
}
void setDescription(String description) {
this.description = description;
}
void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
String getLink() {
return link;
}
String getDescription() {
return description;
}
String getPubDate() {
return pubDate;
}
String getTitle() {
return title;
}
}
class VolleyAdapter extends BaseAdapter{
#Override
public int getCount() {
return arrNews.size();
}
#Override
public Object getItem(int i) {
return arrNews.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder vh ;
if(view == null){
vh = new ViewHolder();
view = lf.inflate(R.layout.row_listview,null);
vh.tvTitle = (TextView) view.findViewById(R.id.txtTitle);
vh.tvDesc = (TextView) view.findViewById(R.id.txtDesc);
vh.tvDate = (TextView) view.findViewById(R.id.txtDate);
view.setTag(vh);
}
else{
vh = (ViewHolder) view.getTag();
}
NewsModel nm = arrNews.get(i);
vh.tvTitle.setText(nm.getTitle());
vh.tvDesc.setText(nm.getDescription());
vh.tvDate.setText(nm.getPubDate());
return view;
}
class ViewHolder{
TextView tvTitle;
TextView tvDesc;
TextView tvDate;
}
}
}
Source

Related

How to update firebase data node from a new activity when child is random key generated by current date and current time

Please see my code and snapshot what I am looking for, I created a new activity from where I can update my product details (note:I will add image upload functionality later in my activity). but from my code I get the result like the snapshot I attached where I marked in red what I wanted. I add products as admin and trying to update as admin but from a different activity I wanted to update my data. Please help me
Here is activity code I am trying
package com.commerce.daily.dailycommerce;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.commerce.daily.dailycommerce.ViewHolder.ProductViewHolder;
import com.commerce.daily.dailycommerce.model.Products;
import com.commerce.daily.dailycommerce.prevalent.prevalent;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class AdminUpdatingProductsActivity extends AppCompatActivity {
private String UpdateDescription, updatePrice, updatePName;
private TextView updateTxtBtn, changeImageTxt, closeTxtBtn;
private EditText productUpdateName, productUpdateDescription, productUpdatePrice;
private DatabaseReference updateProductRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_updating_products);
updateProductRef = FirebaseDatabase.getInstance().getReference().child("Products");
updateTxtBtn = (TextView) findViewById(R.id.update_product_details_btn2);
changeImageTxt = (TextView) findViewById(R.id.product_image_update_txt);
closeTxtBtn = (TextView) findViewById(R.id.close_update_product_btn);
productUpdateName = (EditText) findViewById(R.id.update_product_name);
productUpdateDescription = (EditText) findViewById(R.id.update_product_description);
productUpdatePrice = (EditText) findViewById(R.id.update_product_price);
updateTxtBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
updateinformation();
}
});
}
private void updateinformation() {
updatePName = productUpdateName.getText().toString();
UpdateDescription = productUpdateDescription.getText().toString();
updatePrice = productUpdatePrice.getText().toString();
HashMap<String, Object> ProductMap = new HashMap<>();
ProductMap.put("pname", updatePName);
ProductMap.put("price", updatePrice);
ProductMap.put("description", UpdateDescription);
updateProductRef.updateChildren(ProductMap);
}
}
And here is xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.commerce.daily.dailycommerce.AdminUpdatingProductsActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_update_product"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary">
<android.support.v7.widget.Toolbar
android:id="#+id/tollbar_update_product"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/close_update_product_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:textColor="#android:color/white"
android:textSize="17sp"
android:textStyle="bold"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/update_product_details_btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:textColor="#android:color/white"
android:textSize="17sp"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<ImageView
android:id="#+id/product_image_update"
android:layout_below="#+id/app_bar_update_product"
android:layout_width="250dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:src="#drawable/ic_menu_camera"/>
<TextView
android:id="#+id/product_image_update_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_image_update"
android:text="Change Image"
android:layout_marginTop="4dp"
android:textColor="#android:color/black"
android:textSize="17sp"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_centerHorizontal="true"/>
<EditText
android:id="#+id/update_product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/product_image_update_txt"
android:inputType="textMultiLine"
android:layout_marginTop="30dp"
android:padding="20dp"
android:hint="Product Name..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="#drawable/input_design"/>
<EditText
android:id="#+id/update_product_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/update_product_name"
android:inputType="textMultiLine"
android:layout_marginTop="6dp"
android:padding="20dp"
android:hint="Product Description..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="#drawable/input_design"/>
<EditText
android:id="#+id/update_product_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/update_product_description"
android:inputType="textMultiLine"
android:layout_marginTop="6dp"
android:padding="20dp"
android:hint="Product Price..."
android:layout_marginLeft="45dp"
android:layout_marginRight="45dp"
android:background="#drawable/input_design"/>
</RelativeLayout>
package com.commerce.daily.dailycommerce;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import com.commerce.daily.dailycommerce.Interface.ItemClickListner;
import com.commerce.daily.dailycommerce.ViewHolder.ProductViewHolder;
import com.commerce.daily.dailycommerce.model.Products;
import com.commerce.daily.dailycommerce.prevalent.prevalent;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
public class AdminListedProductActivity extends AppCompatActivity
{
private DatabaseReference AdminProductsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
AdminProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.productlist_recycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(AdminProductsRef, Products.class)
.build();
final FirebaseRecyclerAdapter<Products, ProductViewHolder> adapter =
new FirebaseRecyclerAdapter<Products, ProductViewHolder>(options)
{
#Override
protected void onBindViewHolder(#NonNull ProductViewHolder holder, final int position, #NonNull final Products model)
{
holder.txtProductName.setText(model.getPname());
holder.txtProductDescription.setText(model.getDescription());
holder.txtProductPrice.setText("Price = "+ model.getPrice());
Picasso.get().load(model.getImage()).into(holder.imageView);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CharSequence options[] = new CharSequence[]
{
"Edit",
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(AdminListedProductActivity.this);
builder.setTitle("Edit/Delete");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
if(which == 0)
{
updateProducts();
}
if(which == 1)
{
FirebaseDatabase.getInstance().getReference().child("Products")
.child(model.getDate() + model.getTime())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(AdminListedProductActivity.this, "Item Removed Successfully.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AdminListedProductActivity.this, AdminCategoryActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
#NonNull
#Override
public ProductViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_items_layout, parent, false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
private void updateProducts()
{
finish();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
}
}
and here is my Products Class under a package named model
package com.commerce.daily.dailycommerce.model;
/**
* Created by Romen on 2/10/2019.
*/
public class Products
{
private String pname, description, price,image, category, pid, date, time;
public Products()
{
}
public Products(String pname, String description, String price, String image, String category, String pid, String date, String time)
{
this.pname = pname;
this.description = description;
this.price = price;
this.image = image;
this.category = category;
this.pid = pid;
this.date = date;
this.time = time;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
You can't update the specific node which you want in this way, Because you didn't specify which node you want to update its data.
in this line updateProductRef.updateChildren(ProductMap); you specify the "product" node then add data inside it, instead of that you should specify the node that you want to update it.
to achieve this you should put a unique id for each node (like "pid" attribute in your database), then compare it with the "pid" in your current activity.
in your class "products" put getter and setter methods for the "pid" attribute.
when clicking on the special product from your list that contains all "products" get the position of the item and get "pid" from it, like this:
after getting the current item of "pid" send it with the intent by using the putExtra() method on the intent object to the new activity.
catch the string that sent from previous activity and comare it with all pid attributes that in the database, then get key to the product and set as a child.
Edit
actually, I don't understand your code correctly or it is a mistake so, I build another code totally different.
create an adapter class for display products:
public class AdapterProducts extends RecyclerView.Adapter<AdapterProducts.HolderProuducts> {
Context context;
List<products> listProuducts;
private AdapterProducts.OnItemClickListener mListener;
//This interface for handle clicked on an item in recyclerview
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(AdapterProducts.OnItemClickListener listener) {
mListener = listener;
}
//constrouctor
public AdapterProducts(Context context,List<products> listProuducts)
{
this.listProuducts = listProuducts;
this.context = context;
}
#Override
public AdapterProducts.HolderProuducts onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View row = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.row_item_products, viewGroup, false);
AdapterProducts.HolderProuducts holder = new AdapterProducts.HolderProuducts(row, mListener);
return holder;
}
#Override
public void onBindViewHolder(#NonNull AdapterProducts.HolderProuducts holderProuducts, int i) {
holderProuducts.txtProductName.setText(model.getPname());
holderProuducts.txtProductDescription.setText(model.getDescription());
holderProuducts.txtProductPrice.setText("Price = "+ model.getPrice());
Picasso.get().load(model.getImage()).into(holderProuducts.imageView);
}
#Override
public int getItemCount() {
return listProuducts.size();
}
public class HolderProuducts extends RecyclerView.ViewHolder{
TextView txtProductName,txtProductDescription,txtProductPrice;
ImageView imageView;
public HolderProuducts(#NonNull View itemView, final AdapterProducts.OnItemClickListener listener) {
super(itemView);
txtProductName = (TextView) itemView.findViewById(R.id.name_product);
txtProductDescription = (TextView) itemView.findViewById(R.id.description_product);
txtProductPrice = (TextView) itemView.findViewById(R.id.price_product);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
}
in your AdminListedProductActivity:
`
public class AdminListedProductActivity extends AppCompatActivity {
RecyclerView mRecyclerProducts;
List<Products> listProducts;
LinearLayoutManager layoutManager;
AdapterProducts mAdapterProducts;
DatabaseReference AdminProductsRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
AdminProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
listProducts = new ArrayList();
mRecyclerProducts = findViewById(R.id.productlist_recycler);
mRecyclerProducts.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
mRecyclerProducts.setLayoutManager(layoutManager);
listProducts = displayProuductsInList();
mAdapterProducts.setOnItemClickListener(new AdapterProducts.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Products productsClicked = listProducts.get(position);
//This pid for the item that clicked on it
String pid = productsClicked.getPid();
Intent intent = new Intent(AdminListedProductActivity .this,AdminUpdatingProductsActivity.class);
//send it with intent to activity update
intent.putExtra("pid",pid);
startActivity(intent);
}
});
}
//This method for get all products from database
private List<Products> displayProuductsInList() {
List<Products> list = new ArrayList();
AdminProductsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Products products = data.getValue(Products.class);
list.add(products);
}
mRecyclerProducts.setLayoutManager(new LinearLayoutManager(AdminListedProductActivity .this));
mAdapterProducts.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
`
in your AdminUpdatingProductsActivity:
public class AdminUpdatingProductsActivity extends AppCompatActivity {
private String UpdateDescription, updatePrice, updatePName;
private TextView updateTxtBtn, changeImageTxt, closeTxtBtn;
private EditText productUpdateName, productUpdateDescription, productUpdatePrice;
DatabaseReference updateProductRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_listed_product);
updateProductRef = FirebaseDatabase.getInstance().getReference().child("Products");
updateTxtBtn = (TextView) findViewById(R.id.update_product_details_btn2);
changeImageTxt = (TextView) findViewById(R.id.product_image_update_txt);
closeTxtBtn = (TextView) findViewById(R.id.close_update_product_btn);
productUpdateName = (EditText) findViewById(R.id.update_product_name);
productUpdateDescription = (EditText) findViewById(R.id.update_product_description);
productUpdatePrice = (EditText) findViewById(R.id.update_product_price);
updateTxtBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
updateinformation();
}
});
}
private void updateinformation() {
Intent intent = getIntent();
String pidFromPriveosActivity = intent.getStringExtra("pid");
updatePName = productUpdateName.getText().toString();
UpdateDescription = productUpdateDescription.getText().toString();
updatePrice = productUpdatePrice.getText().toString();
HashMap<String, Object> ProductMap = new HashMap<>();
ProductMap.put("pname", updatePName);
ProductMap.put("price", updatePrice);
ProductMap.put("description", UpdateDescription);
updateProductRef.addListenerForSingleValueEvent(new ValueEventListener() {
String currentKey;
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren())
{
//get each "pid" in database for all products
String pidsInDataBase = data.child("pid").getValue(String.class);
//compare "pid" from previous activity with each "pid" in database
if (pidFromPriveosActivity.equals(pidsInDataBase)){
//get key for product that clicke on it in recyclerview
currentKey = data.getKey();
}
}
//update data for this item
updateProductRef.child(currentKey).updateChildren(ProductMap);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}

Android Recycler View caching

I'm using volley to load data using JSON Parsing in to a recycler view. I've used recylcer view before, but somehow, the downloaded data is persistent this time, meaning its still there after the app is closed, maybe stays in cache. I'm not sure, what I'm doing wrong here. Any help is appreciated, thanks.
Edit: The application is storing downloaded data after the app is closed, which doesn't happen when using recycler view.
This is my Activity Class:
package com.example.recyclerview;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity implements
OnItemClick{
private ArrayList<PostData> posts = new ArrayList<>();
private PostRecycleViewAdapter viewAdapter;
private String listingJsonUrl = "https://jsonplaceholder.typicode.com/posts/";
Toolbar toolbar;
private ProgressDialog progressDialog;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
final RecyclerView.LayoutManager viewLayoutManager = new LinearLayoutManager(getApplicationContext());
viewAdapter = new PostRecycleViewAdapter(posts);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(viewLayoutManager);
recyclerView.setAdapter(viewAdapter);
viewAdapter.setClickListener(this);
new DownloadData().execute(listingJsonUrl);
}
#Override
public void onClick(View view, int position) {
final PostData data = posts.get(position);
String title;
int id;
Intent commentIntent = new Intent(this, CommentsActivity.class);
id = data.getId();
title = data.getTitle();
if(title.length() > 25){
title = title.substring(0,25);
title = title.concat("..");
}
commentIntent.putExtra("title",title) ;
commentIntent.putExtra("id", id);
startActivity(commentIntent);
}
class DownloadData extends AsyncTask<String, String, String>{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... url) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url[0], new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PostData postData = new PostData(jsonObject.getInt("id"),jsonObject.getString("title"), jsonObject.getString("body"));
posts.add(postData);
viewAdapter.notifyDataSetChanged();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JsonError", error.getMessage());
}
});
getRequestQueue().add(jsonArrayRequest);
return null;
}
}
public RequestQueue getRequestQueue()
{
if (requestQueue == null)
{
requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
}
This is my RecyclerView Adapter Class:
package com.example.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostRecycleViewAdapter extends RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>
{
private List<PostData> postData;
private OnItemClick itemClick;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView title, body;
public ViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.title);
body = (TextView) view.findViewById(R.id.body);
view.setTag(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(itemClick != null) itemClick.onClick(view, getAdapterPosition());
}
}
public PostRecycleViewAdapter(List<PostData> postData)
{
this.postData = postData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_recycler_view,parent,false);
return new ViewHolder(itemLayout);
}
#Override
public void onBindViewHolder(PostRecycleViewAdapter.ViewHolder holder, int position) {
PostData data = postData.get(position);
holder.title.setText(data.getTitle());
holder.body.setText(data.getBody());
}
#Override
public int getItemCount() {
return postData.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);}
public void setClickListener(OnItemClick itemClick) {
this.itemClick = itemClick;
}
}
And this is the data item class:
package com.example.recyclerview;
public class PostData {
private String title, body;
private int id;
public PostData(int id, String title, String body)
{
this.id = id;
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getId() {
return id;
}
}

Recycler view not showing after parsing json data using Volley

Inside my tab bar i want to show my data in Recycler view by using json parsing using volley library. I parsed the data and it showing in toast perfectly.But in Recycler view its not showing Here is my codes.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.transform.ErrorListener;
import info.tatwa.adupter.AdupterBoxOffice;
import info.tatwa.extras.Keys;
import info.tatwa.extras.UrlEndPoint;
import info.tatwa.login.L;
import info.tatwa.model.Movies;
import info.tatwa.network.MyApplication;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
import info.tatwa.extras.UrlEndPoint.*;
import info.tatwa.extras.Keys.EndpointBoxOffice.*;
public class FragmentBoxOffice extends Fragment {
private VolleySingleton volleySingleton;
private RequestQueue requestQueue;
private AdupterBoxOffice adupterBoxOffice;
private ArrayList<Movies>listMovie = new ArrayList<>();
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static final String ROTET_TOMATO_URL_BOX_OFFICE="My url is here"
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView listMovieHits;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentBoxOffice.
*/
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static String getRequestUrl(int limit){
//ROTET_TOMATO_URL_BOX_OFFICE+"?apikey="+ MyApplication.ROTET_TOMATO_API_KEY+"&limit="+limit;
return UrlEndPoint.URL_BOX_OFFICE +
UrlEndPoint.URL_CHAR_QUASTIAN+
UrlEndPoint.URL_CHAR_PAREM_APIKEY +
MyApplication.ROTET_TOMATO_API_KEY +
UrlEndPoint.URL_CHAR_APPEND+
UrlEndPoint.URL_CHAR_PAREM_LIMIT + limit;
}
public FragmentBoxOffice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getsInstance();
requestQueue = volleySingleton.getmRequestQueue();
senJsonRequest();
}
public void senJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getRequestUrl(10), (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
paresJSONResponse(response);
listMovie =paresJSONResponse(response);
adupterBoxOffice.setMovieList(listMovie);
L.t(getActivity(), response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Error"+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(request);
}
public ArrayList<Movies> paresJSONResponse(JSONObject response){
ArrayList<Movies> listMovie = new ArrayList<>();
if(response ==null|| response.length()==0 ){
return null;
}
try {
StringBuilder data = new StringBuilder();
JSONArray arrayMovie = response.getJSONArray(Keys.EndpointBoxOffice.KEY_MOVIES);
Log.v("BIKASH", "JSON Object id" + arrayMovie);
for(int i = 0; i<arrayMovie.length();i++){
JSONObject currentMovies= arrayMovie.getJSONObject(i);
Long id =currentMovies.getLong(Keys.EndpointBoxOffice.KEY_ID);
String title=currentMovies.getString(Keys.EndpointBoxOffice.KEY_TITLE);
JSONObject objectReleaseDates=currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RELEASE_DATES);
String releaseDate=null;
if(objectReleaseDates.has(Keys.EndpointBoxOffice.KEY_THEATER)){
releaseDate = objectReleaseDates.getString(Keys.EndpointBoxOffice.KEY_THEATER);
}
else {
releaseDate="NA";
}
int audianceRatting=-1;
JSONObject objectRatting = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RATINGS);
{
if(objectRatting.has(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE)){
audianceRatting=objectRatting.getInt(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE);
}
}
String synuypsis = currentMovies.getString(Keys.EndpointBoxOffice.KEY_SYNOPSIS);
String urlThumbnel = null;
JSONObject objPoster = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
if(objPoster.has(Keys.EndpointBoxOffice.KEY_THUMBNAIL)){
urlThumbnel = objPoster.getString(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
}
Movies movie =new Movies();
movie.setId(id);
movie.setTitle(title);
Date date = dateFormat.parse(releaseDate);
movie.setReleaseDateTheater(date);
movie.setAudienceScore(audianceRatting);
movie.setSynopsis(synuypsis);
movie.setUrlThumbnail(urlThumbnel);
listMovie.add(movie);
// data.append(id + "\n");
}
L.t(getActivity(),listMovie.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return listMovie;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_fragment_box_office, container, false);
listMovieHits =(RecyclerView)view.findViewById(R.id.listMovieHits);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
adupterBoxOffice = new AdupterBoxOffice(getActivity());
listMovieHits.setAdapter(adupterBoxOffice);
senJsonRequest();
return view;
}
}
My Adupter
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import java.util.ArrayList;
import info.tatwa.model.Movies;
import info.tatwa.myfragment.FragmentBoxOffice;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
public class AdupterBoxOffice extends RecyclerView.Adapter<AdupterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
FragmentBoxOffice activity;
private ArrayList<Movies> listMovie = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
public AdupterBoxOffice(Context context){
layoutInflater=LayoutInflater.from(context);
volleySingleton=VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movies>listMovie){
this.listMovie = listMovie;
notifyItemRangeChanged(0,listMovie.size());
}
#Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.movie_list_itom,parent,false);
ViewHolderBoxOffice viewHolder =new ViewHolderBoxOffice(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movies currentMovie =listMovie.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
holder.movieReleaseDate.setText(currentMovie.getReleaseDateTheater().toString());
holder.movieRatting.setRating(currentMovie.getAudienceScore()/20.0f);
String urlThumbnel = currentMovie.getUrlThumbnail();
if(urlThumbnel!=null){
imageLoader.get(urlThumbnel, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.imagePoster.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return listMovie.size();
}
static class ViewHolderBoxOffice extends RecyclerView.ViewHolder {
private ImageView imagePoster;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieRatting;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
imagePoster=(ImageView)itemView.findViewById(R.id.movieThumbnail);
movieTitle =(TextView)itemView.findViewById(R.id.movieTitle);
movieReleaseDate=(TextView)itemView.findViewById(R.id.movieReleaseDate);
movieRatting=(RatingBar)itemView.findViewById(R.id.movieAudienceScore);
}
}
}
And My Model class
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
public class Movies{
private long id;
private String title;
private Date releaseDateTheater;
private int audienceScore;
private String synopsis;
private String urlThumbnail;
private String urlSelf;
private String urlCast;
private String urlReviews;
private String urlSimilar;
public Movies() {
}
public Movies(long id,
String title,
Date releaseDateTheater,
int audienceScore,
String synopsis,
String urlThumbnail,
String urlSelf,
String urlCast,
String urlReviews,
String urlSimilar) {
this.id = id;
this.title = title;
this.releaseDateTheater = releaseDateTheater;
this.audienceScore = audienceScore;
this.synopsis = synopsis;
this.urlThumbnail = urlThumbnail;
this.urlSelf = urlSelf;
this.urlCast = urlCast;
this.urlReviews = urlReviews;
this.urlSimilar = urlSimilar;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getReleaseDateTheater() {
return releaseDateTheater;
}
public void setReleaseDateTheater(Date releaseDateTheater) {
this.releaseDateTheater = releaseDateTheater;
}
public int getAudienceScore() {
return audienceScore;
}
public void setAudienceScore(int audienceScore) {
this.audienceScore = audienceScore;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getUrlThumbnail() {
return urlThumbnail;
}
public void setUrlThumbnail(String urlThumbnail) {
this.urlThumbnail = urlThumbnail;
}
public String getUrlSelf() {
return urlSelf;
}
public void setUrlSelf(String urlSelf) {
this.urlSelf = urlSelf;
}
public String getUrlCast() {
return urlCast;
}
public void setUrlCast(String urlCast) {
this.urlCast = urlCast;
}
public String getUrlReviews() {
return urlReviews;
}
public void setUrlReviews(String urlReviews) {
this.urlReviews = urlReviews;
}
public String getUrlSimilar() {
return urlSimilar;
}
public void setUrlSimilar(String urlSimilar) {
this.urlSimilar = urlSimilar;
}
#Override
public String toString() {
return "\nID: " + id +
"\nTitle " + title +
"\nDate " + releaseDateTheater +
"\nSynopsis " + synopsis +
"\nScore " + audienceScore +
"\nurlThumbnail " + urlThumbnail +
"\nurlSelf " + urlSelf +
"\nurlCast " + urlCast +
"\nurlReviews " + urlReviews +
"\nurlSimilar " + urlSimilar +
"\n";
}
}
Please help me out .. Thanks in advance ..
After adupterBoxOffice.setMovieList(listMovie);
try add adupterBoxOffice.notifyDataSetChanged();
I found my solution.I put some wrong key during pars the Json. That's why my ArrayList returning zero.
Many many thanks to all for helping me out.

I am getting the items in Listview repeated . Here is my sample code I am unable to find the bug in my code ! Can anyone help me out please?

//this is JOBListAdapter class
package com.example.hellotest.adapters;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.hellotest.R;
import com.example.hellotest.model.Job;
public class JobListAdapter extends BaseAdapter {
private LayoutInflater mInflater ;
private List<Job> mJobs;
private SimpleDateFormat mDateFormat;
private SimpleDateFormat mInputFormat;
private String mPosterPrefix;
public JobListAdapter(Context context) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
mInputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US);
mPosterPrefix = context.getString(R.string.job_posted_by);
}
public void setJobList(List<Job> jobs) {
mJobs = jobs;
}
#Override
public int getCount() {
if(null != mJobs) {
return mJobs.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return mJobs.get(position);
}
#Override
public long getItemId(int position) {
return mJobs.get(position).getId();
}
//this is the method where I think that the problem is please somebody tell me.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(null == convertView) {
convertView = mInflater.inflate(R.layout.job_list_row, null);
holder = new ViewHolder();
holder.created = (TextView) convertView.findViewById(R.id.job_listing_date);
holder.location = (TextView) convertView.findViewById(R.id.job_listing_location);
holder.title = (TextView) convertView.findViewById(R.id.job_listing_title);
holder.experience = (TextView) convertView.findViewById(R.id.job_listing_experience);
holder.poster = (TextView) convertView.findViewById(R.id.job_listing_posted_by);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
updateRow(holder, mJobs.get(position));
return convertView;
}
private void updateRow(ViewHolder holder, Job job) {
holder.title.setText(job.getTitle());
int id = job.isPremium() ? R.drawable.icon_premium : 0;
holder.created.setText(getDate(job.getCreated()));
holder.created.setCompoundDrawablesWithIntrinsicBounds(0, 0, id, 0);
holder.experience.setText(job.getExperience());
holder.location.setText(job.getLocation());
holder.poster.setText(mPosterPrefix + job.getPoster());
}
private CharSequence getDate(String created) {
try {
return mDateFormat.format(mInputFormat.parse(created));
} catch (ParseException e) {
e.printStackTrace();
}
return created;
}
private static class ViewHolder {
TextView created;
TextView title;
TextView location;
TextView experience;
TextView poster;
}
}
// layout for fragmentjob_listing even I make the listview height to fill_parent as suggested when I googled the solution for the issue.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/job_listing_filter_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/job_listing_tab_bg"
android:gravity="center_vertical"
android:minHeight="48dp" >
<TextView
android:id="#+id/job_listing_experience"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/selector_job_listing_tab"
android:clickable="true"
android:gravity="center"
android:text="#string/job_listing_experience" />
<ImageView
android:id="#+id/space2"
android:layout_width="1dp"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/job_listing_horizontal_divider" />
<TextView
android:id="#+id/job_listing_location"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/selector_job_listing_tab"
android:clickable="true"
android:gravity="center"
android:text="#string/job_listing_location" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/job_listing_divider" />
<TextView
android:id="#+id/job_listing_message"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:visibility="gone"/>
<ListView
android:id="#+id/job_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
// JobListingFragment Class where the joblistAdapter class called up
package com.example.hellotest;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.example.hellotest.R;
import com.example.hellotest.adapters.JobListAdapter;
import com.example.hellotest.config.Constant;
import com.example.hellotest.io.CookieStringRequest;
import com.example.hellotest.io.json.JobsProcessor;
import com.example.hellotest.model.Job;
import com.example.hellotest.model.JobList;
import com.example.hellotest.model.Pagination;
import com.example.hellotest.tasks.JsonParserTask;
import com.example.hellotest.tasks.JsonParsingListener;
import com.example.hellotest.util.AccountUtils;
import com.example.hellotest.util.Log;
public class JobListingFragment extends Fragment {
public static final String ARG_URL = "argument_url";
public static final String ARG_IS_FILTER_ON = "argument_is_filtered";
public static final String ARG_IS_DEFAULT_JOB_LIST = "argument_is_default_job_list";
public static final String ARG_EMPTY_MESSAGE = "argument_empty_message";
protected static final int REQUEST_EXPERIENCE = 0x11;
protected static final int REQUEST_LOCATION = 0x12;
private ListView mJobsList;
private TextView mMessageView;
private JobListAdapter mAdapter;
private List<Job> mJobs;
private Pagination mPagination;
private boolean mIsFetching;
private boolean mIsDefaultList;
private boolean mIsFilterOn;
private String mUrl;
private String mLocId;
private int mExperienceId = -1;
private ProgressBar mFooterProgress;
private Log mLogger = new Log(JobListingFragment.class);
private Object mRequestTag = new Object();
private RequestQueue mRequestQueue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new JobListAdapter(getActivity());
if (null != savedInstanceState) {
getState(savedInstanceState);
} else {
getState(getArguments());
}
// init();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mRequestQueue = Volley.newRequestQueue(getActivity());
}
#Override
public void onDetach() {
mRequestQueue.cancelAll(mRequestTag);
super.onDetach();
}
#Override
public void onResume() {
init();
super.onResume();
}
private void getState(Bundle bundle) {
mUrl = bundle.getString(ARG_URL);
mIsFilterOn = bundle.getBoolean(ARG_IS_FILTER_ON);
mIsDefaultList = bundle.getBoolean(ARG_IS_DEFAULT_JOB_LIST);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_job_listing, null);
mJobsList = (ListView) view.findViewById(R.id.job_list);
mMessageView = (TextView) view.findViewById(R.id.job_listing_message);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
View footer = getLayoutInflater(savedInstanceState).inflate(R.layout.paginated_list_footer, null);
mFooterProgress = (ProgressBar) footer.findViewById(R.id.footer_progress);
if (!mIsFilterOn) {
view.findViewById(R.id.job_listing_filter_container).setVisibility(View.GONE);
} else {
view.findViewById(R.id.job_listing_experience).setOnClickListener(mOnClickListener);
view.findViewById(R.id.job_listing_location).setOnClickListener(mOnClickListener);
}
mJobsList.addFooterView(footer);
mJobsList.setAdapter(mAdapter);
mJobsList.setOnScrollListener(mOnScrollListener);
mJobsList.setOnItemClickListener(mOnItemClickListener);
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_URL, mUrl);
outState.putBoolean(ARG_IS_FILTER_ON, mIsFilterOn);
outState.putBoolean(ARG_IS_DEFAULT_JOB_LIST, mIsDefaultList);
super.onSaveInstanceState(outState);
}
public void startAfresh(String url, boolean isPaginated) {
mLogger.d("old fragment reused");
mIsFilterOn = true;
mUrl = url;
reset();
init();
}
private void init() {
mLocId = AccountUtils.getLocationFilter();
mExperienceId = AccountUtils.getExperienceFilter();
String url = getUrl(1);
fetchJobs(url);
}
private void reset() {
mJobs = null;
mPagination = null;
mAdapter.setJobList(null);
mAdapter.notifyDataSetChanged();
}
private String getUrl(int pageNumber) {
String appender = "";
if (mIsFilterOn) {
if (null != mLocId || -1 < mExperienceId) {
if (null != mLocId) {
appender += "/loc-" + mLocId;
} else {
appender += "/loc-" + 0;
}
if (-1 < mExperienceId) {
appender += "/exp-" + mExperienceId;
} else {
appender += "/exp-" + 0;
}
}
}
String url = mUrl + appender + "/pg-" + pageNumber;
if (mIsDefaultList && AccountUtils.isLoggedIn()) {
url += "?" + Constant.MAP_COOKIE_KEY + "=" + AccountUtils.getCookie();
}
return url;
}
private void fetchJobs(String url) {
mIsFetching = true;
mLogger.d("url :" + url);
int method = mIsDefaultList ? Method.GET : Method.POST;
CookieStringRequest request = new CookieStringRequest(method, url, mListener, mErrorListener);
request.setTag(mRequestTag);
mRequestQueue.add(request);
}
private Response.Listener<String> mListener = new Listener<String>() {
#Override
public void onResponse(String response) {
mLogger.d("response :" + response);
JsonParserTask<JobList> jsonTask = new JsonParserTask<JobList>(new JobsProcessor());
jsonTask.setListener(mJsonListener);
jsonTask.execute(response);
}
};
private Response.ErrorListener mErrorListener = new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mIsFetching = false;
Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_LONG).show();
}
};
private JsonParsingListener<JobList> mJsonListener = new JsonParsingListener<JobList>() {
#Override
public void onSuccess(JobList result) {
if (null == mPagination) {
mPagination = result.getPagination();
mPagination.setCurrentPage(0);
if(null == result.getJobs() || 0 == result.getJobs().size()) {
mMessageView.setText(getArguments().getString(ARG_EMPTY_MESSAGE));
mMessageView.setVisibility(View.VISIBLE);
} else {
mMessageView.setVisibility(View.GONE);
}
} else {
mPagination.updateData(result.getPagination());
}
if (null != mJobs) {
mJobs.addAll(result.getJobs());
} else {
mJobs = result.getJobs();
}
mAdapter.setJobList(mJobs);
mAdapter.notifyDataSetChanged();
mIsFetching = false;
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getActivity(), "Unable to process response", Toast.LENGTH_LONG).show();
mIsFetching = false;
}
};
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Job job = (Job) mAdapter.getItem(position);
Intent intent = new Intent(getActivity(), JobDetailsActivity.class);
intent.putExtra(JobDetailsActivity.EXTRA_JOB, job);
startActivity(intent);
}
};
// this is the function where I also found that might cause some problem because when I scrolls down the items in the list repeated.
private OnScrollListener mOnScrollListener = new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;
if (loadMore && totalItemCount > 0 && null != mPagination) {
boolean isLastPage = mPagination.getCurrentPage() >= mPagination.getTotalPages();
if (isLastPage) {
mFooterProgress.setVisibility(View.GONE);
}
if (!mIsFetching && !isLastPage) {
fetchJobs(getUrl(mPagination.getCurrentPage()+1));
}
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Activity.RESULT_OK == resultCode) {
switch (requestCode) {
case REQUEST_EXPERIENCE:
onExperienceSelection(data);
break;
case REQUEST_LOCATION:
onLocationSelection(data);
break;
}
}
}
add one more line in your function:
mjob.clear();
private JsonParsingListener<JobList> mJsonListener = new JsonParsingListener<JobList>() {
#Override
public void onSuccess(JobList result) {
if (null == mPagination) {
mPagination = result.getPagination();
mPagination.setCurrentPage(0);
if(null == result.getJobs() || 0 == result.getJobs().size()) {
mMessageView.setText(getArguments().getString(ARG_EMPTY_MESSAGE));
mMessageView.setVisibility(View.VISIBLE);
} else {
mMessageView.setVisibility(View.GONE);
}
} else {
mPagination.updateData(result.getPagination());
}
if (null != mJobs) {
mJobs.clear();
mJobs.addAll(result.getJobs());
} else {
mJobs = result.getJobs();
}
mAdapter.setJobList(mJobs);
mAdapter.notifyDataSetChanged();
mIsFetching = false;
}

read json and insert in list view

i want to read from json on url address to list view but there is noting to show.
this is my code.
main activity.
package customlistviewvolley;
import com.example.customlistviewvolley.R;
/*import java.io.IOException;
import java.io.InputStream;*/
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import customlistviewvolleyadater.CustomListAdapter;
import customlistviewvolleyapp.AppController;
import customlistviewvolleymodel.App;
public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://192.168.1.5/public_html/android/new.json";
private ProgressDialog pDialog;
private List<App> appList = new ArrayList<App>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, appList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest appReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
App app = new App();
app.setAppTitle(obj.getString("app_title"));
app.setAppImageUrl(obj.getString("app_image"));
app.setRatingBar(((Number) obj.get("app_rating"))
.doubleValue());
app.setAppCreator(obj.getString("app_creator"));
app.setAppCase(obj.getString("app_case"));
// adding app to app array
appList.add(app);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(appReq);
}
/* JSONObject obj1 = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj1.getJSONArray("apps");
//ArrayList<HashMap<String, String>> formList= new ArrayList<HashMap<String, String>>();
// HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++) {
try {
JSONObject obj = m_jArry.getJSONObject(i);
App app = new App();
app.setAppTitle(obj.getString("app_title"));
app.setAppImageUrl(obj.getString("app_image"));
app.setRatingBar(((Number) obj.get("rating_bar"))
.doubleValue());
app.setAppCreator(obj.getString("app_creator"));
app.setAppCase(obj.getString("app_case"));
// adding movie to movies array
appList.add(app);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Same way for other value...
}*/
/*public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("jsonfile.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
} */
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
custom adapter.
package customlistviewvolleyadater;
import com.example.customlistviewvolley.R;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import customlistviewvolleyapp.AppController;
import customlistviewvolleymodel.App;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<App> appItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<App> appItems) {
this.activity = activity;
this.appItems = appItems;
}
#Override
public int getCount() {
return appItems.size();
}
#Override
public Object getItem(int location) {
return appItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.top_new_free, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView appImage = (NetworkImageView) convertView
.findViewById(R.id.app_image);
TextView appTitle = (TextView) convertView.findViewById(R.id.app_title);
TextView appCase = (TextView) convertView.findViewById(R.id.app_case);
TextView appCreator = (TextView) convertView.findViewById(R.id.app_creator);
RatingBar ratingBar = (RatingBar) convertView.findViewById(R.id.app_rating_bar);
// getting app data for the row
App app = appItems.get(position);
// app image
appImage.setImageUrl(app.getAppImageUrl(), imageLoader);
// title
appTitle.setText(app.getAppTitle());
// app creator
appCreator.setText( app.getAppCreator());
// appCase
appCase.setText(app.getAppCase());
// rating bar
ratingBar.setNumStars((int) app.getRatingBar());
return convertView;
}
}
app controller.
package customlistviewvolleyapp;
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import customlistviewvolleyutil.LruBitmapCache;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
app.
package customlistviewvolleymodel;
public class App {
private String appTitle, appImageUrl, appCreator;
private double ratingBar;
private String appCase;
public App() {
}
public App(String appName, String appImageUrl, String appCreator, double ratingBar,
String appCase) {
this.appTitle = appName;
this.appImageUrl = appImageUrl;
this.appCreator = appCreator;
this.ratingBar = ratingBar;
this.appCase = appCase;
}
public String getAppTitle() {
return appTitle;
}
public void setAppTitle(String name) {
this.appTitle = name;
}
public String getAppImageUrl() {
return appImageUrl;
}
public void setAppImageUrl(String appImageUrl) {
this.appImageUrl = appImageUrl;
}
public String getAppCreator() {
return appCreator;
}
public void setAppCreator(String appCreator) {
this.appCreator = appCreator;
}
public double getRatingBar() {
return ratingBar;
}
public void setRatingBar(double ratingBar) {
this.ratingBar = ratingBar;
}
public String getAppCase() {
return appCase;
}
public void setAppCase(String appCase) {
this.appCase = appCase;
}
}
here is my cache code .
` `package customlistviewvolleyutil;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
my main activity xml .
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:padding="5dip"
android:clipToPadding="false"
android:listSelector="#drawable/list_row_selector" />
</RelativeLayout>
my rows here .
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp" >
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/app_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp" />
<!-- App(movie) Title -->
<TextView
android:id="#+id/app_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/app_image"
android:layout_toLeftOf="#+id/app_image"
android:textSize="#dimen/title"
android:textStyle="bold" />
<!-- App Creator -->
<TextView
android:id="#+id/app_creator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/app_image"
android:layout_toLeftOf="#+id/app_image"
android:textSize="#dimen/creator"
android:layout_marginTop="1dip"
android:textStyle="bold" />
<!-- Type Free or NotFree or Installed -->
<TextView
android:id="#+id/app_case"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:textColor="#color/year"
android:textSize="#dimen/type" />
<!-- Rating Bar -->
<RatingBar
android:id="#+id/app_rating_bar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_toLeftOf="#+id/app_image"
android:layout_below="#+id/app_creator"
android:stepSize="0.5" />
</RelativeLayout>
plz help me to fix it.
You should access localhost sites in such a way:
http://localhost:8080/MyTestPage.html
Read this to get further information:
http://www.androidref.com//index.html#LocalBrowser

Categories

Resources