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();
}
Related
I'm currently developing an App where I want to use a bottom Navigation with multiple dynamically created Fragments.
Therefore I set up a test app to get used to these funtions.
The problem is now, if I create the ListFragment by a static XML the ListView is created correctly, but If I create it dynamically the ListView does not get displayed, only the BottomNavigation is displayed, nothing else.
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addFragment();
}
private void addFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyListFragment myListFragment = new MyListFragment();
fragmentTransaction.add(R.id.fragmentContainer, myListFragment);
fragmentTransaction.commit();
}
}
Layout:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentContainer"
android:layout_margin="5dp"
android:layout_alignTop="#+id/bottom_nav"/>
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="48dp"
android:id="#+id/bottom_nav"
app:menu="#menu/menu_bottom_nav"
android:background="#808080"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
ListFragment:
public class MyListFragment extends ListFragment implements AdapterView.OnItemClickListener {
CustomerAdapter customerAdapter;
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Customer customer = new Customer("Testcustomer","123456", "654321");
customerAdapter = new CustomerAdapter(Objects.requireNonNull(getActivity()),R.layout.list_pack_item);
listView = new ListView(getActivity());
listView.setAdapter(customerAdapter);
customerAdapter.add(customer);
listView.setOnItemClickListener(this);
return listView;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//do stuff
}
}
CustomerAdapter:
public class CustomerAdapter extends ArrayAdapter {
List list = new ArrayList();
public CustomerAdapter(#NonNull Context context, int resource ) {
super(context, resource);
}
public void add( #Nullable Customer object ) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position ) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent ) {
View row;
row = convertView;
CustomerHolder customerHolder;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.list_pack_item, parent, false);
customerHolder = new CustomerHolder();
customerHolder.tx_name = row.findViewById(R.id.tx_name);
customerHolder.tx_intern = row.findViewById(R.id.tx_intern);
customerHolder.tx_extern = row.findViewById(R.id.tx_extern);
row.setTag(customerHolder);
} else {
customerHolder = (CustomerHolder) row.getTag();
}
Customer customer = (Customer) this.getItem(position);
customerHolder.tx_name.setText(customer.getName());
customerHolder.tx_intern.setText("Internal Number: " + customer.getMyCustomerNumber());
customerHolder.tx_extern.setText("Supplier Number: " + customer.getSupplierNumber());
return row;
}
static class CustomerHolder {
TextView tx_name, tx_intern, tx_extern;
}
}
Customer Class
public class Customer {
private String name;
private String supplierNumber;
private String myCustomerNumber;
public Customer(String name, String supplierNumber, String myCustomerNumber) {
this.name = name;
this.supplierNumber = supplierNumber;
this.myCustomerNumber = myCustomerNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSupplierNumber() {
return supplierNumber;
}
public void setSupplierNumber(String supplierNumber) {
this.supplierNumber = supplierNumber;
}
public String getMyCustomerNumber() {
return myCustomerNumber;
}
public void setMyCustomerNumber(String myCustomerNumber) {
this.myCustomerNumber = myCustomerNumber;
}
}
If there is any further information or code needed please let me know!
Additionally: I need to create the fragments dynamically in order to replace them, am I correct?
I want to display Fragments in a ViewPager however it is only showing the first Fragment in the view tabs. The only fragment that gets shown is the one returned at postion 0 in the getItem(0 method - this fragment is displayed in subsequent views.
FragmentPagerAdapter:
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
public SimpleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new WorldFragment();
} else if (position == 1) {
return new PoliticsFragment();
} else if (position == 2) {
return new TechnologyFragment();
} else if (position == 3) {
return new ScienceFragment();
} else if (position == 4) {
return new SportsFragment();
} else if (position == 5) {
return new FoodFragment();
} else if (position == 6) {
return new TravelFragment();
} else if (position == 7) {
return new MoviesFragment();
} else if (position == 8) {
return new FashionFragment();
} else {
return new OpinionFragment();
}
}
#Override
public int getCount() {
return 10;
}
}
Fragment:
public class WorldFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Story>> {
public static final String LOG_TAG = WorldFragment.class.getName();
private static final String NY_TIMES_REQUEST_URL = "https://api.nytimes.com/svc/topstories/v2/world.json?api-key=<API KEY REMOVED>;
private StoryAdapter mAdapter;
private TextView mEmptyTextView;
private View rootView;
public WorldFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.story_list, container, false);
mAdapter = new StoryAdapter(getActivity(), new ArrayList<Story>());
final ListView listView = (ListView) rootView.findViewById(R.id.story_list);
mEmptyTextView = (TextView) rootView.findViewById(R.id.empty_textview);
listView.setEmptyView(mEmptyTextView);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Story currentStory = mAdapter.getItem(position);
String url = currentStory.getmURL();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected) {
LoaderManager loaderManager = getActivity().getLoaderManager();
loaderManager.initLoader(0, null, this);
} else {
View loadingIndicator = rootView.findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyTextView = (TextView) rootView.findViewById(R.id.empty_textview);
mEmptyTextView.setText(R.string.no_internet_connection);
}
return rootView;
}
#Override
public android.content.Loader<List<Story>> onCreateLoader(int i, Bundle bundle) {
return new StoryLoader(getActivity(), NY_TIMES_REQUEST_URL);
}
#Override
public void onLoadFinished(android.content.Loader<List<Story>> loader, List<Story> stories) {
mAdapter.clear();
View loadingIndicator = rootView.findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
mEmptyTextView.setText(R.string.no_new_stories);
if (stories != null && !stories.isEmpty()) {
mAdapter.addAll(stories);
}
}
#Override
public void onLoaderReset(android.content.Loader<List<Story>> loader) {
mAdapter.clear();
}
#Override
public void onStop() {
super.onStop();
}
}
ViewPager XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.topworldstories.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
List 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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent">
<ListView
android:id="#+id/story_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true" />
<TextView
android:id="#+id/empty_textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
tools:text="No new stories"/>
<ProgressBar
android:id="#+id/loading_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_centerInParent="true"/>
</LinearLayout>
I am unsure of what is causing this. Any help is appreciated
it is only showing the first Fragment multiple times in the view tabs
Two possibilities I see, both of which are copy-paste errors.
1) You didn't change this URL (notice world.json)
private static final String NY_TIMES_REQUEST_URL = "https://api.nytimes.com/svc/topstories/v2/world.json?api-key=<API KEY REMOVED>";
2) You didn't use a different layout.
rootView = inflater.inflate(R.layout.story_list, container, false);
But since your data seems to be consistent, I'm guessing #1 is true.
If you have 10 different URL's that you want to display in the same "fragment layout", you do not need 10 separate Fragment files.
For example, one Fragment
public class NyTimesFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Story>> {
public static final String LOG_TAG = NyTimesFragment.class.getName();
private static final String NY_TIMES_URL = "nyTimesURL";
private StoryAdapter mAdapter;
private TextView mEmptyTextView;
private View rootView;
public NyTimesFragment(String url) {
Bundle b = new Bundle();
b.putExtra(NY_TIMES_URL, url); // Pass URL here
setArguments(b);
}
public NyTimesFragment() {
// Required empty public constructor
}
#Override
public android.content.Loader<List<Story>> onCreateLoader(int i, Bundle bundle) {
// Load url here
String url = getArguments().getString(NY_TIMES_URL);
return new StoryLoader(getActivity(), url);
}
That you pass any NyTimes URL to
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
// List of NyTimes topics
private String[] topics = { "world", "politics" };
// !!! Do NOT store this in your app... !!!
private static final String API_KEY = "XXXXX";
public SimpleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
private String getURL(String apiKey, String topic) {
return String.format(
"https://api.nytimes.com/svc/topstories/v2/%s.json?api-key=%s",
topic, apiKey);
}
#Override
public int getCount() {
return topics.length; // Assuming each fragment goes to NyTimes
}
#Override
public Fragment getItem(int position) {
final String url = getURL(topics[position], API_KEY);
// Call the other constructor
return new NyTimesFragment(url);
} // done... no if statements.
Something to consider to make this somewhat better would be Retrofit + Gson...
Ok so the issue here is I was using the same loader id in initloader for each fragment & this is why the same data was being loaded. The loader id needs to be unique for each fragment for this to work.
Help. I don't know why my RecyclerView does not show anything. My implementation of the adapter is right. I don't know where have I gone wrong.
Here's the Fragment class:
public class RemittanceFragment extends Fragment implements View.OnClickListener {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
#BindView(R.id.remit_cancel_view)
View remitCancelView;
#BindView(R.id.remit_checkpaid_view)
View remitCheckPaidView;
#BindView(R.id.remit_create_view)
View remitCreateView;
#BindView(R.id.remit_main_menu)
View remitMainMenuView;
#BindView(R.id.btn_cancel)
Button btnCancel;
#BindView(R.id.btn_checkpaid)
Button btnCheckPaid;
#BindView(R.id.btn_create)
Button btnCreate;
#BindView(R.id.btn_back)
TextView btnGoBack;
#BindView(R.id.btn_back2)
TextView btnGoBack2;
#BindView(R.id.remit_header_title)
TextView tvRemitHeaderTitle;
#BindView(R.id.remit_cancel_list)
RecyclerView cancelRecyclerView;
public RemittanceFragment() {
// Required empty public constructor
}
public static RemittanceFragment newInstance() {
RemittanceFragment fragment = new RemittanceFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_remit_menu, container, false);
ButterKnife.bind(this, view);
remitCancelView.setVisibility(View.GONE);
remitCheckPaidView.setVisibility(View.GONE);
remitCreateView.setVisibility(View.GONE);
btnCancel.setOnClickListener(this);
btnCreate.setOnClickListener(this);
btnCheckPaid.setOnClickListener(this);
btnGoBack.setOnClickListener(this);
btnGoBack2.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
remitMainMenuView.setVisibility(View.GONE);
switch (v.getId()) {
case R.id.btn_cancel:
remitCancelView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CANCEL\nREMITTANCE");
populateData();
break;
case R.id.btn_checkpaid:
remitCheckPaidView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CHECK / PAID\nREMITTANCE");
break;
case R.id.btn_create:
remitCreateView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CREATE\nREMITTANCE");
break;
case R.id.btn_back:
case R.id.btn_back2:
remitMainMenuView.setVisibility(View.VISIBLE);
remitCancelView.setVisibility(View.GONE);
remitCheckPaidView.setVisibility(View.GONE);
remitCreateView.setVisibility(View.GONE);
tvRemitHeaderTitle.setText("REMITTANCE");
break;
default:
break;
}
}
public void populateData() {
List<RemitTransaction> transactions = new ArrayList<>();
transactions = RemitTransaction.createRemitTransactionList();
RemitTransactionListAdapter adapter = new RemitTransactionListAdapter
(transactions, getActivity());
cancelRecyclerView.setAdapter(adapter);
cancelRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
public static class RemitTransaction {
private String mRefno;
private String mDate;
private String mMsisdn;
private String mAmount;
public RemitTransaction(String refno, String date, String msisdn, String amount) {
mRefno = refno;
mDate = date;
mMsisdn = msisdn;
mAmount = amount;
}
public String getmRefno() {
return mRefno;
}
public String getmDate() {
return mDate;
}
public String getmMsisdn() {
return mMsisdn;
}
public String getmAmount() {
return mAmount;
}
public static ArrayList<RemitTransaction> createRemitTransactionList() {
ArrayList<RemitTransaction> transactions = new ArrayList<>();
for (int n = 0; n < 4; n++) {
transactions.add(n, new RemitTransaction(
"REF01253123" + n,
"July " + n + ", 2016",
"0920987654" + n,
"100" + n));
}
return transactions;
}
}
public class RemitTransactionListAdapter
extends RecyclerView.Adapter<RemitTransactionListAdapter.CancelVH>{
private List<RemitTransaction> mList;
private Context mContext;
public RemitTransactionListAdapter(List<RemitTransaction> list, Context context) {
mList = list;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public CancelVH onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = getContext();
View v = LayoutInflater.from(context).inflate(R.layout.remit_cancel_list_item, parent, false);
return new CancelVH(v);
}
#Override
public void onBindViewHolder(CancelVH holder, int position) {
RemitTransaction transaction = mList.get(position);
holder.cancelRefno.setText(transaction.getmRefno());
holder.cancelAmount.setText(transaction.getmAmount());
holder.cancelDate.setText(transaction.getmDate());
holder.cancelMsisdn.setText(transaction.getmMsisdn());
}
#Override
public int getItemCount() {
return mList.size();
}
public class CancelVH extends RecyclerView.ViewHolder {
#BindView(R.id.remit_item_refno) TextView cancelRefno;
#BindView(R.id.remit_item_amount) TextView cancelAmount;
#BindView(R.id.remit_item_date) TextView cancelDate;
#BindView(R.id.remit_item_msisdn) TextView cancelMsisdn;
public CancelVH(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
}
And here's the layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/utility_white"
android:paddingTop="#dimen/dimen_margin_vertical_extra_large">
<android.support.v7.widget.RecyclerView
android:id="#+id/remit_cancel_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
And here's the list_item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/remit_item_refno"
style="#style/RemitListItem"
android:text="VW832191"
android:textStyle="bold"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/remit_item_amount"
style="#style/RemitListItem"
android:text="100.00"
android:textStyle="bold"
android:layout_alignParentEnd="true"/>
<TextView
android:id="#+id/remit_item_date"
style="#style/RemitListItem"
android:text="2016-07-20"
android:layout_alignParentStart="true"
android:layout_below="#+id/remit_item_refno"/>
<TextView
android:id="#+id/remit_item_msisdn"
style="#style/RemitListItem"
android:text="09273450686"
android:layout_alignParentEnd="true"
android:layout_below="#+id/remit_item_amount"/>
</RelativeLayout>
Hope you can all help me. Thank you!
in previous versions of support library 23.2.0 wrap_content not work for RecyclerView ,and with support library 23.2.0 and above wrap_content work perfectly (now latest version is 24.0.0),
i guess that is your problem.
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>
I know this question is asked several times here, and i go through all the answer and tried implementing it in my code, but the result is fail. That's why i have posted a new question to get my code run. Question is simple whenever i want to trigger listView.setOnItemClickListener(this). It is not fired. I tried each suggestion given in stackoverflow but not able to solve the issue.
Code i used are
visitor_list_fragment.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/node_name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:textIsSelectable="false"
android:textSize="20sp" />
<ListView
android:id="#+id/visitor_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:cacheColorHint="#00000000"
android:dividerHeight="5dp"
android:listSelector="#00000000"
android:scrollingCache="true"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
visitor_list_item.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/photo_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:contentDescription="#string/image_name"
android:focusable="false" />
<TextView
android:id="#+id/profile_info_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:focusable="false"
android:textColor="#android:color/black"
android:textIsSelectable="false"
android:textSize="20sp" />
</LinearLayout>
Code where i called onItemClickListener
public class VisitorListFragment extends Fragment implements OnItemClickListener
{
private TextView m_NodeName;
private ListView m_VisitorListView;
private VisitorListAdapter m_VisitorNodeListAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.visitor_list_fragment, null);
m_NodeName = (TextView)view.findViewById(R.id.node_name_textView);
m_VisitorNodeListAdapter = new VisitorListAdapter(getActivity().getApplicationContext());
m_VisitorListView = (ListView)view.findViewById(R.id.visitor_list_view);
// Displaying header & footer in the list-view
TextView header = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
header.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addHeaderView(header, null, false);
TextView footer = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
footer.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addFooterView(footer, null, false);
m_VisitorListView.setAdapter(m_VisitorNodeListAdapter);
m_VisitorListView.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String nodeName = m_VisitorNodeListAdapter.getNodeName(position);
System.out.println(nodeName);
}
}
AdapterClass
public class VisitorListAdapter extends BaseAdapter
{
private HashMap<String, String> m_ProfileImagePath;
private HashMap<String, String> m_ProfileInfo;
private ArrayList<String> m_NodeName;
private LayoutInflater m_Inflater=null;
public VisitorListAdapter(Context context)
{
super();
m_ProfileImagePath = new HashMap<String, String>();
m_ProfileInfo = new HashMap<String, String>();
m_NodeName = new ArrayList<String>();
m_Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public Object getItem(int arg0)
{
return null;
}
public int getCount()
{
return m_NodeName.size();
}
public long getItemId(int position)
{
return position;
}
public boolean isEnabled(int position)
{
return false;
}
public String getNodeName(int position)
{
return m_NodeName.get(position);
}
public class ViewHolder
{
TextView profileInfoTextView;
ImageView profileImageView;
}
public void addProfileInfo(String nodeName, String profileInfo)
{
boolean found = false;
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
found = true;
}
}
if(found == false)
{
m_NodeName.add(nodeName);
m_ProfileInfo.put(nodeName, profileInfo);
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
}
public void addProfileImagePath(String nodeName, String profileInfoImagePath)
{
m_ProfileImagePath.put(nodeName, Utilities.CHORD_FILE_PATH + "/" + profileInfoImagePath);
notifyDataSetChanged();
}
public void removeNode(String nodeName)
{
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
m_NodeName.remove(i);
m_ProfileInfo.remove(nodeName);
m_ProfileImagePath.remove(nodeName);
}
}
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public void clearAll()
{
m_ProfileImagePath.clear();
m_NodeName.clear();
m_ProfileInfo.clear();
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = m_Inflater.inflate(R.layout.visitor_list_item, null);
holder.profileImageView = (ImageView)convertView.findViewById(R.id.photo_view);
holder.profileInfoTextView = (TextView)convertView.findViewById(R.id.profile_info_textview);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
// Put the code in an async task
new ImageLoaderTask(position, holder).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return convertView;
}
class ImageLoaderTask extends AsyncTask<URL, Integer, Long>
{
private int position;
private ViewHolder holder;
ImageLoaderTask(int position, ViewHolder holder)
{
this.position = position;
this.holder = holder;
}
#Override
protected void onPreExecute()
{
String loadPath = m_ProfileImagePath.get(m_NodeName.get(position));
Bitmap bitmap = BitmapFactory.decodeFile(loadPath);
if(bitmap != null)
{
holder.profileImageView.setImageBitmap(bitmap);
}
holder.profileInfoTextView.setText(m_ProfileInfo.get(m_NodeName.get(position)));
}
#Override
protected Long doInBackground(URL... urls)
{
return null;
}
#Override
protected void onProgressUpdate(Integer... progress)
{
}
#Override
protected void onPostExecute(Long result)
{
}
}
}
public boolean isEnabled(int position)
{
return false;
}
This should be true for all active elements!
Try removing
android:focusable="false" and
android:textIsSelectable="false"
from listView_item.xml file...
Check if your m_VisitorListView isn't null (debugging mode).
Check the import onItemClick, should be AdapterView.OnItemClickListener
If you still facing this issue try implementing it anonymously:
m_VisitorListView .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
} );