我在Android中有一个ListView并设置了一个自定义适配器。我的问题是列表视图没有显示任何内容,无论适配器和notifyDataSetChanged();
这是我的代码:XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawerLayout"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="@null" />
</LinearLayout>
<FrameLayout
android:id="@+id/mainContent"
android:layout_height="match_parent"
android:layout_width="match_parent">
</FrameLayout>
<!-- <TextView
android:id="@+id/empty"
android:text="TextView"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:gravity="center"/> -->
<!-- navigation drawer -->
<ListView
android:id="@+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:divider="@null"
android:descendantFocusability="beforeDescendants"
android:listSelector="#FFFFFF"
android:background="#3b5998"
android:layout_gravity="left" />"
</android.support.v4.widget.DrawerLayout>
活动代码:
package com.sri.vaave;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.sri.vaave.adapter.FeedListAdapter;
import com.sri.vaave.app.AppController;
import com.sri.vaave.data.FeedItem;
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://coherendz.net/vaavefeed1.json";
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private ArrayList<NavDrawerItem> navDrawerItems;
private TypedArray navMenuIcons;
private NavDrawerListAdapter adapter;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
Iterator itr;
private List<FeedItem> arrayTemplist;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// 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)));
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.Options);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerList = (ListView) findViewById(R.id.drawerList);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// all
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.drawer_open, // nav drawer open - description for accessibility
R.string.drawer_close // nav drawer close - description for accessibility
)
{
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {// display view for selected nav drawer item
Toast.makeText(MainActivity.this,navMenuTitles[position]+" was selected", Toast.LENGTH_LONG).show();
setTitle(navMenuTitles[position]);
try {
displayView(position);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
feedItems.clear();
if(arrayTemplist!=null){
arrayTemplist.clear();
}
else{}
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) throws JSONException {
// TODO Auto-generated method stub
switch(position){
case 0: buildFeed(0);
break;
case 1:buildFeed(7);
break;
case 2:buildFeed(1);
break;
case 3: buildFeed(13);
break;
case 4: buildFeed(12);
break;
default:
break;
}
}
}
private String getData(int nodeType) {
// TODO Auto-generated method stub
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
String data = null;
if (entry != null) {
// fetch the data from cache
try {
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) {
//Log.d("RaVI_Bal", response.toString());
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
// Log.d(TAG, feedItems.toString());
return feedItems.toString();
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
FeedItem item;
itr = response.keys();
try
{
while(itr.hasNext())
{
String key = itr.next().toString();
JSONObject entry = response.getJSONObject(key);
JSONObject phone = entry.getJSONObject("basic");
String name = phone.getString("title");
String description = phone.getString("description");
int nodetype = phone.getInt("node_type");
JSONObject comments = entry.getJSONObject("comments");
String comments_count = comments.getString("count");
JSONObject like = entry.getJSONObject("likes");
String like_count = like.getString("count");
String readable_date = phone.getString("readable_date");
item = new FeedItem();
item.setNode_type(nodetype);
item.setName(String.valueOf(name));
item.setStatus(String.valueOf(description));
item.setReadable_date(String.valueOf(readable_date));
item.setComments_count(String.valueOf(comments_count));
item.setLike_count(String.valueOf(like_count));
feedItems.add(item);
// Log.d("LenOVo", feedItems.toString());
}
// notify data changes to list adapter
listAdapter.notifyDataSetChanged();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// Handle action bar actions click
switch (item.getItemId())
{
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void buildFeed(int nodeType) throws JSONException {
// TODO Auto-generated method stub
getData(nodeType);
arrayTemplist = new ArrayList<FeedItem>();
if(nodeType!=0){
for(int x=0;x<feedItems.size();x++)
{
int currentNodeType = feedItems.get(x).getNode_type();
// Log.d("Cem", String.valueOf(currentNodeType));
if (nodeType == currentNodeType)
{
arrayTemplist.add(feedItems.get(x));
Log.d("Cem", String.valueOf(currentNodeType));
}
}
// Log.d("Cem", arrayTemplist.toString());
listAdapter = new FeedListAdapter(this, arrayTemplist);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
else{
// Log.d("Kaner", feedItems.toString());
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
}
}
适配器代码:
package com.sri.vaave.adapter;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.sri.vaave.FeedImageView;
import com.sri.vaave.R;
import com.sri.vaave.app.AppController;
import com.sri.vaave.data.FeedItem;
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;
}
class MyViewHolder{
TextView name,timestamp,statusMsg,url;
NetworkImageView profilePic;
FeedImageView feedImageView;
@SuppressWarnings("unused")
MyViewHolder(View v){
TextView name = (TextView) v.findViewById(R.id.name);
TextView timestamp = (TextView) v
.findViewById(R.id.timestamp);
TextView statusMsg = (TextView) v
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView)v.findViewById(R.id.txtUrl);
NetworkImageView profilePic = (NetworkImageView) v
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) v
.findViewById(R.id.feedImage1);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder holder = null;
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView = inflater.inflate(R.layout.feed_item, null);
holder = new MyViewHolder(convertView);
convertView.setTag(holder);
}
else
{
holder = (MyViewHolder) convertView.getTag();
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
FeedItem item = feedItems.get(position);
holder.name.setText(item.getName());
// Converting timestamp into x ago format
/*CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getReadable_date()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);*/
holder.timestamp.setText(item.getReadable_date());
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
holder.statusMsg.setText(Html.fromHtml(item.getStatus()));
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
holder.url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
holder.url.setMovementMethod(LinkMovementMethod.getInstance());
holder.url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
holder.url.setVisibility(View.GONE);
}
// user profile pic
holder.profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
holder.feedImageView.setImageUrl(item.getImge(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
@Override
public void onError() {
}
@Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
return convertView;
}
}
问题是屏幕上没有显示任何内容。我得到一个白色的屏幕。我看不到所有的textview(在适配器中提到)及其文本。显然我做的事情非常错误,但我无法弄清楚是什么。
答案 0 :(得分:0)
最后,我解决了这个问题。
这是更新的代码。我删除了arrayList.clear和feedItems.clear。他们正在清空我的列表视图。
MainActivity.java
package com.sri.vaave;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.sri.vaave.adapter.FeedListAdapter;
import com.sri.vaave.app.AppController;
import com.sri.vaave.data.FeedItem;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private List<FeedItem> arrayTemplist;
private String URL_FEED = "http://coherendz.net/vaavefeed1.json";
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private ArrayList<NavDrawerItem> navDrawerItems;
private TypedArray navMenuIcons;
private NavDrawerListAdapter adapter;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
Iterator itr;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
feedItems = new ArrayList<FeedItem>();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
buildFeed(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// 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)));
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.Options);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerList = (ListView) findViewById(R.id.drawerList);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// all
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.drawer_open, // nav drawer open - description for accessibility
R.string.drawer_close // nav drawer close - description for accessibility
)
{
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void populateFeedList() {
// TODO Auto-generated method stub
feedItems = getData(0);
//getData(0);
populateListView(feedItems);
}
private void populateListView(List dataFeed) {
// TODO Auto-generated method stub
// feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, dataFeed);
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {// display view for selected nav drawer item
Toast.makeText(MainActivity.this,navMenuTitles[position]+" was selected", Toast.LENGTH_LONG).show();
setTitle(navMenuTitles[position]);
displayView(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
feedItems = new ArrayList<FeedItem>();
switch(position){
case 0: try {
buildFeed(0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 1: try {
buildFeed(7);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 2: try {
buildFeed(1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 3: try {
buildFeed(13);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 4: try {
buildFeed(12);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
try {
buildFeed(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
private List getData(int nodeType) {
// TODO Auto-generated method stub
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
String data = null;
if (entry != null) {
// fetch the data from cache
try {
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() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
return feedItems;
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
FeedItem item;
itr = response.keys();
try
{
while(itr.hasNext())
{
String key = itr.next().toString();
JSONObject entry = response.getJSONObject(key);
JSONObject phone = entry.getJSONObject("basic");
String name = phone.getString("title");
String description = phone.getString("description");
int nodetype = phone.getInt("node_type");
JSONObject comments = entry.getJSONObject("comments");
String comments_count = comments.getString("count");
JSONObject like = entry.getJSONObject("likes");
String like_count = like.getString("count");
String readable_date = phone.getString("readable_date");
item = new FeedItem();
item.setNode_type(nodetype);
item.setName(String.valueOf(name));
item.setStatus(String.valueOf(description));
item.setReadable_date(String.valueOf(readable_date));
item.setComments_count(String.valueOf(comments_count));
item.setLike_count(String.valueOf(like_count));
feedItems.add(item);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// Handle action bar actions click
switch (item.getItemId())
{
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void buildFeed(int nodeType) throws JSONException {
// TODO Auto-generated method stub
getData(0);
arrayTemplist = new ArrayList<FeedItem>();
if(nodeType!=0){
for(int x=0;x<feedItems.size();x++)
{
int currentNodeType = feedItems.get(x).getNode_type();
if (nodeType == currentNodeType)
{
arrayTemplist.add(feedItems.get(x));
}
}
feedItems = arrayTemplist;
}
else{
}
populateListView(feedItems);
}
}