I have got a problem with listview for a json parser !
(ArretsFragment.java) :
package activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.pierre.tan.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import adapter.CustomListAdapter;
import app.AppController;
import model.Movie;
public class ArretsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://api.androidhive.info/json/movies.json";
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
public ArretsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
// Showing progress dialog before making http request
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} 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(movieReq);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_arrets, container, false);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and i've got this (CustomListAdapter.java) :
package adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.example.pierre.tan.R;
import java.util.List;
import app.AppController;
import model.Movie;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.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.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView rating = (TextView) convertView.findViewById(R.id.rating);
TextView genre = (TextView) convertView.findViewById(R.id.genre);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
// rating
rating.setText("Rating: " + String.valueOf(m.getRating()));
// genre
String genreStr = "";
for (String str : m.getGenre()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,
genreStr.length() - 2) : genreStr;
genre.setText(genreStr);
// release year
year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
When i try to lauch my application i've got these errors :
04-16 11:14:57.416 27043-27043/com.example.pierre.tan E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.pierre.tan, PID: 27043
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at activity.ArretsFragment.onCreate(ArretsFragment.java:55)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1763)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:915)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
It's a little difficult process so if someone can help me it would be very nice
Your problem is inside:
listView = (ListView) getActivity().findViewById(R.id.list);
Your activity does not contains your listView.
Add all of this to onActivityCreated() method
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
and learn Fragment lifecycle.
You parse an empty array of Movies to your adapter:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.list);
// movieList is an empty array at this point.
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
// ...
}
I guess you just have to set your adapter after you've populated the list with data from the movieReq request.
You have to infalte your layout before retrieve the listview.
In a fragment, do all your treatments in the onCreateView method.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_arrets, container, false);
listView = (ListView) getActivity().findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
// Showing progress dialog before making http request
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} 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(movieReq);
// Inflate the layout for this fragment
return rootView;
}
Related
I am fetching JSON Array and trying to show it in a list view. I debugged and got that I recieve the array as required but when i run my list view is blank on android screen. When I run no error is shown in syntax or while in emulator. Here is my code:
I have used volley to call the api and fetch json data.
DashBoard.java
public class Dashboard extends AppCompatActivity {
private RequestQueue queue;
ListView listView;
ArrayList<rowitem> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
queue = Volley.newRequestQueue(this);
listView = (ListView) findViewById(R.id.myListView);
arrayList = new ArrayList<>();
String url = "https://api.rootnet.in/covid19-in/stats/latest";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
try {
JSONObject result = new JSONObject(response).getJSONObject("data");
JSONArray jsonArray = result.getJSONArray("regional");
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject json_data = jsonArray.getJSONObject(i);
String location = json_data.getString("loc");
String totalcase = json_data.getString("totalConfirmed");
String recovered = json_data.getString("discharged");
String deaths = json_data.getString("deaths");
rowitem model = new rowitem();
model.setLocation(location);
model.setTotalcase(totalcase);
model.setRecovered(recovered);
model.setDeaths(deaths);
arrayList.add(model);
}
} catch (JSONException e) {
Toast.makeText(Dashboard.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Dashboard.this, "Server is not responding (Covid-19 Tracker)", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
customlistviewadapter adapter = new customlistviewadapter(this, arrayList);
listView.setAdapter(adapter);
}
}
customlistviewadapter.java
package com.example.maps;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class customlistviewadapter extends BaseAdapter {
Context context;
ArrayList<rowitem> arrayList;
public customlistviewadapter(Context context,ArrayList<rowitem> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.row, parent, false);
}
TextView location, totalcase, recovered, deaths;
location = (TextView) convertView.findViewById(R.id.location);
totalcase = (TextView) convertView.findViewById(R.id.cases);
recovered = (TextView) convertView.findViewById(R.id.healthy);
deaths = (TextView) convertView.findViewById(R.id.deaths);
location.setText(arrayList.get(position).getLocation());
totalcase.setText(arrayList.get(position).getTotalcase());
recovered.setText(arrayList.get(position).getRecovered());
deaths.setText(arrayList.get(position).getDeaths());
return convertView;
}
}
my name ari.. i am newbie in Android development. maybe you can help me to answer my problem. I want to display data from the listview adapter, but when i click the data. my app force close.
i have a adapter for show data in listview like :
ListAdapter.java
package com.santosa.sapasantosa.components;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.santosa.sapasantosa.R;
import java.util.ArrayList;
/**
* Created by muhammadaa on 10/14/2017.
*/
public class ListAdapter extends BaseAdapter {
private Activity activity;
private static ArrayList nik;
private static ArrayList nama;
private static ArrayList email;
private static ArrayList phone;
private static ArrayList jabatan;
private static ArrayList departement;
private static ArrayList gender;
private static ArrayList status;
private static ArrayList label;
private static LayoutInflater inflater = null;
public ListAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f, ArrayList g, ArrayList h, ArrayList i, ArrayList j) {
activity = a;
this.nik = b;
this.nama = c;
this.email = d;
this.gender = e;
this.status = f;
this.label = g;
this.phone = h;
this.jabatan = i;
this.departement = j;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return nik.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_data_profile, null);
TextView nik2 = (TextView) vi.findViewById(R.id.profNik); // nik
String ambilNik = nik.get(position).toString();
nik2.setText(ambilNik);
TextView nama2 = (TextView) vi.findViewById(R.id.profNama); // nama
String ambilNama = nama.get(position).toString();
nama2.setText(ambilNama);
TextView email2 = (TextView) vi.findViewById(R.id.profEmail); // email
String ambilEmail = email.get(position).toString();
email2.setText(ambilEmail);
TextView phone2 = (TextView) vi.findViewById(R.id.profPhone); // phone
String ambilPhone = phone.get(position).toString();
phone2.setText(ambilPhone);
TextView gender2 = (TextView) vi.findViewById(R.id.profGender); // gender
String ambilGender = gender.get(position).toString();
gender2.setText(ambilGender);
TextView bagian = (TextView) vi.findViewById(R.id.profBagian); // Bagian
String ambilJabatan = jabatan.get(position).toString();
String ambilDepartement = departement.get(position).toString();
bagian.setText(ambilJabatan+"/"+ambilDepartement);
TextView status2 = (TextView) vi.findViewById(R.id.profStatus); // status
String ambilStatus = status.get(position).toString();
status2.setText(ambilStatus);
TextView label2 = (TextView) vi.findViewById(R.id.countNumber); // label
String ambilLabel = label.get(position).toString();
label2.setText(ambilLabel);
return vi;
}
}
And this class fragment for using adapter
AdminHomeFragment
package com.santosa.sapasantosa.view.admin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.santosa.sapasantosa.R;
import com.santosa.sapasantosa.components.ListAdapter;
import com.santosa.sapasantosa.components.RequestHandler;
import com.santosa.sapasantosa.components.SharedPrefManager;
import com.santosa.sapasantosa.configs.Constrant;
import com.santosa.sapasantosa.models.Employee;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
/**
* A simple {#link Fragment} subclass.
*/
public class AdminHomeFragment extends Fragment {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
ArrayList<String> nik_array = new ArrayList<String>();
ArrayList<String> nama_array = new ArrayList<String>();
ArrayList<String> email_array = new ArrayList<String>();
ArrayList<String> phone_array = new ArrayList<String>();
ArrayList<String> gender_array = new ArrayList<String>();
ArrayList<String> jabatan_array = new ArrayList<String>();
ArrayList<String> departement_array = new ArrayList<String>();
ArrayList<String> status_array = new ArrayList<String>();
ArrayList<Integer> label_array = new ArrayList<>();
com.santosa.sapasantosa.components.ListAdapter adapter;
ListView listPeg;
public AdminHomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_admin_home, container, false);
listPeg = (ListView) view.findViewById(R.id.pegListView);
listPeg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(),ProfileEmployeeActivity.class);
HashMap<String,String> map = (HashMap) parent.getItemAtPosition(position);
Log.e("","adad "+map);
String empId = map.get("nik");
i.putExtra("nik",empId);
startActivity(i);
}
});
loadDataPegawai();
return view;
}
private void loadDataPegawai() {
// get parameter
final String users = SharedPrefManager.getInstance(getContext()).getUserEmployee().getNik();
class LoadPegawai extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("username", users);
//returing the response
return requestHandler.sendPostRequest(Constrant.URL_PROFIL, params);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
int n = 1;
try {
JSONObject obj = new JSONObject(s);
if (!obj.getBoolean("error")) {
// get data user dari respone
JSONArray userJson = obj.getJSONArray("user");
for (int i = 0, count = userJson.length(); i < count; i++) {
try {
JSONObject jsonObject = userJson.getJSONObject(i);
if (jsonObject.getString("employeeStatus").toString().equals("0")) {
nik_array.add(jsonObject.getString("employeeID").toString());
nama_array.add(jsonObject.getString("employeeNama").toString());
email_array.add(jsonObject.getString("employeeEmail").toString());
gender_array.add(jsonObject.getString("employeeGender").toString());
status_array.add(jsonObject.getString("employeeStatus").toString());
phone_array.add(jsonObject.getString("employeePhone").toString());
jabatan_array.add(jsonObject.getString("employeeJabatan").toString());
departement_array.add(jsonObject.getString("employeeDepartement").toString());
label_array.add(n++);
String id = jsonObject.getString("employeeID").toString();
// adding to hashmap
HashMap<String,String> employees = new HashMap<>();
employees.put("nik",id);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/* Set data to listview */
adapter = new com.santosa.sapasantosa.components.ListAdapter( getActivity(),
nik_array,
nama_array,
email_array,
gender_array,
status_array,
label_array,
phone_array,
jabatan_array,
departement_array);
listPeg.setAdapter(adapter);
listPeg.setTextFilterEnabled(true);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//executing the async task
LoadPegawai ru = new LoadPegawai();
ru.execute();
}
}
when i clik data adapter in ListView, i have a Error like:
Can you help me for resolve the error. I say very very thanks you for your help...
Seems you're trying to display all employees as a ListView... If my understanding is't wrong, you should :
Create an EmployeeBean
Put all your employee into a collection...maybe ArrayList.
After that, when you click an item on ListView, the integer you get is the index of EmployeeBean in your collection, so that you can access it from your collection.
I have a ListView in which i am showing some data. I am requesting the data from the server which is in the form of JSON. Also, the data is paginated.
When the API is called for the first time it is loading n items.
I have implemented the logic that after the list end is reached API would be call again to fetch n more data.
API Calls are working fine as I have seen the result in the Logcat.
The Issue is the ListView is not updating properly on scroll after the API has been called for the second time.
Eg: Suppose I am calling API to fetch 7 items at a time. Then in the ListView i would see something like this:
Item1
Item2
..
Item7
Item1
Item2
....
JsonObjectRequest jo = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
pDialog.dismiss();
pDialog = null;
try {
JSONArray ja = jsonObject.getJSONArray("resultset"); // id, title, content, guid
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
SearchListItem ri = new SearchListItem();
ri.setId(jo.getInt("id"));
ri.setTitle(jo.getString("title"));
ri.setContent(jo.getString("content"));
listy.add(ri);
}
} catch (JSONException ex) {
Toast.makeText(getApplicationContext(), "json ex" + ex.getMessage(), Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
searchAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
pDialog.dismiss();
pDialog = null;
Log.d(TAG, "!!!! ERROR " + volleyError.getMessage());
}
});
//Toast.makeText(ListActivity.this, jo.toString().toCharArray(), Toast.LENGTH_SHORT).show();
AppController.getInstance().addToRequestQueue(jo);
//Adapter
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.o.R;
import com.o.SearchListItem;
import java.util.List;
public class SearchListAdapter extends BaseAdapter {
Context context;
List<SearchListItem> items;
//ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public SearchListAdapter(Context context, List<SearchListItem> items)
{
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return items.indexOf(getItem(position));
}
class ViewHolder
{
TextView txtTitle;
TextView txtContent;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);// creates the objects of all views
if(convertView == null)
{
convertView = inflater.inflate(R.layout.style_row, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.txtAbout);
holder.txtContent = (TextView) convertView.findViewById(R.id.txtDetail);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
try {
SearchListItem rowItem = (SearchListItem) getItem(position);
holder.txtTitle.setText(rowItem.getTitle());
holder.txtContent.setText(rowItem.getContent().substring(0,20));
}
catch (Exception e){
//Toast.makeText(SearchListAdapter.this,e.printStackTrace(),Toast.LENGTH_SHORT).show();
}
return convertView;
}
}
You have not set the tag on the view , do convertview.setTag(holder) ...
if(convertView == null)
{
convertView = inflater.inflate(R.layout.style_row, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.txtAbout);
holder.txtContent = (TextView) convertView.findViewById(R.id.txtDetail);
convertView.setTag(holder)
}
Your code seems fine , problem might be that you are requesting multiple times from your code on the server and ArrayList listy getting filled multiple times in the onResponse method of jsonRequest or your server might be returning multiple entries , seems nothing wrong with the posted code.
I have a custom adapter set. When the Listview has more than 4-5 views, the app stops working and gives null object in the set textview. Whereas this code works fine when i have 2-3 views in the Listview.
I have commented the textview which gets the error. Please have a loook ! Thank you
Update: It seems that if i scroll fast, the error is thrown. !!
Update 2: As suggested by #Piotr, it works fine until , when i scroll down to the end and scroll up , it converts the view list_item_header to list_item. So all the view becomes list_item.
Error:
FATAL EXCEPTION: main
Process: edu.gannon.gannonknightnews, PID: 3083
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at edu.gannon.gannonknightnews.MenuFragment$GetNews$CustomAdapter.getView(MenuFragment.java:197)
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class MenuFragment extends Fragment {
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
String my_url;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.home, container, false);
newsList = (ListView) view.findViewById(R.id.homeListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
getActivity().getActionBar().setTitle("GannonKnightNews");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
return view;
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings", "Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
post.put("ListCount",String.valueOf(i));
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
newsList.setAdapter(adapter);
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>> {
private final ArrayList<HashMap<String, String>> objects;
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup Parent){
//convertView = new ImageView();
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
android.widget.ImageView postImage = (android.widget.ImageView) convertView.findViewById(R.id.img);
int getListPos = newsList.getFirstVisiblePosition();
//i set the count starting 0 and saved in the hashmap array
//to compare the first result with the first position of listview
int count = Integer.parseInt(objects.get(position).get("ListCount"));
my_url = objects.get(position).get(GUID);
if(getListPos == count) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
if(objects.get(position).get(GUID).equals("NULL")) {
postImage.setImageResource(R.drawable.default_bg);
}else{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
else{
//CHoose list item
//************************************************
//THe problem is in this textview which gives null object reference error
TextView thisview = (TextView) convertView.findViewById(R.id.email);
Log.d("Title", String.valueOf(thisview.getText()));
TextView postContent = (TextView) convertView.findViewById(R.id.mobile);
thisview.setText(objects.get(position).get(POST_TITLE).toUpperCase());
postContent.setText(objects.get(position).get(POST_CONTENT));
if(objects.get(position).get(GUID).equals("NULL")) {
postImage.setImageResource(R.drawable.default_bg);
}else{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
return convertView;
}
}//Custom Adapter
}//END getnews Async Task
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}//
}
try this:
public View getView(int position, View convertView, ViewGroup Parent)
{
int getListPos = newsList.getFirstVisiblePosition();
int count = Integer.parseInt(objects.get(position).get("ListCount"));
my_url = objects.get(position).get(GUID);
if (getListPos == count)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header, null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
if (objects.get(position).get(GUID).equals("NULL"))
{
postImage.setImageResource(R.drawable.default_bg);
}
else
{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
else
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, null);
TextView thisview = (TextView) convertView.findViewById(R.id.email);
Log.d("Title", String.valueOf(thisview.getText()));
TextView postContent = (TextView) convertView.findViewById(R.id.mobile);
thisview.setText(objects.get(position).get(POST_TITLE).toUpperCase());
postContent.setText(objects.get(position).get(POST_CONTENT));
if (objects.get(position).get(GUID).equals("NULL"))
{
postImage.setImageResource(R.drawable.default_bg);
}
else
{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
return convertView;
}
I'm new to Android so struggling to learn best practices etc and working mainly with tutorials.
I have my app doing what I want it to do using a custom listview. My problem is understanding exactly how it works as there is not an actual listview in the code.
What I want to do is add a container above the listview, but everything I have tried just doesn't seem to work and with it being a custom adapter, I'm struggling to find many resources.
Here is my fragment:
package info.androidhive.slidingmenu;
import android.annotation.TargetApi;
import android.app.ListFragment;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PhotosFragment extends ListFragment {
private static final String TAG = MainActivity.class.getSimpleName();
private List<ListViewItem> mItems; // ListView items list
JSONObject obj;
JSONArray stories;
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
//Do anything with response..
Log.d(TAG, responseString);
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
Log.d(TAG, String.valueOf(e));
} catch (IOException e) {
//TODO Handle problems..
Log.d(TAG, String.valueOf(e));
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
} else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
// initialize and set the list adapter
setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public class newsStories {
private String name, thumbnailUrl, body;
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body.substring(0, 150);
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
//Check if thumbnail exists, if so take out spaces and replace with -
this.thumbnailUrl = thumbnailUrl;
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// View importPanel = ((ViewStub) getActivity().findViewById(R.id.stub_import)).inflate();
new RequestTask().execute("http://www.myjsonurl.co.uk");
// remove the dividers from the ListView of the ListFragment
getListView().setDivider(null);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// retrieve theListView item
ListViewItem item = mItems.get(position);
// do something
Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
}
public class ListViewItem {
public final String title; // the text for the ListView item title
public final String description; // the text for the ListView item description
public final String adUrl;
//public final Drawable image;
public ListViewItem(String title, String description, String Advert_Url) {
Log.e("Advert:", Advert_Url);
if (Advert_Url != null && !Advert_Url.isEmpty()) {
String Advert = "http://alinktomyadvert.co.uk";
Log.e("TITLE: ", title);
this.title = "";
this.description = "";
this.adUrl = Advert;
} else {
this.title = title;
this.description = description;
this.adUrl = "";
}
}
}
}
If somebody can point me in the right direction I'd be so grateful.
EDIT:
Following #Sufian's advise I now have the following:
package info.androidhive.slidingmenu;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.ListFragment;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PhotosFragment extends Fragment {
public PhotosFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new RequestTask().execute("http://www.myaddress.co.uk/app/index.php?Type=8&catid=7&userid=4");
Log.v("created", "onActivityCreated()");
setHasOptionsMenu(true);
//mProgressBar = (ProgressBar) getView().findViewById(R.id.progressBar);
ListView mListView = (ListView) getView().findViewById(R.id.listView2);
//mTvEmpty = (TextView) getView().findViewById(R.id.textView);
ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.simple_list_item_1, mItems);
// load your data to your mListView
mListView.setAdapter(adapter); //NULL POINTER
}
private static final String TAG = MainActivity.class.getSimpleName();
private List<ListViewItem> mItems; // ListView items list
JSONObject obj;
JSONArray stories;
//
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
//Do anything with response..
Log.d(TAG, responseString);
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
Log.d(TAG, String.valueOf(e));
} catch (IOException e) {
//TODO Handle problems..
Log.d(TAG, String.valueOf(e));
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
} else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
// initialize and set the list adapter
//setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public class newsStories {
private String name, thumbnailUrl, body;
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body.substring(0, 150);
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
//Check if thumbnail exists, if so take out spaces and replace with -
this.thumbnailUrl = thumbnailUrl;
}
}
}
//
// #TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
// #Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
//
// // View importPanel = ((ViewStub) getActivity().findViewById(R.id.stub_import)).inflate();
// new RequestTask().execute("http://www.myjsonurl.co.uk");
// // remove the dividers from the ListView of the ListFragment
// getListView().setDivider(null);
// }
//
// #Override
// public void onListItemClick(ListView l, View v, int position, long id) {
// // retrieve theListView item
// ListViewItem item = mItems.get(position);
//
// // do something
// Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
// }
//
public class ListViewItem {
public final String title; // the text for the ListView item title
public final String description; // the text for the ListView item description
public final String adUrl;
//public final Drawable image;
public ListViewItem(String title, String description, String Advert_Url) {
Log.e("Advert:", Advert_Url);
if (Advert_Url != null && !Advert_Url.isEmpty()) {
String Advert = "http://www.myaddress.co.uk/images/websitelogo.png?width=700&height=200";
Log.e("TITLE: ", title);
this.title = "";
this.description = "";
this.adUrl = Advert;
} else {
this.title = title;
this.description = description;
this.adUrl = "";
}
}
}
}
I'm now getting a null pointer exception on the set adapter command - I'm a little unsure where to debug from here. I'm assuming it means the list is null?
EDIT 2
Logcat:
01-19 05:27:30.371 1287-1287/info.androidhive.slidingmenu D/OpenGLRenderer﹕ Enabling debug mode 0
01-19 05:27:31.031 1287-1287/info.androidhive.slidingmenu I/Choreographer﹕ Skipped 60 frames! The application may be doing too much work on its main thread.
01-19 05:27:57.901 1287-1287/info.androidhive.slidingmenu V/created﹕ onActivityCreated()
01-19 05:28:08.271 1287-1287/info.androidhive.slidingmenu D/dalvikvm﹕ GC_FOR_ALLOC freed 326K, 9% free 4066K/4468K, paused 24ms, total 26ms
01-19 05:28:08.471 1287-1287/info.androidhive.slidingmenu D/AndroidRuntime﹕ Shutting down VM
01-19 05:28:08.471 1287-1287/info.androidhive.slidingmenu W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb3ac2ba8)
01-19 05:28:08.511 1287-1287/info.androidhive.slidingmenu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.slidingmenu, PID: 1287
java.lang.NullPointerException
at info.androidhive.slidingmenu.PhotosFragment$RequestTask.onPostExecute(PhotosFragment.java:130)
at info.androidhive.slidingmenu.PhotosFragment$RequestTask.onPostExecute(PhotosFragment.java:52)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
fragment_photos.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">
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="190dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="63dp" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView2"
android:layout_below="#+id/progressBar"
android:layout_centerHorizontal="true" />
</RelativeLayout>
EDIT 3
package info.androidhive.slidingmenu;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ListViewDemoAdapter extends ArrayAdapter<PhotosFragment.ListViewItem> {
public ListViewDemoAdapter(Context context, List<PhotosFragment.ListViewItem> items) {
super(context, R.layout.listview_item, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.listview_item, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
PhotosFragment.ListViewItem item = getItem(position);
//viewHolder.ivIcon.setImageDrawable(item.image);
viewHolder.tvTitle.setText((Html.fromHtml(item.title)));
viewHolder.tvDescription.setText(Html.fromHtml(item.description));
if (!item.adUrl.isEmpty()) {
Picasso.with(getContext())
.load(item.adUrl)
.into(viewHolder.ivIcon);
viewHolder.ivIcon.setVisibility(viewHolder.ivIcon.VISIBLE);
viewHolder.ivIcon.setOnClickListener(new View.OnClickListener() {
//#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.myaddress.co.uk"));
getContext().startActivity(browserIntent);
}
});
}else {
viewHolder.ivIcon.setVisibility(viewHolder.ivIcon.GONE);
}
return convertView;
}
/**
* The view holder design pattern prevents using findViewById()
* repeatedly in the getView() method of the adapter.
*
* #see
*/
private static class ViewHolder {
ImageView ivIcon;
TextView tvTitle;
TextView tvDescription;
}
}
ListFragment comes with a ListView, a ProgressBar (displayed till you write setListShown(true);) and a TextView (which is shown when the ListView has no items.
If you want to add anything above ListView, the easy way to do that is to replace ListFragment with Fragment and inflating your own XML. Like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
And setting up your fields and populating data in onActivityCreated(), like:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("created", "onActivityCreated()");
setHasOptionsMenu(true);
mProgressBar = (ProgressBar) getView().findViewById(R.id.progressBar1);
mListView = (ListView) getView().findViewById(R.id.listView1);
mTvEmpty = (TextView) getView().findViewById(R.id.tv_empty);
// load your data to your mListView
}
Edit:
Update your onPostExecute() to:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
}
else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
// initialize and set the list adapter
//setListAdapter(new ListViewDemoAdapter(getActivity(), mItems));
}
//mProgressBar = (ProgressBar) getView().findViewById(R.id.progressBar);
ListView mListView = (ListView) getView().findViewById(R.id.listView2);
//mTvEmpty = (TextView) getView().findViewById(R.id.textView);
Log.d("mListView: ", String.valueOf(mListView));
ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.simple_list_item_1, mItems);
Log.d("Adapter: ", String.valueOf(adapter));
// load your data to your mListView
mListView.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
You were creating adapter even if mItems was null (putting it after catch would run it always).