NullPointerException while listview fills - java

I have MainActivity class where I parse an HTML page with JSOUP and I also have custom adapter which store data for each row in my ListView. So I get data with JSOUP and it's ok as my LogCat tell me. But when I try to put data to my ListView I get an error.
My activity_main layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
My list_item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/thumbImageNews"
android:layout_marginLeft="10dp"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/titleNews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/thumbImageNews"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="5dp"
android:text=""
android:textColor="#ff0d075c"
android:textStyle="italic"
android:typeface="sans"
android:gravity="center"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/date2News"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/thumbImageNews"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="2dp"
android:text=""
android:textColor="#ff585858"
android:textSize="12sp"
android:layout_marginLeft="10dp"/>
</RelativeLayout>
CustomListAdapter activity:
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_item, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.titleNews);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date2News);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImageNews);
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;
}
}
FeedItem class to store data for each row:
public class FeedItem implements Serializable {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
private String date;
public String getAttachmentUrl() {
return attachmentUrl;
}
public void setAttachmentUrl(String attachmentUrl) {
this.attachmentUrl = attachmentUrl;
}
private String attachmentUrl;
}
And my MainActivity class where executes all main functions:
public class MainActivity extends Activity {
public Elements title;
public Elements picture;
final String ATTRIBUTE_NAME_TEXT = "text";
final String ATTRIBUTE_NAME_IMAGE = "image";
final String ATTRIBUTE_NAME_DATE = "date";
private ArrayList<FeedItem> feedList = null;
private ListView feedListView = null;
public CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
feedListView = (ListView) findViewById(R.id.listView1);
new NewThread().execute();
}
public class NewThread extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
Document doc;
try {
doc = Jsoup.connect("http://example.com/news/").get();
title = doc.select("h2[class=et_pt_title]");
picture = doc.select("img");
for (Element titles : title) {
FeedItem item = new FeedItem();
item.setTitle(titles.text());
Log.w("title",""+item.getTitle());
feedList.add(item);
}
for (Element img : picture){
String iurl;
iurl = img.absUrl("src");
FeedItem item = new FeedItem();
item.setAttachmentUrl(iurl);
Log.w("imgUrl",""+item.getAttachmentUrl());
feedList.add(item);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
adapter = new CustomListAdapter(MainActivity.this,feedList);
feedListView.setAdapter(adapter);
}
}
}
So my problem is that when feedList.add(item); executes I get NullPointerException, but Log.w("title",""+item.getTitle()); shows me that everything is ok. What I do wrong?

Your feedList is not initialized.
So before adding items to it, please initialize.
ArrayList<FeedItem> feedList = new ArrayList<FeedItem> ;
Add the above line before you call the AsyncTask i.e. before new NewThread().execute();
It should look like this
feedList = new ArrayList<FeedItem> ;
new NewThread().execute();

Your mistake was you have just declared this
private ArrayList<FeedItem> feedList = null;
not initialized. So just initialize on onCreate() method.
feedList = new ArrayList<FeedItem> ;

private ArrayList<FeedItem> feedList = null;
without create object you are adding data in arraylist
feedList.add(item);
please create object
feedList = new ArrayList<FeedItem>()
than Add
feedList.add(item);

Related

Locally stored images are not displayed in the CardView inside a RecyclerView

I have a RecyclerView which has CardView as its list items. The CardView have only 2 TextView and one ImageView.
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
android:id="#+id/dcCardView">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/detail_coast_cardview_bg">
<ImageView
android:id="#+id/dcImage"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:src="#drawable/radiation"
android:layout_gravity="center_vertical" />
<LinearLayout
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/dcName"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="212"
android:textSize="18dp" />
<TextView
android:textColor="#fff"
android:id="#+id/dcValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="renu asdasasd"
android:textSize="18dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
The class that goes in it is this
public class DetailedCoastRecyclerView {
//region fields
private String name;
private String value;
private int imageName;
//end region fields
//constructor
public DetailedCoastRecyclerView() {}
public DetailedCoastRecyclerView(String name, String value, int image) {
this.name = name;
this.value = value;
this.imageName = image;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public int getImageName() {
return imageName;
}
}
And my CoastDetailsActivity2
public class CoastDetailsActivity2 extends AppCompatActivity {
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private int coastId;
private String jsonCoastDetailsString = "";
private RecyclerView recyclerView;
private DetailedCoastAdapter detailedCoastAdapter;
private ImageView btnBlueFlag;
private ImageView btnHandycapFriendly;
private ImageView btnFavorite;
private ImageView btnWaze;
private LinearLayout mainLayout;
private Beach mBeach;
private TextView tvBeachName;
private DetailedCoastWithForcast detailedCoastWithForcast;
private DetailedBeachMetadata detailedBeachMetadata;
private DetailedBeachHourlyForecast dbhfToday;
private List<DetailedCoastRecyclerView> detailedCoastRecyclerViewList = new ArrayList<>();
private Map<String, String> windBearing = new HashMap<>();
private Map<String, String> jellyType = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coast_details2);
setPointer();
}
private void setPointer() {
this.context = this;
mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
sharedPreferences = context.getSharedPreferences(sharedPreferencesName, MODE_PRIVATE);
editor = sharedPreferences.edit();
tvBeachName = (TextView) findViewById(R.id.tvBeachName);
//start the forecast activity
tvBeachName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ForecastActivity.class);
intent.putExtra("coastId", coastId);
startActivity(intent);
}
});
AndroidNetworking.initialize(context);
//get the coastId
Bundle extras = getIntent().getExtras();
if (extras == null) {
//TODO add snackbar for error
} else {
coastId = extras.getInt("coastId");
}
getBeachDetails();
recyclerView = (RecyclerView) findViewById(R.id.dcRecyclerView);
detailedCoastAdapter = new DetailedCoastAdapter(detailedCoastRecyclerViewList, context);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(detailedCoastAdapter);
}
}
And the adapter
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.myViewHolder> {
Context context;
private List<DetailedCoastRecyclerView> dbhf0;
public ForecastAdapter(Context context, List<DetailedCoastRecyclerView> dbhf0) {
this.context = context;
this.dbhf0 = dbhf0;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.detailed_coast_card, parent, false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
DetailedCoastRecyclerView dcrv = dbhf0.get(position);
holder.tvName.setText(dcrv.getName());
holder.tvValue.setText(dcrv.getValue());
//holder.ivImage.setImageResource(dcrv.getImageName());
Glide.with(context).load(dcrv.getImageName()).into(holder.ivImage);
}
#Override
public int getItemCount() {
return dbhf0.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView ivImage;
TextView tvName;
TextView tvValue;
public myViewHolder(View itemView) {
super(itemView);
ivImage = (ImageView) itemView.findViewById(R.id.dcImage);
tvName = (TextView) itemView.findViewById(R.id.dcName);
tvValue = (TextView) itemView.findViewById(R.id.dcValue);
}
}
}
When I run it, the getBeachDetails() method gets all the info from the server, add it to an ArrayList and calls notifyDataSetChanged() on the adapter.
I know its working because I see the name and value for every card but the images which are stored locally are not displayed.
I use the same adapter inside a ViewPager with 3 fragments and there everything is ok.
Any ideas?
You provided code of ForecastAdapter, but actually you are using DetailedCoastAdapter. Make sure whether they are the same.
Check whether you have a valid url/resource in dcrv.getImageName()
I guess your image resolution is too high that android buffer cant handle and throws exception while rendering your image, so as I know you have to decrease your image quality when loading it on ImageView.
In Picasso this is done like this by calling resize(width,height) method.
Picasso.with(context)
.load(res)
.resize(width,height)
.placeholder(placeHolder)
.into(view);
I guess it is done in the same way with Glide.

ListView not displayed in Fragment (Android)

So im following this tutorial http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ on how to parse a JSON Api and displays data into Listview
I tried to adapt the code in my fragment , in onCreateView method , but the Listview is not displayed (blank fragment). And i dont know why.
I imported all the required libs
Actor.java
public class Actors {
private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
ActorAdapter.java
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
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.TextView;
import info.androidhive.navigationdrawer.R;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.imgadd);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
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);
}
}
}
Articles.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:src="#drawable/imgadd" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tom Cruise"
android:textColor="#166CED"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvDateOfBirth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="Date of Birth: July 3, 1962" />
<TextView
android:id="#+id/tvHeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Height: 1.80 m"
android:textColor="#D64530"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/tvCountry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="United States" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/tvDescriptionn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009A57"
android:text="Description" />
<TextView
android:id="#+id/tvSpouse"
android:layout_width="wrap_content" android:textColor="#166CED"
android:layout_height="wrap_content"
android:text="Spouse: Katie Holmes" />
<TextView
android:id="#+id/tvChildren"
android:layout_width="wrap_content" android:textColor="#166CED"
android:layout_height="wrap_content"
android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />
</LinearLayout>
Fragment_accueil.xml (my fragment layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical"
tools:context="info.androidhive.navigationdrawer.fragment.AccueilFragment">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/articles">
</ListView>
</LinearLayout>
fragment_accueil.java (my fragment activity)
//import.....
public class AccueilFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
int score = 0;
TextView t1, t2, t3,t4;
ImageView img;
private OnFragmentInteractionListener mListener;
public AccueilFragment() {
}
public static AccueilFragment newInstance(String param1, String param2) {
AccueilFragment fragment = new AccueilFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_accueil, container, false);
t1 = (TextView) view.findViewById(R.id.tvName);
t2 = (TextView) view.findViewById(R.id.tvDateOfBirth);
t3 = (TextView) view.findViewById(R.id.tvHeight);
t3 = (TextView) view.findViewById(R.id.tvCountry);
img = (ImageView) view.findViewById(R.id.ivImage);
ArrayList actorsList = new ArrayList<Actors>();
ListView listview = (ListView) view.findViewById(R.id.list);
ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);
listview.setAdapter(adapter);
new getData().execute();
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
class getData extends AsyncTask<String, String, String> {
HttpURLConnection urlConnection;
#Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jsono = new JSONObject(result);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
What's the problem and how to fix that ? thanks
There is couple of things wrong:
1.You are not adding Actors actor = new Actors(); to the actorsList
2.Calling this:
ArrayList actorsList = new ArrayList<Actors>();
ListView listview = (ListView) view.findViewById(R.id.list);
ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);
will reuslt in blank data in listview
I would suggest you to add the data in your onPostExecute() to the Arraylist and then initialize the adapter with the data.
or you can also call
adapter.notifyDataSetChanged() in onPostExecute()
Are you adding the ListView in your fragment that you want it to be displayed for example:
public class FragmentMain extends Fragment
{
private ListView listView; //Define the list view up here.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Set the listview equal to the fragment name
listView = inflater.inflate(R.layout.fragment_name, container, false);
}
}
This should work, let me know if otherwize :)

Android: calling getview() for ListView's Adapter from Fragment in viewPager

I have ViewPager that containing 3 different Fragment. each Fragment containing A Different View and also ListView, I got a problem when I was trying to show the ListView in one of Fragment from ViewPager, it doesn't show anything. I've tried to debug my adapter and it seems my getView() method is not called. I try to call my Fragment not from ViewPager, the result is getView() is called from adapter and ListView is showing. Is there any problem to show ListView from ViewPager? I have tried this solution by calling my adapter from onViewCreated() but there's nothing change. so is there any wrong with my method? this is my code :
My Fragment Class for Managing ViewPager
public class Frag_Provider extends Fragment {
private String[] tabsTitles = {"TERDEKAT", "SEMUA", "PROVIDERKU"};
String url = "";
List<ModelProvider> list_provider;
DB_Esehat db_esehat = null;
SQLiteDatabase db = null;
ContentLoadingProgressBar progressbar;
TabLayout tabLayout;
ViewPager pager;
public Frag_Provider (){
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).custom_toolbar("Provider", R.color.toolbar_provider, R.color.toolbar_provider_dark);
View result=inflater.inflate(R.layout.fragment_provider, container, false);
list_provider = new ArrayList<ModelProvider>();
progressbar = (ContentLoadingProgressBar)result.findViewById(R.id.progressbar);
db_esehat = new DB_Esehat(getActivity());
db = db_esehat.getWritableDatabase();
db.delete("LST_PROVIDER", null, null);
pager=(ViewPager)result.findViewById(R.id.pager);
tabLayout = (TabLayout)result.findViewById(R.id.sliding_tabs);
url = getResources().getString(R.string.url_host)+getResources().getString(R.string.url_provider);
new ProviderTask(url).execute();
pager.setAdapter(buildAdapter(tabsTitles));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(pager);
}
});
return(result);
}
public class ProviderTask extends AsyncTask<String, Void, String> {
String url = "";
public ProviderTask(String url) {
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
progressbar.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.VISIBLE);
super.onPostExecute(result);
if (result.equals("") || result.equals(null)) {
MethodSupport.AlertDialog(getActivity());
} else {
try {
JSONArray Data = new JSONArray(result);
for (int i = 0; i < Data.length(); i++) {
String LSKA_NOTE = "";
String RSALAMAT = "";
String RSTELEPON = "";
String RSNAMA = "";
String MAPPOS = "";
int RSTYPE = 0;
int RSID = 0;
int RS_NTT = 0;
JSONObject json = Data.getJSONObject(i);
if (json.has("LSKA_NOTE")) {
LSKA_NOTE = json.getString("LSKA_NOTE");
}
if (json.has("RSALAMAT")) {
RSALAMAT = json.getString("RSALAMAT");
}
if (json.has("RSTELEPON")) {
RSTELEPON = json.getString("RSTELEPON");
}
if (json.has("RSNAMA")) {
RSNAMA = json.getString("RSNAMA");
}
if (json.has("MAPPOS")) {
MAPPOS = json.getString("MAPPOS");
}
if (json.has("RSTYPE")) {
RSTYPE = json.getInt("RSTYPE");
}
if (json.has("RSID")) {
RSID = json.getInt("RSID");
}
if (json.has("RS_NTT")) {
RS_NTT = json.getInt("RS_NTT");
}
db_esehat.InsertRS(LSKA_NOTE, RSALAMAT, RSTELEPON, RSNAMA, MAPPOS, RSTYPE, RSID, RS_NTT);
}
} catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
}
private PagerAdapter buildAdapter(String[] tabsTitles) {
return(new FragmentStatePagerAdapter(getActivity(), getChildFragmentManager(),tabsTitles));
}
}
This is FragmentStatePagerAdapter.java
public class FragmentStatePagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
private String[] tabsTitles;
public FragmentStatePagerAdapter(Context ctxt, FragmentManager mgr, String[] tabsTitles) {
super(mgr);
this.ctxt=ctxt;
this.tabsTitles = tabsTitles;
}
#Override
public int getCount() {
return tabsTitles.length;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return Frag_Provider_Terdekat.newInstance(position);
case 1:
return Frag_Provider_Semua.newInstance(position);
case 2:
return Frag_Provider_Ku.newInstance(position);
}
return null;
}
// #Override public float getPageWidth(int position) { return(0.7f); }
#Override
public String getPageTitle(int position) {
return tabsTitles[position];
}
}
this is my Fragment_Provider.xml, Layout for managing my ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</RelativeLayout>
This is of my Fragment in ViewPagerthat containing ListView :
public class Frag_Provider_Terdekat extends Fragment {
private static final String KEY_POSITION="position";
private ListView list_provider;
List<ModelProviderTerdekat> list_ekamedicare;
DB_Esehat db_esehat;
SQLiteDatabase db;
ProviderTerdekatAdapter adapter;
static Frag_Provider_Terdekat newInstance(int position) {
Frag_Provider_Terdekat frag=new Frag_Provider_Terdekat();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
return("PROVIDER KU");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_child_providerterdekat, container, false);
list_provider = (ListView)result.findViewById(R.id.list_provider);
list_ekamedicare = new ArrayList<ModelProviderTerdekat>();
db_esehat = new DB_Esehat(getActivity());
list_ekamedicare = db_esehat.getProvider();
adapter = new ProviderTerdekatAdapter(getActivity().getApplicationContext(), R.layout.adapter_provider, list_ekamedicare);
list_provider.setAdapter(adapter);
return result;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and this is Adapter for my ListView
public class ProviderTerdekatAdapter extends ArrayAdapter<ModelProviderTerdekat> {
List<ModelProviderTerdekat> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
static class ViewHolder {
ImageView imvprov_map;
ImageView imvprov_fav;
TextView textprov_nama_rs;
TextView textprov_alamat_rs;
TextView textprov_km_rs;
}
public ProviderTerdekatAdapter (Context context, int viewResourceId, List<ModelProviderTerdekat> data) {
super(context, R.layout.adapter_provider, data);
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.adapter_provider, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imvprov_map = (ImageView) view.findViewById(R.id.imvprov_map);
viewHolder.imvprov_fav = (ImageView) view.findViewById(R.id.imvprov_fav);
viewHolder.textprov_nama_rs = (TextView) view.findViewById(R.id.textprov_nama_rs);
viewHolder.textprov_alamat_rs = (TextView) view.findViewById(R.id.textprov_alamat_rs);
viewHolder.textprov_km_rs = (TextView) view.findViewById(R.id.textprov_km_rs);
view.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.textprov_nama_rs.setText(data.get(position).getRSNAMA());
viewHolder.textprov_alamat_rs.setText(data.get(position).getRSALAMAT());
return view;
}
}
I have no Idea why my GetView() not called in my Adapter, is it because I put in ViewPager? well I hope someone understand about it and help me to solver my problem. thank you very much.
Finally.. I found a solution for my problem, it's because I put ViewPager in RelativeLayout after I change into LinearLayout all view displayed as I wanted
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</LinearLayout>

drag-sort-listview Drag is not working Android

I'm using drag-sort-listview to sort rows of my ListView, and I have created a demo using this library, but it is not working. When I try to drag rows it is not working.
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] titles = new String[] { "Strawberry",
"Banana", "Orange", "Mixed" };
public static final String[] descriptions = new String[] {
"It is an aggregate accessory fruit",
"It is the largest herbaceous flowering plant", "Citrus Fruit",
"Mixed Fruits" };
public static final Integer[] images = { R.drawable.drag,
R.drawable.drag, R.drawable.drag, R.drawable.drag };
//ListView listView;
DragSortListView listView;
List<RowItem> rowItems;
CustomListViewAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
listView = (DragSortListView) findViewById(R.id.listview);
//listView = (ListView) findViewById(R.id.list);
final CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
listView.setDropListener(new DropListener() {
#Override
public void drop(int from, int to) {
if (from != to) {
//DragSortListView list = getListView();
RowItem item = adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
listView.moveCheckState(from, to);
//Log.d("DSLV", "Selected item is " + listView.getCheckedItemPosition());
}
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(), "Item "
+ (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:dslv="http://schemas.android.com/apk/res/com.example.testingui"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.mobeta.android.dslv.DragSortListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="5dp"
dslv:collapsed_height="2dp"
dslv:drag_enabled="true"
dslv:drag_handle_id="#drawable/drag"
dslv:drag_scroll_start="0.33"
dslv:drag_start_mode="onMove"
dslv:float_alpha="0.6"
dslv:max_drag_scroll_speed="0.5"
dslv:remove_enabled="true"
dslv:remove_mode="flingRemove"
dslv:slide_shuffle_speed="0.3"
dslv:sort_enabled="true"
dslv:track_drag_sort="true"
dslv:use_default_controller="true" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.descs);
holder.txtTitle = (TextView) convertView.findViewById(R.id.titles);
holder.imageView = (ImageView) convertView.findViewById(R.id.icons);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icons"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/titles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icons"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/descs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titles"
android:layout_toRightOf="#+id/icons"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
RowItem.java
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
Use Drag handle Id in DragSortListView tag in Xml
dslv:drag_handle_id="#id/drag_handle"
Make an id.xml file and put drag handle id as above to make it common and use the same id on dragable handle image view in your row item.
Hope it helps.

Custom ArrayAdapter showing a blank screen in my Fragment

So I've just been messing around with android for a little bit and I've run into a bit of a snag. The fragment where I am instantiating ListOfJokesTypesAdapter for some reason is not displaying a listview populated with the Data from my JokeData class.
All that I get is a blank screen (no errors or anything of that nature).
This is just a proof of concept thing I've been working on so any help would be greatly appreciated. Why is it that this particular custom adapter is not working while my MainClassAdapter is working just fine.
The Code
My Joke Class:
public class Joke {
private String jokeSetup;
private String jokePunchline;
public Joke(String jokeSetup, String jokePunchline) {
this.jokeSetup = jokeSetup;
this.jokePunchline = jokePunchline;
}
public String getJokeSetup() {
return jokeSetup;
}
public void setJokeSetup(String jokeSetup) {
this.jokeSetup = jokeSetup;
}
public String getJokePunchline() {
return jokePunchline;
}
public void setJokePunchline(String jokePunchline) {
this.jokePunchline = jokePunchline;
}
}
My JokeListClass
public class JokeListData {
private String listName;
private List<Joke> arrayListOfJokes;
public JokeListData(String listName, List<Joke> arrayListOfJokes) {
this.listName = listName;
this.arrayListOfJokes = arrayListOfJokes;
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
public List<Joke> getArrayListOfJokes() {
return arrayListOfJokes;
}
public void setArrayListOfJokes(ArrayList<Joke> arrayListOfJokes) {
this.arrayListOfJokes = arrayListOfJokes;
}
}
My Actual Joke Data
public class JokeData {
private static List<Joke> dogJokes = new ArrayList<Joke>(){
{
add(new Joke("Dogs", "Bark"));
add(new Joke("Dogs", "Woof"));
add(new Joke("Dogs", "Howl"));
add(new Joke("Dogs", "Sniff"));
}
};
private static List<Joke> catJokes = new ArrayList<Joke> (){
{
add(new Joke("Cats", "woof"));
add(new Joke("Dogs", "Meow"));
}
};
static List<JokeListData> dataOfJokeList = new ArrayList<JokeListData>();
public static void addEntries(){
dataOfJokeList.add(new JokeListData("Cat Jokes", catJokes));
dataOfJokeList.add(new JokeListData("Dog Jokes", dogJokes));
}
}
The Adapter
public class ListOfJokeTypesAdapter extends ArrayAdapter<JokeListData> {
Context mContext;
int mLayoutId;
List<JokeListData> mList;
public ListOfJokeTypesAdapter(Context context, int resource, List<JokeListData> objects) {
super(context, resource, objects);
this.mContext = context;
this.mLayoutId = resource;
this.mList = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mLayoutId,parent,false);
holder = new ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.rowForMainList);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
JokeListData jokeListData = mList.get(position);
holder.mTextView.setText(jokeListData.getListName());
return convertView;
}
private static class ViewHolder{
TextView mTextView;
}
}
The Fragment which utilizes the adapter
public class ListOfJokeTypesFragment extends Fragment {
ListView mListView;
ListOfJokeTypesAdapter listOfJokeTypesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.joke_type_fragment,container,false);
JokeData.addEntries();
mListView = (ListView)view.findViewById(R.id.jokeTypeListView);
listOfJokeTypesAdapter = new ListOfJokeTypesAdapter(getActivity().getApplicationContext(),R.layout.row,JokeData.dataOfJokeList);
mListView.setAdapter(listOfJokeTypesAdapter);
return view;
}
}
The Fragment Manager
package com.example.taranveer.jokeapplicationactual;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by Taranveer on 2014-07-22.
*/
public class TheFragmentActivityManager extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container);
Bundle args = getIntent().getExtras();
if(findViewById(R.id.container) != null){
if(args != null){
if(args.getInt("randomjoke") == 1){
RandomJokeFragment randomJokeFragment = new RandomJokeFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container, randomJokeFragment)
.commit();
}
}
}
if(findViewById(R.id.container) != null){
if(args!=null){
if(args.getInt("listofjoketypes") == 2){
ListOfJokeTypesFragment listOfJokeTypesFragment = new ListOfJokeTypesFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container,listOfJokeTypesFragment)
.commit();
}
}
}
}
}
The relevant XML:
joke_type_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/jokeTypeListView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_margin="5dp"
android:gravity="center_vertical"
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#eeeeee"
android:textStyle="bold"
android:layout_margin="5dp"
android:padding="5dp"
android:background="#2299dd"
android:textSize="20sp"
android:text="Main Activity Items"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rowForMainList"/>
</LinearLayout>
</LinearLayout>
better to put these lines
JokeListData jokeListData = mList.get(position);
holder.mTextView.setText(jokeListData.getListName());
inside if(convertView == null) condition
beforr#Override
public int getCount() {
return super.getCount();
}
remove this line
You need to override getCount() in your custom adapter.
It will return the number of entries in your ListView.
Replace
#Override
public int getCount() {
return super.getCount();
}
With something like
#Override
public int getCount() {
return mySourceArrayList.getCount();
}

Categories

Resources