Can't use Volley to display two custom ListView - android

I am a beginner in android, and i am trying to use Volley to create a custom list which contains list of images and text description for each. There are two activities as list view, downloaded json data using volley, use OnItemClickListener to start other activity. the first activity is complete to run, when i click the other one, the Logcat got nothing to show, but the second Listview activity is blank only have title...
This is Logcat i don't it has usefully or not.
All my Logcat
05-22 16:09:32.549: V/Monotype(14980): SetAppTypeFace- try to flip, app = com.wangjian.klmeet_sightseeing
05-22 16:09:32.550: V/Monotype(14980): Typeface getFontPathFlipFont - systemFont = default
05-22 16:09:33.378: D/Volley(14980): [1] 2.onErrorResponse: MainActivity
my code look like this:
The first activity SightseeingActivity.java
public class SightseeingActivity extends Activity {
//Log tag
private static final String TAG = SightseeingActivity.class.getSimpleName();
//Sightseeing json url
private static final String url = "http://wangjian.site90.net/json/api_klmeet_sightseeing.json";
private ProgressDialog pDialog;
private List<Sight> sightList = new ArrayList<Sight>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sightseeing_activity);
listView = (ListView) findViewById(R.id.sight_list);
adapter = new CustomListAdapter(this, sightList);
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 sightReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response){
Log.d(TAG, response.toString());
pDialog.dismiss();
for (int i = 0; i < response.length(); i++){
try{
JSONObject obj = response.getJSONObject(i);
Sight sight = new Sight();
sight.setTitle(obj.getString("title"));
sight.setThumbnailUrl(obj.getString("image"));
sight.setReadmore(obj.getString("readmore"));
sight.setPreintroduce(obj.getString("preintroduce"));
sight.setTag(obj.getString("tag"));
sightList.add(sight);
} 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());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(sightReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Class<? extends Activity> activityToSrart = null;
switch (position){
case 0:
activityToSrart = MainActivity.class;
break;
case 1:
activityToSrart = MerdekaSquare.class;
break;
}
Intent i = new Intent(getApplicationContext(), activityToSrart);
startActivity(i);
}
});
}
}
The second activity MainActivity
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://wangjian.site90.net/json/api_klmeet_sightseeing_face.json";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
i will upload more code if needed.
FeedListAdapter.java
#SuppressLint("InflateParams")
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.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.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
FeedIteam
package com.wangjian.klmeet_sightseeing.model;
public class FeedItem {
private int id;
private String name, status, image, profilePic, timeStamp, url;
public FeedItem() {
}
public FeedItem(int id, String name, String image, String status,
String profilePic, String timeStamp, String url) {
super();
this.id = id;
this.name = name;
this.image = image;
this.status = status;
this.profilePic = profilePic;
this.timeStamp = timeStamp;
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
i upload XML file if needed
feed_item.xml
<?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:background="#color/feed_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="#dimen/feed_item_margin"
android:layout_marginRight="#dimen/feed_item_margin"
android:layout_marginTop="#dimen/feed_item_margin"
android:background="#drawable/bg_parent_rounded_corner"
android:orientation="vertical"
android:paddingBottom="#dimen/feed_item_padding_top_bottom"
android:paddingTop="#dimen/feed_item_padding_top_bottom" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="#dimen/feed_item_padding_left_right"
android:paddingRight="#dimen/feed_item_padding_left_right" >
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/profilePic"
android:layout_width="#dimen/feed_item_profile_pic"
android:layout_height="#dimen/feed_item_profile_pic"
android:scaleType="fitCenter" >
</com.android.volley.toolbox.NetworkImageView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="#dimen/feed_item_profile_info_padd" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
<TextView
android:id="#+id/timestamp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/timestamp"
android:textSize="#dimen/feed_item_timestamp" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/txtStatusMsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="#dimen/feed_item_status_pad_left_right"
android:paddingRight="#dimen/feed_item_status_pad_left_right"
android:paddingTop="#dimen/feed_item_status_pad_top" />
<TextView
android:id="#+id/txtUrl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:linksClickable="true"
android:paddingBottom="10dp"
android:paddingLeft="#dimen/feed_item_status_pad_left_right"
android:paddingRight="#dimen/feed_item_status_pad_left_right"
android:textColorLink="#color/link" />
<info.androidhive.listviewfeed.FeedImageView
android:id="#+id/feedImage1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:scaleType="fitXY"
android:visibility="visible" />
</LinearLayout>
</LinearLayout>
This is my first activity
the second one should be like this
But
JSON
{
"feed": [
{
"id": 1,
"name": "National Geographic Channel",
"image": "http://api.androidhive.info/feed/img/cosmos.jpg",
"status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": null
},
{
"id": 2,
"name": "TIME",
"image": "http://api.androidhive.info/feed/img/time_best.jpg",
"status": "30 years of Cirque du Soleil's best photos",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg,
"timeStamp": "1403375851930",
"url": "http://ti.me/1qW8MLB"
},
{
"id": 5,
"name": "Abraham Lincoln",
"image": null,
"status": "That some achieve great success, is proof to all that others can achieve it as well",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": null
},
{
"id": 3,
"name": "Discovery",
"image": "http://api.androidhive.info/feed/img/discovery_mos.jpg",
"status": "A team of Austrian scientists has developed a laser system that causes fruit flies to dance.",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://dsc.tv/xmMxD"
},
{
"id": 4,
"name": "Ravi Tamada",
"image": "http://api.androidhive.info/feed/img/nav_drawer.jpg",
"status": "Android Sliding Menu using Navigation Drawer",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/"
},
{
"id": 6,
"name": "KTM",
"image": "http://api.androidhive.info/feed/img/ktm_1290.jpg",
"status": "\"The Beast\" KTM 1290 Super Duke",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": ""
},
{
"id": 7,
"name": "Harley-Davidson",
"image": "http://api.androidhive.info/feed/img/harley_bike.jpg",
"status": "We’re assembling riders of every style, bike, and passion. If you ride with conviction, ride with us. You have 24 days to get ready for World Ride. Prepare by visiting:",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://bit.ly/1wmBWaN"
},
{
"id": 8,
"name": "Rock & Girl",
"image": "http://api.androidhive.info/feed/img/rock.jpg",
"status": "A long time back...",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": ""
},
{
"id": 8,
"name": "Gandhi",
"image": null,
"status": "An eye for an eye will make the whole world blind.",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": ""
},
{
"id": 9,
"name": "LIFE",
"image": "http://api.androidhive.info/feed/img/life_photo.jpg",
"status": "In 1965, LIFE photographer Bill Ray spent weeks with the Hells Angels, but his amazing photos never ran in the magazine",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://ti.me/1rfcQa4"
},
{
"id": 10,
"name": "Shakira",
"image": "http://api.androidhive.info/feed/img/shakira_la_la.png",
"status": "Download La La La (Brazil 2014) from iTunes:",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": "http://smarturl.it/FWCalbum?IQid=sh"
},
{
"id": 11,
"name": "A. R. rahman",
"image": "http://api.androidhive.info/feed/img/ar_bw.jpg",
"status": "",
"profilePic": "http://wangjian.site90.net/json/klcc.jpg",
"timeStamp": "1403375851930",
"url": ""
}
]
}
I'm a newbie at this stuff so any help will be appreciated. Thanks in Advance.!

Firstly, private String URL_FEED = "http://wangjian.site90.net/json/api_klmeet_sightseeing_face.json"; in your MainActivity doesn't exist and when I tried it in AdvanceRestClient I got this:
So I tried looking more into directory structure of your WS and found there isn't any such URL you have mentioned as above.
Further more, I got security issues while trying to access your directory:
I am not sure what you are looking for seriously, but you could try with a valid URL in MainActivity and it should work fine.
Security issue creep me out literaly. :(

Related

Troubles with JSON parsing

I'm working on a simple news app.
I need to fetch data from a remote server in JSON format then put it in view. I use TabLayout and recyclerView to display data categories and Volley for the query no API here.
The TabLayout is set automatically depending on data from JSON where I extract tabs title and the content of every tab is being displayed on recyclerView (Article title, image, content, links...) and rendered inside a fragment
I spent several hours trying to debug it without success., but whatever I do, no data is being displayed. Not sure what I'm doing wrong.
I know this is not the right place to ask for such things, but I'm a bit of a desperate and would need some experienced developer than me look at my problem.
How it works:
Activity launches BaseArticleFragment which calls a method that loads contents categories and bind the data to the views:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.fm = getSupportFragmentManager();
this.baseArticleFragment = new BaseArticleFragment();
FragmentTransaction ft = this.fm.beginTransaction();
ft.add(R.id.fragment_container, this.baseArticleFragment, TAB_LAYOUT_FRAGMENT_TAG);
ft.commit();
}
When launched, baseArticleFragment calls loadCategories() method inside its onActivityCreated() method:
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
loadCategories();
}
here is the loadCategories() method:
private void loadCategories(){
String url = "http://somesite.com/categories"; //link to grab the json data
ApplicationController.getInstance().addToRequestQueue(
new JsonObjectRequest(0, url, null, new Listener<JSONObject>() { //0 is the Volley code for GET method
#Override
public void onResponse(JSONObject jsonObject) {
BaseArticleFragment.categories = JSONParser.parseCategories(jsonObject);
BaseArticleFragment.this.mViewPager.setAdapter(
new RecyclerViewFragmentPagerAdapter(BaseArticleFragment.this.getChildFragmentManager(),
BaseArticleFragment.categories));
BaseArticleFragment.this.mTabLayout.setupWithViewPager(BaseArticleFragment.this.mViewPager);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError vError){
Log.d("BaseArticleFragment", "---Volley Error---");
Snackbar.make(BaseArticleFragment.this.mTabLayout, R.string.error_load_categories, Snackbar.LENGTH_SHORT)
.setAction(R.string.action_retry, new View.OnClickListener() {
#Override
public void onClick(View v) {
BaseArticleFragment.this.loadCategories();
}
}).show();
}
}));
}
I guess the problem may be with the query but not sure cause I think my logic here is good
EDIT :
Here is the JSON data I need to fetch:
[
{
"name": "Topic 1",
"tid": "2",
},
{
"name": "Topic 2",
"tid": "3",
},
{
"name": "Topic 3",
"tid": "4",
},
{
"name": "Topic 4",
"tid": "5",
},
{
"name": "Topic 5",
"tid": "6",
},
{
"name": "Topic 6",
"tid": "1415",
},
{
"name": "Topic 7",
"tid": "1414",
},
{
"name": "Topic 8",
"tid": "1298",
},
{
"name": "Topic 9",
"tid": "1301",
},
{
"name": "Topic 10",
"tid": "1299",
},
{
"name": "Topic 11",
"tid": "1302",
},
{
"name": "Topic 12",
"tid": "1300",
},
{
"name": "Topic 13",
"tid": "1297",
}
]
Edit 2:
I forget to paste the code for parseCategories() in my JSONPArser class
public static ArrayList<Category> parseCategories(JSONObject jsonObject) {
ArrayList<Category> categoryArrayList = new ArrayList<>();
try {
JSONArray categories = jsonObject.getJSONArray("categories");
Category all = new Category();
all.setTid("0");
all.setName(ApplicationController.getInstance().getString(R.string.tab_all));
categoryArrayList.add(all);
for (int i = 0; i < categories.length(); i++) {
JSONObject catObject = categories.getJSONObject(i);
Category category = new Category();
category.setTid(catObject.getString("tid"));
category.setName(catObject.getString("name"));
categoryArrayList.add(category);
}
return categoryArrayList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
Try this #esQmo_,
StringRequest stringRequest = new StringRequest(url , new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
ArrayList<Hashmap<String,String>> arraylist = new
ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> hashMap = new HashMap<>();
String name =
jsonArray.getJSONObject(i).getString("name");
String tid =
jsonArray.getJSONObject(i).getString("tid");
hashMap.put("name", name);
hashMap.put("tid ", tid );
arraylist.add(hashMap);
Log.e("response",name + "\n" + tid);
}
attachAdapter(arraylist);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
//setting adapter data to the RecyclerView
private void attachAdapter(ArrayList<HashMap<String, String>>
arrayList) {
ExampleAdapter adapter = new ExampleAdapter(arrayList,this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
This is the adapter class
public class ExampleAdpater extends RecyclerView.Adapter<ExampleAdpater.ExampleViewHolder>{
public ArrayList<HashMap<String,String>> arraylist;
public Context context;
public ExampleAdpater(ArrayList<HashMap<String, String>> arraylist, Context context) {
this.arraylist= arraylist;
this.context = context;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.textLayout,viewGroup,false);
return new ExampleViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder viewHolder, int i) {
HashMap<String,String> hashMap = arraylist.get(i);
viewHolder.name.setText(hashMap.get("name"));
viewHolder.tid.setText(hashMap.get("tid"));
}
#Override
public int getItemCount() {
return arraylist.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder{
TextView name,tid;
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
tid = itemView.findViewById(R.id.tid);
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), ""+name.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
textLayout.xml
<?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" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tid"
/>
</LinearLayout>
You forgot to add this thing at the end of the "load" method:
Volley.newRequestQueue(this).add(jsonRequest);
Try to add it...
Instead of using new RequestQueue, please use RequestQueue jsonQueue = new RequestQueue
Like this:
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "https://someurl.com/api";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray ja = new JSONArray(response);
for(int i = 0; i < ja.length(); i++)
{
JSONObject jo = ja.get(i);
String name = jo.getString("name");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG", error.toString());
}
});
requestQueue.add(jsonObjectRequest);
Just check if you have set LayoutManager for recyclerView
recyclerView.setLayoutManager(new LinearLayoutManager(MyActivity.this));
Can we have your code and JSON data too? Since we can't read what's on your mind or on your computer... Plase make some edits to your post, add code and json data so we may help you.
Since you are getting a timeout error you can change the timeout value so that it will be willing to wait longer.
Try something like this:
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
where MY_SOCKET_TIMEOUT_MS is amount of time (in milliseconds) you want to wait before a timeout. Start with 5000 (5 seconds) and play around with it.
Do this before
requestQueue.add(jsonObjectRequest);

RatingBar display on ListView with ratings from Json parse

How to set the ratings of RatingBar that the data are from MySQL database pass by json, I don't know where I am doing wrong but I can manage to display the name, but the ratings is not functioning, for example in the name Sample have a rating of 4.5 so in the output RatingBar will set the star in a value of 4.5.
Sample Json Data:
{
"item": [
{
"id": "1",
"name": "Sample",
"description": "Sample",
"ratings": "4.5"
},
{
"id": "2",
"name": "Sample1",
"description": "Sample1",
"ratings": "1.5"
},
{
"id": "3",
"name": "Wow Magic",
"description": "Amazing",
"ratings": "4"
},
{
"id": "4",
"name": "Capstone with ROS",
"description": "Amazing diba",
"ratings": "5"
},
{
"id": "5",
"name": "asdasdasdasdasasdasdasdasdasdasdasdasdasd",
"description": "asdas",
"ratings": "3"
}
],
"success": 1
}
Now this is my code for displaying it
public class ItemFragment extends Fragment {
private String TAG = ItemFragment.class.getSimpleName();
private ListView mListView;
RatingBar ratess;
ArrayList<HashMap<String, String>> itemList;
public static ItemFragment newInstance() {
ItemFragment fragment = new ItemFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void findViews(View view)
{
itemList = new ArrayList<>();
mListView = (ListView) view.findViewById(R.id.listView);
new GetItems().execute();
}
private class GetItems extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(getActivity(), "Retrieving data", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http://10.20.18.204/FindForMe/show.php";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null){
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray items = jsonObj.getJSONArray("item");
for (int i = 0; i < items.length(); i++){
JSONObject c = items.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("name");
String description = c.getString("description");
String ratings = c.getString("ratings");
HashMap<String, String> itemm = new HashMap<>();
itemm.put("id",id);
itemm.put("name", title);
itemm.put("description", description);
itemm.put("ratings", ratings);
itemList.add(itemm);
}
}
catch (final JSONException e){
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(getActivity(), itemList, R.layout.customlayout, new String[]{"name","ratings"}, new int[]{R.id.item_title,R.id.ratings});
mListView.setAdapter(adapter);
}
}
View myView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_item, container, false);
findViews(myView);
return myView;
}
}
This is my layour xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="120dp"
android:layout_height="120dp"
app:srcCompat="#mipmap/ic_launcher"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="10dp"
android:id="#+id/imageViewer"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="20dp"/>
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_marginLeft="19dp"
android:layout_marginStart="19dp"
android:layout_alignTop="#+id/imageViewer"
android:layout_toRightOf="#+id/imageViewer"
android:layout_toEndOf="#+id/imageViewer"
android:id="#+id/item_title"/>
<ImageView
android:id="#+id/imageView"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignLeft="#+id/item_title"
android:layout_alignStart="#+id/item_title"
android:layout_below="#+id/item_title"
app:srcCompat="#drawable/location2" />
<RatingBar
android:id="#+id/ratings"
style="#android:style/Widget.Holo.RatingBar.Indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView"
android:layout_below="#+id/imageView"
android:layout_marginTop="7dp"
android:numStars="5"
android:stepSize=".5"/>
</RelativeLayout>
You need to set your ratings in ratingBar in listview adapter. In your adapter's getView() method:
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent)
{
viewHolder.ratess= (RatingBar) convertView.findViewById(R.id.ratess);
viewHolder.ratess.setRating(yourModel.getRatingValue());
}

JSON parsing and displaying into a recycler-card view fragment

I am trying to parse json with volley and display with recycler-card view in my tabbed fragment class in android. The json response is not displayed in the fragment. No errors or exceptions are shown. The app runs fine but no data is displayed. Take a look at the code below and tell me where I went wrong.
My Fragment Class
public class Latest_News extends Fragment {
private RecyclerView recyclerView;
private List<NewsItems> newsItemsList = new ArrayList<>();
private static final String TAG = Latest_News.class.getSimpleName();
private NewsItems newsItems;
public Latest_News() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
networkAvailable();
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View mView = inflater.inflate(R.layout.fragment_latest__news, container, false);
recyclerView = (RecyclerView) mView.findViewById(R.id.latestNews_recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llMan = new LinearLayoutManager(getContext());
llMan.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llMan);
//recyclerView.setAdapter(new HomeFrag_RecyclerAdapter(getActivity(), newsItemsList));
if (networkAvailable()){
String url = "www.goal.com/api"; // fake url, pls dont mind
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject newsObject = new JSONObject(response.toString());
String title = newsObject.getString("title");
String time = newsObject.getString("time");
String date = newsObject.getString("date");
String link = newsObject.getString("link");
String content = newsObject.getString("content");
String image = newsObject.getString("image" + "");
newsItems = new NewsItems();
newsItems.setImage_Id(Integer.parseInt(image));
newsItems.setNewsDate(date);
newsItems.setNewTitle(title);
newsItems.setNewsDesc(content);
newsItems.setNewsUrl(link);
newsItems.setNewsTime(time);
newsItemsList.add(newsItems);
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setAdapter(new HomeFrag_RecyclerAdapter(getActivity(), newsItemsList));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,"Error is: " + error.toString());
}
});
mRequestQueue.add(jsonObjectRequest);
}
else{
Toast.makeText(getActivity(), "Turn On Mobile Data or Wifi", Toast.LENGTH_SHORT).show();
}
return mView;
}
private boolean networkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
}
Fragment Adapter Code is Shown Below:
public class HomeFrag_RecyclerAdapter extends RecyclerView.Adapter<HomeFrag_RecyclerAdapter.MyHolder> {
private Context context;
List<NewsItems> newsItemsList;
public HomeFrag_RecyclerAdapter(Context context, List<NewsItems> newsItemsList) {
this.context = context;
this.newsItemsList = newsItemsList;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.tab_frags_customview,parent,false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.title.setText(newsItemsList.get(position).getNewTitle());
holder.descn.setText(newsItemsList.get(position).getNewsDesc());
holder.time.setText(newsItemsList.get(position).getNewsTime());
holder.date.setText(newsItemsList.get(position).getNewsDate());
int i = position;
Picasso.with(context).load(newsItemsList.get(i).getImage_Id())
.centerCrop()
.error(R.drawable.ic_toc_black_24dp)
.into(holder.coverImg);
}
#Override
public int getItemCount() {
return newsItemsList.size();
}
public class MyHolder extends RecyclerView.ViewHolder{
private TextView title, descn, time, date;
private ImageView coverImg;
public MyHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.news_titleTxt);
descn = (TextView) itemView.findViewById(R.id.news_DescTxt);
time = (TextView) itemView.findViewById(R.id.news_TimeTxt);
date = (TextView) itemView.findViewById(R.id.newsDateTxt);
coverImg = (ImageView) itemView.findViewById(R.id.newsImage);
}
}
}
Sample JSON to be parsed
<pre>
{
"0": {
"image": null,
"title": "Suresh Raina to miss 2nd ODI against New Zealand ",
"time": "08:29 pm ",
"date": "18 Oct ",
"content": "Indian cricketer Suresh Raina will miss the second ODI against New Zealand at Delhi on Thursday. ...",
"link": "https://full-story.newsinshorts.com/v1/article/a659a7be-0c4d-408c-851d-689da6b95498-1 "
},
"1": {
"image": null,
"title": "Harley-Davidson net income falls by 18.67% to $114 mn ",
"time": "08:29 pm ",
"date": "18 Oct ",
"content": "Motorcycle manufacturer Harley-Davidson on Tuesday reported an 18.67% year-on-year decline in net ...",
"link": "https://full-story.newsinshorts.com/v1/article/448cc170-1d42-4109-9c50-0fe3a3c36f44-1 "
},
"2": {
"image": null,
"title": "JNU to get 200 solar power operated street lights ",
"time": "08:27 pm ",
"date": "18 Oct ",
"content": "The Jawaharlal Nehru University in Delhi is set to get 200 solar power operated street lights, Vice ...",
"link": "https://full-story.newsinshorts.com/v1/article/96db26c8-be8f-4313-8d51-27fee9bd084d-1 "
},
"3": {
"image": null,
"title": "Patiala Court dismisses fake degree case against Irani ",
"time": "08:22 pm ",
"date": "18 Oct ",
"content": "Patiala House Court today dismissed a case against Union Minister Smriti Irani for allegedly ...",
"link": null
},
</pre>
XML layout for the Fragment Class above:
<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="com.example.joey.mydrawerapp.Fragments.HomeFragment_Fragments.Latest_News">
<!-- TODO: Update blank fragment layout -->
<include layout="#layout/recyclerview_layout"
android:id="#+id/latestNews_recyclerView"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:gravity="center"
android:textStyle="bold"
android:text="Stay Tuned For Latest News" />
</RelativeLayout>
I generally don't parse JSON by hand anymore, I always use Gson or jackson. Provided your json is correct, your onResponse can look something like this:
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
#Override
public void onResponse(Stringresponse) {
Gson gson = new Gson();
Map<String,Item> map = gson.fromJson(response, new TypeToken<Map<String,Item>>(){}.getType());
newsItemLists = new ArrayList(); // Clear the list if desired
for (Item item : map.values()) {
newsItems = new NewsItems();
// Copy all item attributes to newsItems here.
// if NewsItems is annotated correct, it can even be used to parse
// the json instead of the Item class below.
newsItemsList.add(newsItems);
}
// Move this line into the onCreate() initializng the adapter with an empty list.
//recyclerView.setAdapter(new HomeFrag_RecyclerAdapter(getActivity(), newsItemsList));
// add this to notify the adapter that the list has changed.
adapter.notifyDataSetChanged();
}
You will need a pojo for the gson object:
class Item {
String image;
String title;
String time;
String date;
String content;
String link;
}
Update
I've updated my answer just a bit to make a StringRequest Volley instead of a JSONRequest. We'll use the whole string response and parse it as JSON. Alternatively, you can change your Volley JsonObjectRequest to a JsonArrayRequest and receive a JSON array. Then you'll loop over each item in the array and parse it out.

Dyanamic tabs in android with dynamic content from json

I m creating dynamic tabs in android in which the data for the tabs is populated from the json
Following is the json response
{
"shop_details": [
{
"id": "36",
"shop_name": "All in One Mart",
"shop_no": "23223",
"shop_address": "Tinkune",
"phone": "9804966595",
"email": "arjundangal4#gmail.com",
"user_name": "arjun",
"address": "",
"tel": "",
"fax": "",
"facebook": "",
"twitter": "",
"googleplus": "",
"image": "",
"featured_image": ""
}
],
"category": [
{
"category_id": "35",
"category_name": "Skirt",
"product": [
{
"product_id": "49",
"product_name": "Skirt",
"category_id": "35",
"subcategory_id": "37",
"product_color": "blue",
"description": "Skirt for girls",
"price": "301",
"discount": "0",
"service_charge": "0",
"user_id": "36",
"image_name": "6baab8a5308b7e821f5b6387794979a4.jpeg",
"created_at": "2016-07-04 03:54:54"
}
]
},
{
"category_id": "36",
"category_name": "Men",
"product": [
{
"product_id": "48",
"product_name": "Glasses",
"category_id": "36",
"subcategory_id": "39",
"product_color": "red",
"description": "Glasses of Rayban",
"price": "594",
"discount": "23",
"service_charge": "22",
"user_id": "36",
"image_name": "fce01420a9021fdb159226b4bdc5b591.jpg",
"created_at": "2016-07-04 03:52:58"
}
]
},
{
"category_id": "37",
"category_name": "Bags",
"product": [
{
"product_id": "50",
"product_name": "Laptop bag",
"category_id": "37",
"subcategory_id": "41",
"product_color": "black",
"description": "Bag to carry laptop",
"price": "190",
"discount": "2",
"service_charge": "3",
"user_id": "36",
"image_name": "e836e090a54cd2b6b594fa0a3382bb38.jpg",
"created_at": "2016-07-04 04:14:08"
}
]
}
]
}
Following is the code to fetch in which i add the tabs dynamically
private void getShopDetails() {
coordinatorLayout.setVisibility(View.GONE);
new ProgressDialog(this);
ProgressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ProgressDialog.dismiss();
coordinatorLayout.setVisibility(View.VISIBLE);
try {
JSONArray shopDetailsArray = response.getJSONArray("shop_details");
JSONObject shopDetailsObj = shopDetailsArray.getJSONObject(0);
shopName = shopDetailsObj.getString("shop_name");
phone = shopDetailsObj.getString("tel");
shopNum = shopDetailsObj.getString("shop_no");
shopAddress = shopDetailsObj.getString("shop_address");
shopImage = shopDetailsObj.getString("featured_image");
Glide.with(getApplicationContext()).load("http://allmartapp.com/appapi/uploads/" + shopImage).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(backdrop);
colLayout.setTitle(shopName);
address.setText("Address - Shop no -" + shopNum + ", " + shopAddress);
JSONArray tabsArray = response.getJSONArray("category");
categoryId = new int[tabsArray.length()];
for (int i = 0; i < tabsArray.length(); i++) {
JSONObject tabsObj = tabsArray.getJSONObject(i);
tabLayout.addTab(tabLayout.newTab().setText(tabsObj.getString("category_name")));
categoryId[i] = tabsObj.getInt("category_id");
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
ShopDetailsTabsFragment.sgetid(categoryId[tab.getPosition()]);
Log.d("CATIID", categoryId[tab.getPosition()] + "");
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ProgressDialog.dismissWithError();
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
In ontabselected() i assigned the category id according to the position of the tabs and call the sgetid() function which is in the fragment
My pageradapter returns only one Fragment with the recyclerview.
Following is the Fragment code
public class ShopDetailsTabsFragment extends Fragment {
RecyclerView recyclerView;
boolean isViewShown = false;
CategoryListItemsAdapter shopListRvAdapters;
private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
ArrayList<CategoryItemsListModel> arrayList = new ArrayList<>();
static int catid = 0;
int shopId;
public ShopDetailsTabsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_shop_details_tabs, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.rv);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
shopId = sharedPreferences.getInt("shopid", 0);
return v;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
getShopCat();
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
} else {
isViewShown = false;
}
}
public static void sgetid(int cat) {
catid = cat;
}
private void getShopCat() {
recyclerView.setAdapter(null);
shopDetailsJsonUrl += shopId;
arrayList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("JSON", response.toString());
try {
JSONArray categoryArray = response.getJSONArray("category");
for (int i = 0; i < categoryArray.length(); i++) {
JSONObject catObj = categoryArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid) {
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++) {
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("product_id");
CategoryItemsListModel shopListRvModels = new CategoryItemsListModel(id, image, name, price);
arrayList.add(shopListRvModels);
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
shopListRvAdapters.notifyDataSetChanged();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
shopDetailsJsonUrl = baseshopDetailsJsonUrl;
}
}
My problem is that, the tabs are showing strange behaviors. I know that the logic to fetch the category lists is correct. But I think there is problem in the state of the fragment. When i switch the tabs, the data loaded in the tabs are sometimes duplicated and even the data are loaded twice sometimes. Any suggestions are appreciated as im facing the problem for couple of days. I want to know the easy way to load the data in the tabs.
Try below code if it helps:
public class ShopDetailsTabsFragment extends Fragment {
RecyclerView recyclerView;
boolean isViewShown = false;
CategoryListItemsAdapter shopListRvAdapters;
private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
ArrayList<CategoryItemsListModel> arrayList = new ArrayList<>();
static int catid = 0;
int shopId;
public ShopDetailsTabsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_shop_details_tabs, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.rv);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
shopId = sharedPreferences.getInt("shopid", 0);
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
return v;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
getShopCat();
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
} else {
isViewShown = false;
}
}
public static void sgetid(int cat) {
catid = cat;
}
private void getShopCat() {
recyclerView.setAdapter(null);
shopDetailsJsonUrl += shopId;
arrayList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("JSON", response.toString());
try {
JSONArray categoryArray = response.getJSONArray("category");
if(arrayList!=null){
if(arrayList.size()>0)
arrayList.clear();
}
for (int i = 0; i < categoryArray.length(); i++) {
JSONObject catObj = categoryArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid) {
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++) {
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("product_id");
arrayList.add(new CategoryItemsListModel(id, image, name, price));
}
shopListRvAdapters.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
shopDetailsJsonUrl = baseshopDetailsJsonUrl;
}

How to show other JsonArray in RecyclerView on Android

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 post and go to end! in this project i use okHTTP v3 and RecyclerView!
I want show title from categories in textview, but i don't know how to show this?!
My Json :
{
"status": "ok",
"count": 10,
"count_total": 28,
"pages": 3,
"posts": [{
"id": 145,
"type": "post",
"slug": "english-post-2",
"url": "http:\/\/tellfa.com\/tafrihgah\/?p=145",
"status": "publish",
"title": "English Post",
"title_plain": "English Post",
"content": "<p>This post is test for show Text and Image<\/p>\n<p><img class=\"alignnone size-medium wp-image-79\" src=\"http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-300x240.jpg\" alt=\"[WallpapersMania]_vol49-027\" width=\"300\" height=\"240\" srcset=\"http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-300x240.jpg 300w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-768x614.jpg 768w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027-1024x819.jpg 1024w, http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/04\/WallpapersMania_vol49-027.jpg 1280w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>This is image in Text<\/p>\n",
"excerpt": "<p>This post is test for show Text and Image<\/p>\n<p>This is image in Text<\/p>\n",
"date": "2016-05-01 08:20:39",
"modified": "2016-05-01 08:20:39",
"categories": [{
"id": 1,
"slug": "%d8%af%d8%b3%d8%aa%d9%87%e2%80%8c%d8%a8%d9%86%d8%af%db%8c-%d9%86%d8%b4%d8%af%d9%87",
"title": "\u062f\u0633\u062a\u0647\u200c\u0628\u0646\u062f\u06cc \u0646\u0634\u062f\u0647",
"description": "",
"parent": 0,
"post_count": 24
}],
"tags": [],
"author": {
"id": 1,
"slug": "tellfa",
"name": "\u0645\u062d\u0645\u062f",
"first_name": "",
"last_name": "",
"nickname": "\u0645\u062d\u0645\u062f",
"url": "http:\/\/codesaz.com",
"description": "\u0627\u06cc\u0646 \u0632\u0646\u062f\u06af\u06cc \u0646\u0627\u0645\u0647 \u0645\u0646 \u0627\u0633\u062a",
"avatar": "76"
},
"comments": [],
"attachments": [{
"id": 146,
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
"slug": "wallpapersmania_vol33-031",
"title": "WallpapersMania_vol33-031",
"description": "",
"caption": "",
"parent": 145,
"mime_type": "image\/jpeg",
"images": {
"full": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
"width": 1600,
"height": 1200
},
"thumbnail": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x225.jpg",
"width": 300,
"height": 225
},
"mediaphase-frontpage-news": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x220.jpg",
"width": 300,
"height": 220
},
"mediaphase-blog-large": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-700x313.jpg",
"width": 700,
"height": 313
}
}
}],
"comment_count": 0,
"comment_status": "open",
"thumbnail": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
"custom_fields": {},
"thumbnail_size": "thumbnail",
"thumbnail_images": {
"full": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031.jpg",
"width": 1600,
"height": 1200
},
"thumbnail": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-150x150.jpg",
"width": 150,
"height": 150
},
"medium": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x225.jpg",
"width": 300,
"height": 225
},
"mediaphase-frontpage-news": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-300x220.jpg",
"width": 300,
"height": 220
},
"mediaphase-blog-large": {
"url": "http:\/\/tellfa.com\/tafrihgah\/wp-content\/uploads\/2016\/05\/WallpapersMania_vol33-031-700x313.jpg",
"width": 700,
"height": 313
}
}
}
I read this title from this Array :
"categories": [{
"id": 1,
"slug": "%d8%af%d8%b3%d8%aa%d9%87%e2%80%8c%d8%a8%d9%86%d8%af%db%8c-%d9%86%d8%b4%d8%af%d9%87",
"title": "\u062f\u0633\u062a\u0647\u200c\u0628\u0646\u062f\u06cc \u0646\u0634\u062f\u0647",
"description": "",
"parent": 0,
"post_count": 24
}],
My AsyncTask codes:
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
// Thumbnail
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
// Author
JSONObject Author = postObject.optJSONObject("author");
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String dateTime = postObject.getString("date");
String thumbnail = imagesPair.getString("url");
String authorShow = Author.getString("name");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + thumbnail);
Log.d("Data", "Post category: " + authorShow);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, thumbnail));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
MainActivity code:
public class Main_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private RelativeLayout root;
private ImageView menu_image, toolbar_refresh;
private RecyclerView main_recyclerView;
private MainAdapter_loadMore mAdaper;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
protected Handler handler;
private RelativeLayout loadLayout;
private LinearLayoutManager mLayoutManager;
private int pageCount = 1;
String ServerAddress = ServerIP.getIP();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
// Initializing
handler = new Handler();
context = getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
mLayoutManager = new LinearLayoutManager(this);
loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
toolbar_refresh = (ImageView) toolbar.findViewById(R.id.toolbar_update);
// Toolbar
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
// Load First Data
LoadData();
// Menu
root = (RelativeLayout) findViewById(R.id.main_root);
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView and setData
main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
main_recyclerView.setHasFixedSize(true);
main_recyclerView.setLayoutManager(mLayoutManager);
mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
main_recyclerView.setAdapter(mAdaper);
// Load More data
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
LoadMoreData(pageCount);
}
});
// Refresh Data
toolbar_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), PostShow_page.class));
}
});
}
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
mAdaper.setLoaded();
}
mAdaper.add(mainInfoModels);
mAdaper.notifyDataSetChanged();
pageCount++;
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
private void LoadData() {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this);
}
private void LoadMoreData(int pageNumber) {
MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
// here getMainDataInfo() should return the server response
dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
}
}
Attention : Please don't give me negative points, i am amateur and i really need you helps! thanks all <3
add RecyclerView in layout
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
add dependencies
compile 'com.android.support:recyclerview-v7:23.1.1'
create a layout for each row of RecyclerView and name it list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:textColor="#color/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
create a JAVA file Model.java
public class Model {
public String title;
}
now create java file named as Adapter.java
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 Adapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
private ArrayList<Model> modelArrayList=new ArrayList<>();
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}
}
public Adapter(ArrayList<Model> modelArrayList) {
this.modelArrayList = modelArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Movie movie = moviesList.get(position);
holder.title.setText(modelArrayList.get(position).title);
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
}
in MainActivity.java
create a Arrylist of type Model
ArrayList<Model> modelArrayList=new ArrayList<>();
RecyclerView recyclerView;
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
prase data
JSONObject jsonObject = new JSONObject(ou_response);
JSONArray message = jsonObject.getJSONArray("categories");
for (int i = 0; i < message.length(); i++) {
Model model = new Model();
JSONObject temp = message.getJSONObject(i);
model.tittle = temp.getString("tittle");
modelArrayList.add(model);
}
create Adapter and set it to recyclerView
Adapter madapter = new Adapter(modelArrayList);
recyclerView.setAdapter(mAdapter);
creating RecyclerView in your xml file:
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Declare the RecyclerView and JsonArray in your Activity class :
VolleyClass volleyClass;
JSONArray jsonArray = new JSONArray();
RecyclerAdapter recyclerAdapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_head_two_head);
volleyClass = VolleyClass.getInstance(this);
//volleyClass=new VolleyClass(this);
recyclerAdapter = new RecyclerAdapter();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(HeadToHeadRandom.this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recyclerAdapter);
Retrieve Json data :
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL.HEADTOHEAD_LIST.getURL(), urlObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("onResponse", response.toString());
try {
jsonArray = response.getJSONArray("Categories");
if (jsonArray != null) {
recyclerAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
mDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
mDialog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", System.getProperty("http.agent"));
return headers;
}
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
volleyClass.addToRequestQueue(jsObjRequest);
Adapter Class like this:
class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.HaderView> {
#Override
public HaderView onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_head_to_head, parent, false);
lastItem = recyclerView.getChildAdapterPosition(view);
return new HaderView(view);
}
#Override
public void onBindViewHolder(HaderView holder, int position) {
try {
holder.tv_category.setText(jsonArray.getJSONObject(position).getString("title"));
String image_path = jsonArray.getJSONObject(position).getString("icon");
if (image_path != null) {
imageLoader.displayImage(image_path, holder.img_head_to_head, options);
}
} catch (JSONException e) {
e.printStackTrace();
}
final int posi = position;
holder.tv_category.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String category_id = jsonArray.getJSONObject(posi).getString("id");
startActivity(new Intent(HeadToHead.this, HTHActivity.class).putExtra("category_id", category_id).putExtra("friend_userId", friend_Id));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public int getItemCount() {
return jsonArray.length();
}
class HaderView extends RecyclerView.ViewHolder {
TextView tv_category;
ImageView img_head_to_head;
HaderView(View v) {
super(v);
tv_category = (TextView) v.findViewById(R.id.tv_category);
img_head_to_head = (ImageView) v.findViewById(R.id.img_head_to_head);
}
}
}

Categories

Resources