Everytime I run my code I get the following error.
JSON.typeMismatch(JSON.java:111)
How can I parse a JSONObject wrapped with an array?
Here is my code.
public class FeedActivity extends AppCompatActivity implements OnFeedListener {
ListView listView;
FeedAdapter adapter;
ArrayList<Post> posts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
listView = (ListView)findViewById(R.id.listView);
adapter = new FeedAdapter(getApplicationContext(), R.layout.layout_feed_item);
listView.setAdapter(adapter);
FeedTask task= new FeedTask(this);
task.execute("http://www.botswanayouth.com/wp-json/wp/v2/posts");
}
#Override
public void onFeed(JSONArray array) {
posts= new ArrayList<>();
int length = array.length();
for (int i = 0; i < length; ++i) {
JSONObject object = array.optJSONObject(i);
Post post = new Post(object.optString("title"),object.optString("excerpt"),object.optString("featured_media"));
posts.add(post);
}
adapter.addAll(posts);
}
public class FeedTask extends AsyncTask<String, Void, JSONArray> {
private OnFeedListener listener;
public FeedTask(OnFeedListener listener) {
this.listener= listener;
}
#Override
protected JSONArray doInBackground(String... params) {
String url = params[0];
OkHttpClient client= new OkHttpClient();
Request.Builder builder= new Request.Builder();
Request request= builder.url(url).build();
try {
Response response= client.newCall(request).execute();
String json= response.body().string();
try {
JSONObject object= new JSONObject(json);
JSONArray array = object.optJSONArray("posts");
return array;
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray array) {
super.onPostExecute(array);
if (null== array)
return;
if (null != listener)
listener.onFeed(array);
}
}
public class FeedAdapter extends ArrayAdapter<Post> {
private int resource;
public FeedAdapter(Context context, int resource) {
super(context, resource);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null==convertView) {
LayoutInflater inflater=LayoutInflater.from(getContext());
convertView=inflater.inflate(resource, null);
}
Post post = getItem(position);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView desc = (TextView) convertView.findViewById(R.id.description);
title.setText(post.title);
desc.setText(post.description);
return convertView;
}
}
public class Post {
public String title;
public String description;
public String thumbnail; //URL
public Post(String title, String desc, String thumbnail) {
this.title=title;
this.description=desc;
this.thumbnail=thumbnail;
}
}
}
If this is your json
array-[
0object-{ "id" : number5878, "date" : string2016-09-20T14:04:01, "guid" :
object-{ "rendered" : stringhttp:\/\/botswanayouth.com\/?p=5877 },
"type" : stringpost, "link" : stringhttp:\/\/botswanayouth.com\/5877\/blow-blow-rappers-beef-dramaboi-vs-emtee\/,
"title" : object+{ ... }, "content" : object+{ ... }, "excerpt" :
object-{ "rendered" : string<p> Sessions next month at Stanbic Bank.<\/p>}
]
Then in your initial response you are getting a json array not a json object.
So this
String json= response.body().string();
try {
JSONObject object= new JSONObject(json);
....
}
Should be
String json= response.body().string();
try {
JSONArray object= new JSONArray(json);
....
}
But it's honestly a little hard to tell because what you've provided doesn't match your code. For example you are looking for a "posts" array in your code, but that's not anywhere in your example json.
Related
My RecyclerView is returning the Boolean value 'true' for some odd reason.
I can't seem to fix the issue
This is the output I am getting
It should display text from the JSON
JSON LINK - https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=c80ddd850a524fe5975cad881d6f4aba
I am accessing the 'articles' JSON array and I want to display the title
MainActivity code:
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
MyAdapter mViewAdapter;
List<News> news_list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ParseNewsJSON().execute();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
//mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mViewAdapter = new MyAdapter(new ArrayList<News>());
mRecyclerView.setAdapter(mViewAdapter);
}
public class ParseNewsJSON extends AsyncTask<String, Void, String> {
private final String JSON_URL = "https://newsapi.org/v2/top-headlines?sources=cnn&apiKey=c80ddd850a524fe5975cad881d6f4aba";
String result = "";
ArrayList<String> article_heading = new ArrayList<>();
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(JSON_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
mViewAdapter = new MyAdapter(news_list);
mRecyclerView.setAdapter(mViewAdapter);
mViewAdapter.notifyDataSetChanged();
super.onPostExecute(s);
}
}
}
MyAdapter Code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<News> newsArticleList;
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
//description, genre;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textView_articleHeading);
// description = (TextView) itemView.findViewById(R.id.textView_description);
// image = (TextView) itemView.findViewById(R.id.rating);
}
}
public MyAdapter (List<News> newsArticleList){
this.newsArticleList = newsArticleList;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
News news = newsArticleList.get(position);
holder.title.setText(news.getHeading());
}
#Override
public int getItemCount() {
return newsArticleList.size();
}
}
News.Java;
public class News {
private String heading;
//private String descrpiton;
private String img;
public String getHeading() {
return heading;
}
public void setHeading(String heading) {
this.heading = heading;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
Your problem is here
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
article_heading is an ArrayList, the method add returns a boolean to whether the list has changed due to your call or not.
You are not adding the title, you are adding the return of the ArrayList method, what you need is to change that line to that
String title = jsonArray.getJSONObject(i).optString("title");
article_heading.add(title);
news.setHeading(title);
change your onPostExecute as below
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("articles");
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
String headingFromJson = jsonArray.getJSONObject(i).getString("title");
article_heading.add(headingFromJson);
news.setHeading(headingFromJson);
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
mViewAdapter = new MyAdapter(news_list);
mRecyclerView.setAdapter(mViewAdapter);
mViewAdapter.notifyDataSetChanged();
super.onPostExecute(s);
}
You are setting the heading of the news in a wrong way.
You should be doing the following in your Aynctask:
news.setHeading(jsonArray.getJsonObject(i).getString("title"));
You are instead putting the title inside the arraylist using add method. And putting the result of the add method as the heading. Add method of arraylist returns a boolean value indicating if the addition to list was successful or not. Thus you keep getting true instead of the actual text
Try this:
In yout ParseNewsJSON class onpostexecute()
Change to :
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(jsonArray.getJSONObject(i).optString("title"));
news_list.add(news);
}
Instead of:
for (int i = 0; i < jsonArray.length(); i++) {
News news = new News();
news.setHeading(String.valueOf(article_heading.add(jsonArray.getJSONObject(i).optString("title"))));
// article_heading.add(jsonArray.getJSONObject(i).optString("title"));
Log.d("news_JSON", article_heading.toString());
Log.d("news", news.getHeading().toString());
news_list.add(news);
}
I want to create the multiple array of data from MySQL, but received NullPointerException. The error is found here: JSONObject jsonResponse = new JSONObject...
NewsFeed.java
public class NewsFeed extends Fragment {
public NewsFeed() {
// Required empty public constructor
}
String T = "check";
TextView newsTime;
TextView newsTitle;
TextView newsSection;
//TextView txtT;
//String title2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rv = inflater.inflate(R.layout.newsfeed, container, false);
LayoutInflater infnews = getLayoutInflater();
LinearLayout linearLayout =
(LinearLayout)rv.findViewById(R.id.linear_newsfeed);
final View view1 = infnews.inflate(R.layout.newsfront, linearLayout,
false);
view1.getLayoutParams().width =
RelativeLayout.LayoutParams.MATCH_PARENT;
linearLayout.addView(view1);
newsTime = (TextView)rv.findViewById(R.id.newsTime);
newsTitle = (TextView)rv.findViewById(R.id.newsTitle);
newsSection = (TextView)rv.findViewById(R.id.newsSection);
Typeface GothamProFont =
Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamPro.ttf");
newsTime.setTypeface(GothamProFont);
newsTitle.setTypeface(GothamProFont);
newsSection.setTypeface(GothamProFont);
newsFeedDisplay();
view1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), NewsBody.class);
startActivity(intent);
}
});
return rv;
}
void newsFeedDisplay () {
Response.Listener<String> responseListener = new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new
JSONObject(jsonResult.substring(jsonResult.indexOf("{"),
jsonResult.lastIndexOf("}")+1));
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
final ArrayList<HashMap<String,String>> MyArrList = new
ArrayList<HashMap<String, String>>();
HashMap<String,String> map;
for(int i=0; i<jsonMainNode.length(); i++){
JSONObject c = jsonMainNode.getJSONObject(i);
Log.i(T, c.toString());
map = new HashMap<String,String>();
map.put("title", c.getString("title"));
map.put("time", c.getString("time"));
map.put("section", c.getString("section"));
MyArrList.add(map);
Log.i(T, MyArrList.toString());
SimpleAdapter sAdap;
//sAdap = new SimpleAdapter(getActivity(), MyArrList,
R.layout.activity_column, new String[]{"MemberID","Name","city"}, new int[]
{R.id.ColMemberID, R.id.ColName, R.id.Colcity});
//listView.setAdapter(sAdap);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
NewsFeedRequest3 newsFeedRequest3 = new
NewsFeedRequest3(responseListener);
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(newsFeedRequest3);
}
}
NewsFeedRequest3
public class NewsFeedRequest3 extends StringRequest{
private static final String REGISTER_REQUEST_URL =
"https://blazhko.000webhostapp.com/test.php";
private Map<String, String> params;
public NewsFeedRequest3(Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
//params.put("section", section);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(java.lang.String)' on a null object reference
at blazhko.sportarena.main_screen.NewsFeed$3.onResponse(NewsFeed.java:145)
at blazhko.sportarena.main_screen.NewsFeed$3.onResponse(NewsFeed.java:141)
What I do incorrectly? Please help me.
According to your problem
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(java.lang.String)' on a null object reference at
You can do like this .
1.Do you get the correct response in your code? jsonResult or response .
2.Deal with NullPointerException
3.make sure that your code contain { and }.
You can do this . If you use jsonResult as result , you can change to jsonResult in your code .
#Override
public void onResponse(String response) {
// String response = "hello{\"key\":\"value\"}world"; if you response like this
try {
if (response != null) {
JSONObject jsonResponse = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
// do something here
Log.e("TAG", response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Am an newbie to android ...kindly help me guys...I have 2 strings in my sample webservice(Not in an array) and I want to populate it in the listview .I wrote code to populate with a single string.But I don't know how to populate with 2nd strings below to 1st string in listview.Any suggestion will be appreciated.
Here is my complete code
HTTPURLCONNECT
class HttpULRConnect {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d("testhtt2","test");
String line;
while ((line= reader.readLine())!=null) {
sb.append(line+"\n");
}
Log.d("test44", sb.toString());
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally{
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}}}
Here is my FETCH.java
public class Fetch extends Activity {
ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
String url ="http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fetch);
new BackTask().execute(url);
}
public class BackTask extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content =HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ar = new JSONArray(s);
for (int i = 0; i < ar.length(); i++) {
JSONObject jsonobject = ar.getJSONObject(i);
Flowers flowers = new Flowers();
flowers.setName(jsonobject.getString("NAME"));
flowersList.add(flowers);
}
}
catch (JSONException e){
e.printStackTrace();
}
FlowerAdapter adapter = new FlowerAdapter(Fetch.this, R.layout.flower_lis_item, flowersList);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
}
}
static class Flowers {
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
private String NAME;
}
public static class FlowerAdapter extends ArrayAdapter<Flowers> {
private ArrayList<Flowers> items;
private Context mContext;
public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){
super(context,textViewResourceID,items);
mContext = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Flowers flowers = items.get(position);
if(v==null){
LayoutInflater inflater =(LayoutInflater) getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.flower_lis_item,null);
}
TextView title = (TextView)v.findViewById(R.id.textView3);
TextView text =(TextView)v.findViewById(R.id.textView2);
if (title != null) {
title.setText(flowers.getName());
text.setText(flowers.getName());
}
return v;
}
}
}
I have php file when user post existing ticknumber the php will echo JSON code for one array of that was posted, I linked it with Activity that will do same job of php file but when I click on button nothing show up in Listview !!
<?php
if ($_SERVER ['REQUEST_METHOD']=='POST') {
$ticketnumber = $_POST['ticketnumber'];
require_once('config.php');
$con->set_charset('utf8');
$sql = " SELECT * FROM contact WHERE ticketnumber = '$ticketnumber' ";
$res = mysqli_query($con, $sql);
$result = array();
while($get = mysqli_fetch_array($res))
{
array_push($result,array('ticketnumber' =>$get[5], 'subject' =>$get[4],'response' =>$get[6]));
}
if(!empty($result)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
}
?>
SupportActivity.java
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aaa/getticket.php";
private RequestQueue requestQueue1;
int i ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("error")) {
Toast.makeText(supportActivity.this, "please check the number", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject ticket ;
JSONArray jsonArray = new JSONArray("responseticket");
ticket = jsonArray.getJSONObject(Integer.parseInt(response));
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
SupportAdapter.java
public class supportAdapter extends ArrayAdapter<supportContent> {
private Context context;
private List<supportContent> contents;
public supportAdapter(Context context, List<supportContent> con){
super(context, R.layout.supportcontent, con);
this.contents = con;
}
#Override
public int getCount(){
return contents.size();
}
public View getView(int position, View convertview, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(getContext());
View supcon = inflater.inflate(R.layout.supportcontent, null);
TextView ticketnumber = (TextView)supcon.findViewById(R.id.ticketnumber);
ticketnumber.setText(contents.get(position).getTicketnumber());
TextView supportsubject = (TextView)supcon.findViewById(R.id.supportsubject);
supportsubject.setText(contents.get(position).getSubject());
TextView response = (TextView)supcon.findViewById(R.id.response);
response.setText(contents.get(position).getResponse());
return supcon;
}
}
Parse your response as below -
JSONObject jObj = new JSONObject(response);
JSONArray jResponseTicketarray = jObj.getJSONArray("responseticket");
JSONObject jTicket = jResponseTicketarray.getJSONObject(0);
String Ticketnumber = jTicket.getString("ticketnumber");
String Subject = jTicket.getString("subject");
String Response = jTicket.getString("response");
response - returned Json response in onResponse() mth.
jResponseTicketarray.getJSONObject(0); - here '0' is first element in ResponseTicketArray. If der are multiple object u might wanna iterate thr loop and extract required fields.
Modify below code too -
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
to below -
supportContent support = new supportContent();
support.setTicketnumber(TicketNumber);
support.setSubject(Subject);
support.setResponse(Response);
I am working with facebook app for my project and I'm getting a json from the graph API. I have a custom listView with hashMap, but when I run, the list wont populate but there isn't any errors. please help me.
here are the codes:
public class PageFeedHome extends Fragment {
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
new LoadPosts().execute();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
}
}
Move this code :
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv }); //initialize adapter
listView.setAdapter(adapter); //set adapter
adapter.notifyDataSetChanged();
To the AsyncTask's onPostExecute to make sure the feedList is already inserted from the onBackground.
Or if you prefer to initialize your adapter and setting the adapter to the listview in the onCreate, just move adapter.notifyDataSetChanged(); to the onPostExecute. This is recommended if you call the AsyncTask multiple times, because theres no need to initialize and set the adapter multiple times. (see my comment in the code)
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
BaseAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
listView.setAdapter(adapter);
new LoadPosts().execute();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), ""+feedList.size(), Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
}
}