I am working on an application related with news, I have successfully parsed a json response and displayed the data in listview.
But the listview is not loading data at first time and remains empty.
On second time it displayed parsed data in listview.
What might be the problem ? Below is my code
// This is my java file:
public class FunHallListActivity extends AppCompatActivity {
FunHallDBHandler funhallhandler;
SQLiteDatabase db;
InputStream is=null;
String resultFunHall = null;
String line=null;
int code;
String URL = "";
private Context context;
private ListView fhListview;
private FunHallAdapter adapterfunhall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_hall_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
fhListview=(ListView)findViewById(R.id.funhall_lv);
context=this;
new FunHallFetcherTask().execute();
funhallhandler=new FunHallDBHandler(context);
ArrayList<FunHall> fhDataList = new ArrayList<FunHall>();
fhDataList = funhallhandler.getAllFunHall();
adapterfunhall = new FunHallAdapter(context, fhDataList);
fhListview.setAdapter(adapterfunhall);
}
//Json parsing code with to fech and add into Sqlite Database
class FunHallFetcherTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://cmr.newsoft.co.in/FunctionalHall.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("pass 1", "connection success ");
Log.d("Data:",is.toString());
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
resultFunHall = sb.toString();
Log.d("Json_string_Result", resultFunHall);
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.d("Fail 2", e.toString());
}
// Log.e(result,"hello");
try
{
JSONArray jArrayFunHall = new JSONArray(resultFunHall);
for(int i=0; i<jArrayFunHall.length();i++)
{
Log.d("jArrayFunHall.length()", ""+jArrayFunHall.length());
JSONObject json_data = jArrayFunHall.getJSONObject(i);
publishProgress();
code=1;
String funhall_Name = json_data.getString("Name");
String funhall_Address = json_data.getString("Address");
String funhall_Phone = json_data.getString("Phone");
FunHall funhall=new FunHall();
funhall.setFHallName(funhall_Name);
funhall.setFHalladdress(funhall_Address);
funhall.setFHallContact(funhall_Phone);
funhallhandler.addFunHall(funhall);
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
//Json Parsing code end
return null;
}
}
}
// and this is my adapter
public class FunHallAdapter extends BaseAdapter {
private List<FunHall> funHallList;
private Context context;
private LayoutInflater layoutInflater;
public FunHallAdapter(Context context, List<FunHall> funHallList)
{
this.context = context;
this.funHallList = funHallList;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return funHallList.size();
}
#Override
public FunHall getItem(int position) {
return funHallList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tvfunHallName,tvfunHalladdress,tvfunHallcontact;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Holder holder;
if (convertView == null)
{
holder = new Holder();
convertView = layoutInflater.inflate(R.layout.funhall_list_item,null);
holder.tvfunHallName=(TextView)convertView.findViewById(R.id.funhallname_tv);
holder.tvfunHalladdress=(TextView)convertView.findViewById(R.id.funhalladdress_tv);
holder.tvfunHallcontact=(TextView)convertView.findViewById(R.id.hunhallcantact_tv);
convertView.setTag(holder);
}else
{
holder = (Holder) convertView.getTag();
}
holder.tvfunHallName.setText(funHallList.get(position).getFHallName());
holder.tvfunHalladdress.setText(funHallList.get(position).getFHalladdress());
holder.tvfunHallcontact.setText(funHallList.get(position).getFHallContact());
return convertView;
}
}
i think you must declare setAdapter was onPostExecute. don't declare before onPreExecute or doInBackground. i think it was issue..
Issue is that you are not notifying the adapter when data is changed.
Follow the steps
1. Modify your constructor
ArrayList<FunHall> funHallList;
public FunHallAdapter(Context context, ArrayList<FunHall> funHallList)
{
this.context = context;
this.funHallList = funHallList;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Step 2.
In your FunHallAdapter add this method
public void swapData(ArrayList<FunHall> funHallList){
this.funHallList = funHallList;
notifyDataSetChanged();
}
In your FunHallListActivity
class FunHallFetcherTask extends AsyncTask<Void,Void,String> {
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://cmr.newsoft.co.in/FunctionalHall.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("pass 1", "connection success ");
Log.d("Data:",is.toString());
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
resultFunHall = sb.toString();
Log.d("Json_string_Result", resultFunHall);
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.d("Fail 2", e.toString());
}
// Log.e(result,"hello");
return resultFunHall ;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!TextUtils.isEmpty(s)) {
try
{
JSONArray jArrayFunHall = new JSONArray(resultFunHall);
for(int i=0; i<jArrayFunHall.length();i++)
{
Log.d("jArrayFunHall.length()", ""+jArrayFunHall.length());
JSONObject json_data = jArrayFunHall.getJSONObject(i);
publishProgress();
code=1;
String funhall_Name = json_data.getString("Name");
String funhall_Address = json_data.getString("Address");
String funhall_Phone = json_data.getString("Phone");
FunHall funhall=new FunHall();
funhall.setFHallName(funhall_Name);
funhall.setFHalladdress(funhall_Address);
funhall.setFHallContact(funhall_Phone);
funhallhandler.addFunHall(funhall);
}
adapterfunhall.swapData(funhallhandler.getAllFunHall());
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
}
}
i found what mistake i did, and i solved it as follow,
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ArrayList<FunHall> fhDataList = new ArrayList<FunHall>();
fhDataList = funhallhandler.getAllFunHall();
adapterfunhall = new FunHallAdapter(context, fhDataList);
fhListview.setAdapter(adapterfunhall);
}
Related
I've been working on an android app ... I am stuck at a point ... after getting the JSON data from the internet I am having trouble to show it in the ListView ... Below is my code ...
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.name_lst_view,
R.id.name_list_view_textview,
blogTitles
);
ListView listView = (ListView) rootView.findViewById(R.id.listview_name);
listView.setAdapter(titleAdapter);
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
}
}
}
From the above code you can see that i am getting that data through doInBackground method of AsyncTask ... Data is coming through perfectly as I can see through the logcat ... The issue is somewhere in this method which I can't seem to figure out ..
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
The above method is called in onPostExecute I mean if i print to logcat within this method I can see the results being printed but when I try to show those results in the onCreateView method results don't show up not even in the logcat ... Any help will be appreciated ... Thanks
Change your code as following:
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
ListView listView;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listview_name);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
return rootView;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.name_list_view,
R.id.name_list_view_textview,
blogTitles
);
listView.setAdapter(titleAdapter);
}
}
}
Use same array list in both update and initialize so globally declare a single array list and update it in updateList() method,
Try like this,
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];//remove this and use the
//same as you are using in adapter
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
titleAdapter.notifyDataSetChanged();//here
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
OR even you can use in onPostExecute
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
titleAdapter.notifyDataSetChanged();//here
}
find the listview : ListView listView = (ListView) rootView.findViewById(R.id.listview_name); before calling
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
and put this line listView.setAdapter(titleAdapter); in your onPostExecute method.
I have a sliding image that extends pageradapter. At first it was working. But when i open new activity then press the back button the app is crashing and i've got this error :
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 10, found: 0 Pager id: malate.denise.chelsie.igphthesisbfinal:id/pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class malate.denise.chelsie.igphthesisbfinal.SlidingImage_Adapter
Here's my SlidingImage_Adapter.class
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Pictures> IMAGES;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context,ArrayList<Pictures> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.slidingimage_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
new DownloadImageTask(imageView).execute(IMAGES.get(position).getPhotopath());
// imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
notifyDataSetChanged();
}
#Override
public Parcelable saveState() {
return null;
}
and my AttractionInfo.class
public class AttractionInfo extends ActionBarActivity implements View.OnClickListener {
TextToSpeech tts;
TextView nameofplace,location,exact_address,operatinghours,info;
String nameofplace_s,location_s,exact_address_s,operatinghours_s,info_s,latlang_s,path_s,category_s;
ImageView play,rate,addtoplan,map;
ArrayList<Pictures> records;
private static ViewPager mPager;
private static int currentPage = 0;
String line=null;
private static int NUM_PAGES = 0;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_info);
map = (ImageView)findViewById(R.id.map);
map.setOnClickListener(this);
records=new ArrayList<Pictures>();
nameofplace = (TextView) findViewById(R.id.nameofplace);
info = (TextView) findViewById(R.id.info);
exact_address = (TextView) findViewById(R.id.exact_address);
location = (TextView)findViewById(R.id.location);
operatinghours=(TextView)findViewById(R.id.operatinghours);
play = (ImageView) findViewById(R.id.play);
rate = (ImageView) findViewById(R.id.rate);
addtoplan = (ImageView)findViewById(R.id.addtoplan);
addtoplan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
play.setOnClickListener(this);
rate.setOnClickListener(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setDisplayShowTitleEnabled(false);
tts = new TextToSpeech(AttractionInfo.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
if (extras != null) {
nameofplace_s = extras.getString("name");
nameofplace.setText(nameofplace_s);
info_s = extras.getString("description");
info.setText(info_s);
exact_address_s = extras.getString("exactaddress");
exact_address.setText(exact_address_s);
location_s = extras.getString("location");
location.setText(location_s);
operatinghours_s=extras.getString("operatinghours");
operatinghours.setText(operatinghours_s);
latlang_s = extras.getString("latlang");
path_s=extras.getString("path");
category_s = extras.getString("category");
}
}
public void onStart() {
super.onStart();
fetchphoto bt = new fetchphoto();
bt.execute();
}
#Override
protected void onPause() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onClick(View v) {
if (v == play) {
String speech1 = nameofplace.getText().toString();
String speech2 = info.getText().toString();
String speech = speech1 + "." + speech2;
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
} else if (v==rate){
Intent myIntent = new Intent(this, ListOfReviews.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if(v==addtoplan){
Intent myIntent = new Intent(this, AddPlan.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
startActivity(myIntent);
}else if (v == map){
Intent myIntent = new Intent(this, Map.class);
myIntent.putExtra("placename", nameofplace_s);
myIntent.putExtra("category",category_s);
myIntent.putExtra("latlang",latlang_s);
myIntent.putExtra("address",exact_address_s);
myIntent.putExtra("path",path_s);
startActivity(myIntent);
}
}
private void init() {
SlidingImage_Adapter adapter = new SlidingImage_Adapter(this,records);
for(int i=0;i<records.size();i++){
Pictures pics = records.get(i);
String pic = pics.getPhotopath();
adapter.notifyDataSetChanged();
}
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
CirclePageIndicator indicator = (CirclePageIndicator)
findViewById(R.id.indicator);
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
NUM_PAGES =records.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
},5000, 5000);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
private class fetchphoto extends AsyncTask<Void, Void, Void> {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
nameValuePairs.add(new BasicNameValuePair("cityname", nameofplace_s));
try
{
records.clear();
HttpParams httpParams = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://igph.esy.es/getphoto.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//parse json data
try {
Log.i("tagconvertstr", "["+result+"]");
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Pictures p = new Pictures();
p.setPhotoname(json_data.getString("photo_name"));
p.setPlacename(json_data.getString("place_name"));
p.setCategory(json_data.getString("category"));
p.setPhotopath(json_data.getString("path"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
init();
}
}
}
I've red some similar problems and learned that adding notifychanged may solved the problem but i dont where to place it. Hope you can help m . thanks
I have a jsonArray which I want to parse in my android app.
The array:-
[
{
"id": 96905,
"category": "topup",
"detail": "Full talktime of Rs.55 + 1 local airtel SMS free for 1 day",
"price": 55,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"validity": "7 days",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 55
},
{
"id": 90397,
"category": "topup",
"price": 510,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 520
},
{
"id": 90399,
"category": "topup",
"price": 1000,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 1020
}]
My android Code:-
Asynctask:-
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
JSONObject jo;
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam");
for (int i = 0; i < ja2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jo = ja2.getJSONObject(i);
map.put("rank", jo.getString("price"));
map.put("country", jo.getString("validity"));
map.put("population", jo.getString("talktime"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
JsonFunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
The error I get:-
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:67)
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
The json is hosted here
I was following this tutorial for learning json parsing, but this tutorial uses jsonObject and I am not able to parse the json array.
Not a duplicate to this :-Sending and Parsing JSON Objects or this How to parse this JSON Array in android?
Let me offer an alternate solution (of sorts). A much simpler version of your existing code would be:
Updated code:
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(TestListActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam";
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
okHttpClient.setRetryOnConnectionFailure(true);
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
String strResult = response.body().string();
JSONArray JARoot = new JSONArray(strResult);
for (int i = 0; i < JARoot.length(); i++) {
JSONObject JORoot = JARoot.getJSONObject(i);
HashMap<String, String> map = new HashMap<>();
if (JORoot.has("category") && JORoot.getString("category").equals("topup")) {
if (JORoot.has("id")) {
map.put("id", JORoot.getString("id"));
}
if (JORoot.has("category")) {
map.put("category", JORoot.getString("category"));
}
if (JORoot.has("detail")) {
map.put("detail", JORoot.getString("detail"));
} else {
map.put("detail", null);
}
if (JORoot.has("price")) {
map.put("price", JORoot.getString("price"));
}
/** ADD THE COLLECTED DATA TO THE ARRAY LIST **/
arraylist.add(map); /* THE DATA WILL ONLY BE ADDED IF THE CATEGORY = "topup" */
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ListView testList = (ListView) findViewById(R.id.testList);
TestListAdapter adapter = new TestListAdapter(TestListActivity.this, arraylist);
testList.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
private class TestListAdapter extends BaseAdapter {
Activity activity;
// LAYOUTINFLATER TO USE A CUSTOM LAYOUT
LayoutInflater inflater = null;
// ARRAYLIST TO GET DATA FROM THE ACTIVITY
ArrayList<HashMap<String, String>> arrItem;
public TestListAdapter(Activity activity, ArrayList<HashMap<String, String>> arrItem) {
this.activity = activity;
// CAST THE CONTENTS OF THE ARRAYLIST IN THE METHOD TO THE LOCAL INSTANCE
this.arrItem = arrItem;
// INSTANTIATE THE LAYOUTINFLATER
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrItem.size();
}
#Override
public Object getItem(int position) {
return arrItem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// A VIEWHOLDER INSTANCE
ViewHolder holder;
// CAST THE CONVERTVIEW IN A VIEW INSTANCE
View vi = convertView;
// CHECK CONVERTVIEW STATUS
if (convertView == null) {
// CAST THE CONVERTVIEW INTO THE VIEW INSTANCE vi
vi = inflater.inflate(R.layout.test_item, null);
// INSTANTIATE THE VIEWHOLDER INSTANCE
holder = new ViewHolder();
/***** CAST THE LAYOUT ELEMENTS *****/
/* TOP (PRIMARY) ELEMENTS */
holder.txtPrice = (TextView) vi.findViewById(R.id.txtPrice);
holder.txtDetail = (TextView) vi.findViewById(R.id.txtDetail);
// SET THE TAG TO "vi"
vi.setTag(holder);
} else {
// CAST THE VIEWHOLDER INSTANCE
holder = (ViewHolder) vi.getTag();
}
if (arrItem.get(position).get("price") != null) {
String strPrice = arrItem.get(position).get("price");
holder.txtPrice.setText("PRICE: " + strPrice);
}
if (arrItem.get(position).get("detail") != null) {
String strDetail = arrItem.get(position).get("detail");
holder.txtDetail.setText("DETAIL: " + strDetail);
} else {
holder.txtDetail.setText("DETAIL: NA");
}
return vi;
}
private class ViewHolder {
/* TOP (PRIMARY) ELEMENTS */
TextView txtPrice;
TextView txtDetail;
}
}
For the sake of completeness, I am also including the code for the adapter. It is a simple implementation. Do clean it up / optimize it / customize as per your requirement.
This piece of code has been tested prior to being posted (see screenshot of Logs at the bottom)
This uses the OkHttp library. Add this compile statement to the dependencies section of the module's gradle file: compile 'com.squareup.okhttp:okhttp:2.5.0'. Check the link for an updated version.
The example code uses if statements considering that not every record has the same set of nodes.
You BufferReader is not working as expected in your class JSONfunctions , do some changes in your class and it should looks like
JSONfunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
StringBuffer sb = new StringBuffer("");
try {
URL urls = new URL(url);
URLConnection urlConnection;
urlConnection = urls.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
result=sb.toString();
} catch (IOException e) {}
catch (Exception e) {}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
and to avoid Exception check if JSONArray is not null then only it goes to run for loop like this :
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android? service=airtel&circle=assam");
if(ja2!=null)
for (int i = 0; i < ja2.length(); i++) {}
jsonResponse="";
for(int i = 0; i<response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String id = person.getString("id");
String category = person.getString("category");
}
This question already has answers here:
Error parsing data org.json.JSONException: Value String cannot be converted to JSONArray
(2 answers)
Closed 8 years ago.
Here is list activity
ListActivity:
public class ListDataActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_listview);
url = "http://xxx.xx.x.xxx/index.php";
Bundle c = getIntent().getExtras();
blo = c.getString("blood");
new ProgressTask(ListDataActivity.this).execute();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
class ProgressTask extends AsyncTask<String, Void, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(),
"INTERNET CONNECTION NOT PRESENT", Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(ListDataActivity.this,
MainActivity.class));
}
}
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {}
#Override
protected void onPostExecute(final Boolean success) {
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.row_listitem, new String[] { name, Category },
new int[] { R.id.vehicleType, R.id.vehicleColor }) {
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_listitem,
null);
}
// TODO Auto-generated method stub
if (position % 2 == 1)
convertView.setBackgroundColor(Color.rgb(120, 151, 66));
else
convertView.setBackgroundColor(Color.rgb(86, 107, 129));
return super.getView(position, convertView, parent);
}
};
setListAdapter(adapter);
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
protected Boolean doInBackground(final String... args) {
url = url + "?blo_name=" + blo;
Log.d("", url);
baseAdapter jParser = new baseAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtype = c.getString(name);
String vfuel = c.getString(Category);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(name, vtype);
map.put(Category, vfuel);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
Base Adapter class:
public class baseAdapter {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public baseAdapter() {}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed ");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray(builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
PHP:
if (isset($_POST['blo_name'])) {
$str = $_POST['blo_name'];
$sql = "SELECT * FROM blood_group where Category IN ($str)";
$result = mysql_query($sql);
while ($row=mysql_fetch_array($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
}
I am trying to parse bol string, it have value like bol="'B-','O-'"; while I parse this type of value it didn't show results and gives the logcat
logcat:
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
I need to get result against query SELECT * FROM blood_group where Category IN ($str) but I cannot get. When I give hard core value in php like $str = "'A+','B+'"; it give me result while parsing from android it does not give result while in logcat I can see value http://xxx.xx.x.xxx/heart.php?blo_name='A','B' but error as well.
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
Notice <br - the web service is returning HTML and not a plain JSON string. Basically you need to fix your PHP response so it doesn't return HTML.
I have made an listview application, then i created a new one with fragments and want to implement listview to fragments. But when i do i got an strange error.
public class Fragment1 extends Fragment {
private ArrayList<FeedItem> feedList = null;
private ProgressBar progressbar = null;
private ListView feedListView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_row_layout, container, false);
progressbar = (ProgressBar)rootView.findViewById(R.id.progressBar);
String url = "";
new DownloadFilesTask().execute(url);
return rootView;
}
public void updateList() {
feedListView= (ListView)getActivity().findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
**feedListView.setAdapter(new CustomListAdapter(this, feedList));**
feedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
FeedItem newsData = (FeedItem) o;
**Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);**
intent.putExtra("feed", newsData);
startActivity(intent);
}
});
}
public class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
if (null != feedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.getString("title"));
item.setDate(post.getString("description"));
item.setId(post.getString("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("description"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
feedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Problems are on this lines
feedListView.setAdapter(new CustomListAdapter(this, feedList));
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
Multiple markers at this line
- Line breakpoint:Fragment1 [line: 57] - updateList()
- The constructor CustomListAdapter(Fragment1, ArrayList<FeedItem>) is
undefined
No enclosing instance of the type FeedListActivity is accessible in scope
CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = (FeedItem) listData.get(position);
holder.headlineView.setText(newsItem.getTitle());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getAttachmentUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
in this line feedListView.setAdapter(new CustomListAdapter(this, feedList)); just replace this with getActivity();