pass date from Activity to tab frgament - android

hi friends i am trying to pass array data from activity to the tab fragment but its gives me the null pointer exception i am using the json to store data into getter and setter method and trying to pass that list into the frgament method
Display.class
public static void toast(Context context, String display) { Toast.makeText(context, display, Toast.LENGTH_LONG).show(); }
MyError
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
Here is my main activity
public class HotelDetails extends AppCompatActivity {
#BindView(R.id.hoteldetailedtoolbar)
Toolbar hoteldetailedtoolbar;
#BindView(R.id.hotelamentiestab)
TabLayout hotelamentiestab;
#BindView(R.id.hotelpager)
ViewPager hotelpager;
ArrayList<Hotel_image> hotelimg = new ArrayList<Hotel_image>();
#BindView(R.id.hotelname)
TextView hotelname;
#BindView(R.id.hotelprice)
TextView hotelprice;
#BindView(R.id.roomtype)
TextView roomtype;
#BindView(R.id.whatsmakes)
TextView whatsmakes;
#BindView(R.id.needtoknow)
TextView needtoknow;
HotelImages hoteladapter;
#BindView(R.id.indicator)
InkPageIndicator indicator;
#BindView(R.id.bannerpager)
ViewPager bannerpager;
#BindView(R.id.roomtypes)
Spinner roomtypes;
List<Hotel_TabBeans> listhotelbeans=new ArrayList<Hotel_TabBeans>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotel_detail);
ButterKnife.bind(this);
setSupportActionBar(hoteldetailedtoolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
hoteldetailedmethod();
setupviewpager(hotelpager);
hotelpager.setOffscreenPageLimit(1);
hotelamentiestab.setupWithViewPager(hotelpager);
hoteladapter = new HotelImages(getApplicationContext(), hotelimg);
bannerpager.setAdapter(hoteladapter);
ArrayList<String> roomlist = new ArrayList<>();
roomlist.add("Rooms Types");
roomlist.add("Standard");
roomlist.add("Deluxe");
roomlist.add("Luxury");
ArrayAdapter<String> roomadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_detailed, R.id.spinnertext, roomlist);
roomadapter.setDropDownViewResource(R.layout.spinner_dropdown);
roomtypes.setAdapter(roomadapter);
}
#OnClick(R.id.spinnerbutton)
public void spinnerbuttonclick() {
roomtypes.performClick();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.hoteldetailed_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.call:
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
return true;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "CYStay");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Here live url will come");
startActivity(Intent.createChooser(shareIntent,
"Share The Post"));
return true;
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupviewpager(ViewPager pager) {
TabsFragments tabsFragments = new TabsFragments(getSupportFragmentManager());
tabsFragments.addfragment(new Hotel_tab(), "Hotel");
tabsFragments.addfragment(new Hotel_tab(), "Room");
pager.setAdapter(tabsFragments);
}
private void hoteldetailedmethod() {
Display.showLoadingDialog(HotelDetails.this, "Loading...");
final String hoteldetaildurl = Jsonurl.url + "hotel_details.php?rid=" + getIntent().getStringExtra("Roomid");
Display.log(hoteldetaildurl);
JsonObjectRequest hoteldetailedreq = new JsonObjectRequest(Request.Method.GET, hoteldetaildurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray hotelimagesarray = response.getJSONArray("hotel_images");
for (int i = 0; i < hotelimagesarray.length(); i++) {
JSONObject hotelimagearrayobj = hotelimagesarray.getJSONObject(i);
Hotel_image hotelimage = new Hotel_image();
hotelimage.setHotelimages(hotelimagearrayobj.getString("image"));
hotelimg.add(hotelimage);
}
int number = bannerpager.getChildCount();
if (number != -1) {
indicator.setViewPager(bannerpager);
}
JSONObject hoteldtails = response.getJSONObject("hotel_details");
getSupportActionBar().setTitle(hoteldtails.getString("hotel_name"));
hotelname.setText(hoteldtails.getString("hotel_name"));
hotelprice.setText(hoteldtails.getString("room_price"));
roomtype.setText(hoteldtails.getString("room_name"));
whatsmakes.setText(hoteldtails.getString("what_makes_special"));
needtoknow.setText(hoteldtails.getString("need_to_know"));
JSONArray ammarray=hoteldtails.getJSONArray("amenities");
for (int i = 0; i <ammarray.length() ; i++) {
JSONObject arrayobj=ammarray.getJSONObject(i);
Hotel_TabBeans tabeans=new Hotel_TabBeans();
tabeans.setAmenitimage(arrayobj.getString("img"));
tabeans.setAmenitiname(arrayobj.getString("name"));
listhotelbeans.add(tabeans);
Hotel_tab hotelTab=new Hotel_tab();
hotelTab.hoteltablist(listhotelbeans);
}
// hoteldatas.hoteldatamethod(listhotelbeans);
// Bundle listbundle=new Bundle();
// listbundle.putStringArrayList("hotelist",listhotelbeans);
// listbundle.putSerializable("hoye", (Serializable) listhotelbeans);
// Hotel_tab hoteltab=new Hotel_tab();
// hoteltab.setArguments(listbundle);
} catch (JSONException e) {
e.printStackTrace();
}
hoteladapter.notifyDataSetChanged();
Display.hideLoadingDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Display.log(error.toString());
Display.hideLoadingDialog();
}
});
hoteldetailedreq.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(hoteldetailedreq);
}
}
Here is my fragment activity:
public class Hotel_tab extends Fragment {
public Hotel_tab() {
}
#BindView(R.id.hotel_tab_list)
RecyclerView hotel_tab_list;
Hotel_Tab_Layout hotel_tab_layout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.hotel_tab,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this,view);
LinearLayoutManager hotelmanager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
hotel_tab_list.setLayoutManager(hotelmanager);
}
public void hoteltablist(List<Hotel_TabBeans> msg){
Display.toast(getActivity(),msg);//here is the null pointer exeception i am getting
}
}

The problem is clear:
You would like to get the Context without attaching a Fragment to the activity.
Inside parsing a successful response from a server, you code look like:
Hotel_tab hotelTab=new Hotel_tab();
hotelTab.hoteltablist(listhotelbeans);
That means, that you're creating a new Fragment and invoke a method getActivity() on a fragment that is not attached to it.
You have 3 choices:
If you just want to show toast, show it inside Activity, not inside Fragment.
If you really need to do this inside Framgent, attach it first to the activity with FragmentManager
Or pass Context as one of Fragment's function hoteltablist(...) parameters, if you want to show toast inside fragment.

Related

Bundle from main activity to fragment

i m following some guide to pass parameter from login to one fragment.
I have this structure (login page, user area (main activity that cointain only a fragment and some fragment)
I try to do this :
public class UserAreaActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener{
ProgressDialog progressDialog;
#Override
public void onBackPressed() {
//super.onBackPressed();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.anto.fitfix.R.layout.activity_user_area);
Bundle b = getIntent().getExtras();
final String name = b.getString("name");
final String user = b.getString("id");
final String email = b.getString("email");
final String gender = b.getString("gender");
final String photourl= b.getString("photo");
final String birthday = b.getString("birthday");
final String p="null";
Log.d("nome",""+name);
// loadFragment(new fragment_home());
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_home()).commit();
BottomNavigationView navigation = findViewById(R.id.navigationView);
navigation.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fragment_home fragment = null;
switch (item.getItemId()) {
case R.id.action_home:
fragment = new fragment_home();
break;
case R.id.action_cron:
fragment = new fragment_home();
break;
case R.id.action_face:
// fragment = new NotificationsFragment();
break;
}
return loadFragment(fragment);
}
private boolean loadFragment(android.support.v4.app.Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
and this for fragment
public class fragment_home extends Fragment {
ProgressDialog progressDialog;
String name,email,user,p;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
View view = inflater.inflate(R.layout.fragment_home, container, false);
TextView tResult = (TextView) view.findViewById(R.id.tResult);
TextView tMail = (TextView) view.findViewById(com.example.anto.fitfix.R.id.tMail);
TextView tAge = (TextView) view.findViewById(R.id.tAge);
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt("name");
Log.d("name",""+myInt);
tResult.setText(name);
}
BLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("wait..."); // Setting Message
progressDialog.setTitle("Logout"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
disconnectFromFacebook();
Thread.sleep(1600);
Intent fbIntent = new Intent(getActivity(), LoginActivity.class);
getActivity().startActivity(fbIntent);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
}
});
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
} catch (JSONException e) {
e.printStackTrace();
}
}
};
/* FbActivity registerRequest = new FbActivity(name, user, p, email, responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(registerRequest);*/
return view;
}
}
I recived the name from login , but i cant pass in fragment section..
Someone can give me the suggestion?
When you pass a bundle to fragment, you do not create an object of Fragment class, but instead you create the object of the fragment you created i.e fragment_home
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new fragment_home()).commit();
Change the above code with the code below
fragment_home fragment = new fragment_home();
Bundle bundle = new Bundle();
bundle.putInt("name", 123);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();

RecyclerView.Adapter is null in ViewPager Fragment

public class MainLibraryFragment extends Fragment implements PlaylistChangedInterface {
AudioItemSelectedListener mCallback;
// Container Activity must implement this interface
public interface AudioItemSelectedListener {
// public void onAudioItemSelected(int position);
public void onAudioItemSelected(Audio audioSelected);
}
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private Context context;
private ArrayList<Audio> listToDisplay;
private String TAG = "MainLibraryFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = getActivity();
MemoryManagement memoryManagement = new MemoryManagement(context);
listToDisplay = memoryManagement.loadAudioList(MemoryManagement.MAIN_LIST_KEY);
try {
//Expression is meaningless but tests if null.
//TODO, should catch this in loadAudioList.
if (listToDisplay.isEmpty()){}
} catch (NullPointerException e){
defaultList();
}
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutCompat.VERTICAL));
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addOnItemTouchListener(new CustomTouchListener(context, new onItemClickListener() {
#Override
public void onClick(View view, int index) {
mCallback.onAudioItemSelected(listToDisplay.get(index));
}
}));
mAdapter = new SongListAdapter2(listToDisplay, context);
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
private void defaultList(){
listToDisplay = new ArrayList<>();
listToDisplay.add(new Audio("You need to add some songs!"));
}
#Override
public void playListChanged(ArrayList<Audio> arrayList) {
Log.d(TAG, "updateTop: in.");
if (!arrayList.isEmpty()) {
listToDisplay = arrayList;
}else {
defaultList();
}
updateListView();
Log.d(TAG, "updateTop: out.");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = getContext();
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (AudioItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement AudioItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallback = null;
}
private void updateListView(){
Log.d(TAG, "updateTop: in.");
((SongListAdapter2) mAdapter).refreshList(listToDisplay);
Log.d(TAG, "updateTop: out.");
}
}
I have added refreshList():
public void refreshList(ArrayList<Audio> list) {
this.list = list;
notifyDataSetChanged();
}
And then the error message:
--------- beginning of crash
06-09 15:14:24.275 9114-9114/com.bteq.audia E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.bteq.audia, PID: 9114
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.bteq.audia.SongListAdapter2.refreshList(java.util.ArrayList)' on a null object reference
at com.bteq.audia.MainLibraryFragment.updateListView(MainLibraryFragment.java:128)
at com.bteq.audia.MainLibraryFragment.playListChanged(MainLibraryFragment.java:100)
at com.bteq.audia.MainActivity.onDialogPositiveClick(MainActivity.java:195)
at com.bteq.audia.AddSongDialog$2.onClick(AddSongDialog.java:47)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6753)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:482)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
06-09 15:14:24.281 9114-9114/com.bteq.audia W/OPDiagnose:
getService:OPDiagnoseService NULL
The MainActivity that contains the Pager. I tried to remove as much code as I could that wasn't relevant.
public class MainActivity extends AppCompatActivity implements MainLibraryFragment.AudioItemSelectedListener, AddSongDialog.NoticeDialogListener, ShowQueueDialog.ShouldClearAll {
private MemoryManagement memoryManagement;
private ViewPager viewPager;
private com.bteq.audia.PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
memoryManagement = new MemoryManagement(this);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
initialiseViews();
}
public void initialiseViews() {
//Fills the titles of all the tabs.
String[] tabTitles = getTabTitles();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
for (int i = 0; i < tabTitles.length; i++) {
tabLayout.addTab(tabLayout.newTab().setText(tabTitles[i]));
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Sets up the ViewPager and creates the functionality to make them changeable.
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
setupBottomView();
}
//method used as main control to the service from this activity.
private void audioActionDo(String audioAction) {
Intent intent = new Intent("audio_control_intent");
intent.putExtra("button_pressed", audioAction);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
/*
Method tells the activity which item in the shown playlist has been selected. This should then cause that item to play if possible.
//TODO, fill in body of method.
*/
#Override
public void onAudioItemSelected(Audio audio) {
songSelected(audio);
Log.d("MainActivity", "onAudioItemSelected: At end");
}
#Override
public void onDialogPositiveClick(String titleString, String artistString, String albumString, String genreString) {
Audio audioToAdd = new Audio(genreString, titleString, albumString, artistString);
memoryManagement.addAudioToList(audioToAdd, MemoryManagement.MAIN_LIST_KEY);
Fragment fragment = adapter.getItem(0);
PlaylistChangedInterface playlistChangedInterface = (PlaylistChangedInterface) fragment;
playlistChangedInterface.playListChanged(memoryManagement.loadAudioList(MemoryManagement.MAIN_LIST_KEY));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_top, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
//TODO, take the user to the app settings page.
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_favorite:
//TODO, make this favourite the current Audio.
// User chose the "Favorite" action, mark the current item
// as a favorite...
memoryManagement.clearPrefsValue(MemoryManagement.MAIN_LIST_KEY);
return true;
case R.id.action_add_new_song:
showAddSongDialog();
return true;
case R.id.action_show_queue:
showQueueDialog();
return true;
case R.id.action_add_from_internal:
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
public void showAddSongDialog() {
DialogFragment newFragment = new AddSongDialog();
newFragment.show(getSupportFragmentManager(), "missiles");
}
public void showQueueDialog() {
DialogFragment newFragment = new ShowQueueDialog();
newFragment.show(getSupportFragmentManager(), "showQueue");
}
//Should immediately play a song then be able to continue with the queued audio.
public void songSelected(Audio audioToAdd) {
}
//clears the entire queue but completes playback of current audio.
private void clearCurrentQueue() {
memoryManagement.clearPrefsValue(MemoryManagement.QUEUE_KEY);
}
// Utility method. Returns the locale titles for the tabs in the viewpager.
private String[] getTabTitles() {
return getResources().getStringArray(R.array.tab_titles);
}
#Override
public void clearAllPressed() {
clearCurrentQueue();
}
private void setupBottomView() {
ImageView playButton = (ImageView) findViewById(R.id.bottom_play);
ImageView replayButton = (ImageView) findViewById(R.id.bottom_replay);
ImageView skipBackButton = (ImageView) findViewById(R.id.bottom_skip_back);
ImageView skipForwardButton = (ImageView) findViewById(R.id.bottom_skip_next);
ImageView shuffleButton = (ImageView) findViewById(R.id.bottom_shuffle);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// playAudio(storageUtility2.loadAudioIndex());
audioActionDo(getResources().getString(R.string.broadcast_action_playpause));
}
});
replayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
audioActionDo(getResources().getString(R.string.broadcast_action_loop));
}
});
skipBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
audioActionDo(getResources().getString(R.string.broadcast_action_skip_back));
}
});
skipForwardButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
audioActionDo(getResources().getString(R.string.broadcast_action_skip_forward));
}
});
shuffleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
audioActionDo(getResources().getString(R.string.broadcast_action_shuffle));
}
});
}
}
I get a null pointer exception whenever the method updateListView is called. The fragment initially displays with no problem, but when a new entry is added to the ArrayList and the updateListView is called - it stops. The log shows that mAdapter is null. I don't know enough about android yet to understand why mAdapter becomes null after it is used before.
Sorry for large amount of code but I'm completely stumped. Thanks.
In my opinion this is because your variable mAdapter is declared as of type RecyclerView.Adapter which is an interface which does not declare your method, refreshList(). Therefore if you intend to use the type RecyclerView.Adapter, only the methods declared in the interface could be called by using the reference variable. If you intend to call methods implemented by yourself other than whats overridden from the interface, the reference type SongListAdapter2 has to be used.
Simple fix is to change the RecyclerView.Adapter to SongListAdapter2 at the declaration of the mAdapter.
Ps. Check android docs to see the methods declared by the RecyclerView.Adapter.
It depends on how you are accessing the adapter in the RecyclerView. If you look at this line Fragment fragment = adapter.getItem(0), you are trying to access the first fragment in your ViewPager's adapter. getItem usually won't get called again after the ViewPager has layout its fragments which means your call to access the RecyclerView's adapter in the first fragment in the ViewPager will be pointing to a null adapter even though the fragment might exist (and you might even be calling a wrong fragment). Use this Fragment fragment = getChildFragmentManager().getFragments().get(0) to access the right fragment which will ensure the RecyclerView adapter won't be null. Change getChildFragmentManager() to getFragmentManager() if your ViewPager is in an Activity.

How to open link in a fragment with webview when a specific item is clicked from listview fragment

I have an Android app with a navigation drawer with menu items.This menu contains entry to multiple fragments. One of the fragments has a listview in it with names of websites. My aim is that whenever a name of website is clicked from that list the link associated with the listview item saved in stringarray in strings.xml file is opened in new fragment with webview which opens the site.
So far I have implemented this code for the fragment with listview
class AtlasListFragment extends android.support.v4.app.ListFragment implements AdapterView.OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.atlas_list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tut_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}}
And the code which launches the fragment from navigation drawer is below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.Fragment fragment = null;
if (id == R.id.home) {
fragment = frag;
else if (id == R.id.settings) {
fragment=new Settings();
} else if (id == R.id.about_us) {
fragment=new AboutUc();
}
else if(id == R.id.atlas){
fragment = new AtlasListFragment();
}
else{
}
if (fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.fragmentview,fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
By this mehod you can open a webview in where you want use WebView layout and use this method in your activity
public void openWebView(String url){
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Hope it works for you
First of all you will need broadcast so you can send your clicked
URL from adapter to your fragment, and in your main fragment when you
receive the url you can use intent or webview
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.hossam";
private static final String UPDATE_LOCATION_METHOD = "updateLocation";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
String url_adapter = arg1.getStringExtra("url_adapter");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url_adapter));
startActivity(i);
break;
default:
break;
}
}
}
}
i hope this helped

Fragment button causes backstack error

I am trying to create an app that will get some information from a server, using volley. You should enter your info in, and then click login at the bottom, but for somereason it keeps crashing.
First and foremost when the button is clicked, it crashes and the logcat is:
https://pastebin.com/deQi874r
Main Activity code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
TextView textView = (TextView)findViewById(R.id.currentFragDisplay);
textView.setText("My Profile");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmentContainer, new Personal_Profile_Fragment());
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.toolbar_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int item_id = item.getItemId();
switch (item_id) {
case R.id.accDetails:
swapFragment(item_id);
return true;
case R.id.personalProfileLookup:
swapFragment(item_id);
return true;
case R.id.favoriteCharacters:
swapFragment(item_id);
return true;
case R.id.friendProfileLookup:
swapFragment(item_id);
return true;
case R.id.tipsAndTricks:
swapFragment(item_id);
return true;
}
return false;
}
private void swapFragment(int fragmentID){
TextView tracker = (TextView) findViewById(R.id.currentFragDisplay);
Fragment fragment = null;
if(fragmentID == R.id.personalProfileLookup) {
tracker.setText("My Profile");
fragment = new Personal_Profile_Fragment();
} else if(fragmentID == R.id.favoriteCharacters) {
tracker.setText("Favorite Characters");
fragment = new Favorite_Characters_Fragment();
} else if(fragmentID == R.id.friendProfileLookup) {
tracker.setText("Friend Lookup");
fragment = new Friend_Profile_Fragment();
} else if(fragmentID == R.id.tipsAndTricks) {
tracker.setText("Tips and Tricks");
fragment = new TipsandTricks_Fragment();
} else if(fragmentID == R.id.accDetails) {
tracker.setText("Log In");
fragment = new loginFragment();
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
login fragment(where button is):
public class loginFragment extends Fragment {
//Local Vars
private boolean loginCheck = false;
//required constructor
public loginFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
login(v);
}
});
// Inflate the layout for this fragment
return view;
}
public boolean isLoggedIn() {
return loginCheck;
}
private void login(View v){
Toast.makeText(getActivity(),"Clicked",Toast.LENGTH_LONG).show();
String username;
String password;
username = v.findViewById(R.id.enteredUsername).toString();
password = v.findViewById(R.id.enteredPassword).toString();
final ArrayList<String> info = new ArrayList<>();
String[] unameSeparated = new String[username.length()];
unameSeparated = username.split("(?!^)");
String startUrl = "https://us.api.battle.net/d3/profile/";
String uname = "";
String APIKey = "/?locale=en_US&apikey=6nguxckrzchn86q9792jvdhww4uxf32v";
//Separating the username into the parts needed for sending request
for (int i = 0; i < unameSeparated.length; i++) {
if ((unameSeparated[i].equals("#"))) {
//Replacing # with '%23'
uname += "%23";
} else {
uname += unameSeparated[i];
}
}
String url = startUrl + uname+ APIKey;
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
info.add(response);
Toast.makeText(getActivity(),"Request Success",Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Request FAIL",Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
}
The problem is with you login click. You are passing the button and not the view in
login(v);
The V you are passing is an instance of the button not the view. So this
username = v.findViewById(R.id.enteredUsername).toString();
password = v.findViewById(R.id.enteredPassword).toString();
would be refering to a null pointer. Hope this helps

How to send data From activity to Fragment Activity?

I have referred many code on this question , but can not get any help for my problem.
This is My code from where I want to send data to previous FragmentActivity:
public class AddTask extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_task);
ImageButton position = (ImageButton) findViewById(R.id.select_position);
position.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent m = new Intent().setClass(getApplicationContext(),
MapActivity.class);
startActivity(m);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_add_task, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.accept:
FinishActivity();
finish();
break;
case R.id.cancle:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
protected void FinishActivity() {
EditText activity = (EditText) findViewById(R.id.activity_name);
EditText description = (EditText) findViewById(R.id.description);
EditText address = (EditText) findViewById(R.id.address);
Bundle bundle = new Bundle();
bundle.putString("activity", activity.getText().toString());
if (activity.toString().isEmpty() || description.toString().isEmpty()
|| address.toString().isEmpty()) {
Toast.makeText(this, "Field must not be empty", Toast.LENGTH_LONG)
.show();
}
}
}
Can anyone tell me What to use in this code to send data, I have used Fragment class to send it but it make error in Activity.
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}

Categories

Resources