Swipe to refresh webview fragment doesnt load url - java

I have a webview fragment in my MainActivity. I am trying to add Swipetoview inside it. But when I load the fragment it doesn't load the url.
My fragment:
// Inflate the layout for this fragment
View vDriver=inflater.inflate(R.layout.fragment_drivers, container, false);
mWebView = vDriver.findViewById(R.id.drivers_webview);
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
// Enable Javascript
//WebSettings webSettings = mWebView.getSettings();
//webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
swipeLayout = vDriver.findViewById(R.id.fragment_drivers);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
});
return vDriver;
My fragment layout:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_drivers"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Drivers">
<WebView
android:id="#+id/drivers_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
I tried different things and this is the last code I tried. What am I doing wrong?
Thanks for your time in advance.
EDIT: MainActivity
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, HomeFragment.OnFragmentNavListener,Drivers.OnDriverNavigationListener {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 0 ;
private SignInButton btn_signin;
private TextView nameText;
private TextView emailText;
private ImageView imgProfilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment fragment = new HomeFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navHeader1 = navigationView.getHeaderView(0);
btn_signin = navHeader1.findViewById(R.id.signin_btn);
View navHeader3 = navigationView.getHeaderView(0);
nameText = navHeader3.findViewById(R.id.name);
View navHeader4 = navigationView.getHeaderView(0);
emailText = navHeader4.findViewById(R.id.email);
View navHeader5 = navigationView.getHeaderView(0);
imgProfilePic = navHeader5.findViewById(R.id.imgProfilePic);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
btn_signin.setVisibility(View.GONE);
if(user.getDisplayName() != null) {
nameText.setText(user.getDisplayName());
nameText.setVisibility(View.VISIBLE);
}
emailText.setText(user.getEmail());
emailText.setVisibility(View.VISIBLE);
imgProfilePic.setVisibility(View.VISIBLE);
Picasso.get().load(user.getPhotoUrl())
.into(imgProfilePic);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(false);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(true);
}
else {
nameText.setVisibility(View.GONE);
emailText.setVisibility(View.GONE);
btn_signin.setVisibility(View.VISIBLE);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(true);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(false);
imgProfilePic.setVisibility(View.GONE);
}
}
};
btn_signin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn () {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// deneme
}
}
}
#Override
public void onStop() {
super.onStop();
if(mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
signIn();
} else if (id == R.id.nav_send2) {
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Toast.makeText(getApplicationContext(), "Çıkış yaptınız.", Toast.LENGTH_SHORT).show();
}
});
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentNav(int position) {
Fragment navFragment = null;
switch (position) {
case 0:
navFragment = new HomeFragment();
break;
case 1:
navFragment = new Drivers();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, navFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onDriverNavigation(int asd) {
}
}
HomeFragment.java
package com.ahmetbarpa.grandprix;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class HomeFragment extends Fragment {
private OnFragmentNavListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v1 =inflater.inflate(R.layout.fragment_home, container, false);
Button profile= v1.findViewById(R.id.button1);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
onButtonSelected(1);
}
});
Button education= v1.findViewById(R.id.button2);
education.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Takımlar ve arabalar",Toast.LENGTH_SHORT).show();
}
});
Button health= v1.findViewById(R.id.button3);
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Pistler",Toast.LENGTH_SHORT).show();
}
});
Button goals= v1.findViewById(R.id.button4);
goals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Sıralama",Toast.LENGTH_SHORT).show();
}
});
Button finance= v1.findViewById(R.id.button5);
finance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Grand Prix Tarihi",Toast.LENGTH_SHORT).show();
}
});
Button comfort= v1.findViewById(R.id.button6);
comfort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"GP kart oyunu",Toast.LENGTH_SHORT).show();
}
});
return v1;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonSelected(int position) {
if (mListener != null) {
mListener.onFragmentNav(position);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentNavListener) {
mListener = (OnFragmentNavListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentNav");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentNavListener {
void onFragmentNav(int position);
}
}

Instead of reload()
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
Try it..
If this is not the way you want, the second method is:
make a new class as:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
then, Instead of this:
mWebView.setWebViewClient(new WebViewClient());
write this:
mWebView.setWebViewClient(new MyBrowser());
Hopefully your problem will be solved

Related

How to pass data between fragments in FragmentPagerAdapter

For my academic project, I want create an application with 4 tabs. The first one will show recent games added to a list, the second one will be a search form, the third will show the search result, and the last one will show the details. I currently have created the code for TabView and the 4 tabs. The problem is that I want to perform a search to get the items I have in a list which meet the search criteria on fragment 2, but I don't know how to pass the data from fragment 2 (textView data and spinner) to fragment 3. My code is the following:
MainActivity.java:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_search_white_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//TabLayout function call
configureTabLayout();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
return true;
case R.id.menu_settings:
Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Tab Layout function declaration
private void configureTabLayout() {
//Getting the tab layout
TabLayout tabLayout = findViewById(R.id.tab_layout);
//Adding Tabs
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));
//The TabPagerAdapter instance is then
//assigned as the adapter for the ViewPager and the TabLayout component added
//to the page change listener
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Finally, the onTabSelectedListener is configured on the TabLayout instance and
//the onTabSelected() method implemented to set the current page on the
//ViewPager based on the currently selected tab number.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(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) {
}
});
}
}
TabPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeScreenFragment();
case 1:
return new SearchFormFragment();
case 2:
return new SearchResultsFragment();
case 3:
return new DetailsScreenFragment();
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
SearchFormFragment.java
package gr.pliroforiki_edu.videogamedb;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchFormFragment extends Fragment {
private Button searchButton;
private EditText gameTitleEditText;
Spinner spinnerGenre;
public SearchFormFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);
searchButton = searchFormView.findViewById(R.id.searchButton);
gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);
spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
getActivity(),
R.array.game_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterGameTitle = gameTitleEditText.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);
Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();
}
});
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_search_form, container, false);
return searchFormView;
}
}
SearchResultsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);
return searchResultsView;
}
private void findViews()
{
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
I want to archive the following via the fragments:
ListActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ListActivity extends AppCompatActivity {
private TextView textViewInfo;
private ListView listViewBooks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// Animation when this Activity appears
overridePendingTransition(R.anim.pull_in_from_right, R.anim.hold);
// Get user filters from Intent
Intent intent = getIntent();
String filterAuthor = intent.getStringExtra("AUTHOR");
String filterTitle = intent.getStringExtra("TITLE");
int filterGenreId = intent.getIntExtra("GENREID", 0);
findViews();
// Show user filters for information
String message = String.format("Author: %s\nTitle: %s\nGenreId: %d",
filterAuthor, filterTitle, filterGenreId);
textViewInfo.setText(message);
DataStore.LoadBooks(filterAuthor, filterTitle, filterGenreId);
//Complex Object Binding
ListAdapter booksAdapter = new SimpleAdapter(
this,
DataStore.Books,
R.layout.list_item,
new String[]{DataStore.KEY_TITLE, DataStore.KEY_AUTHOR, DataStore.KEY_GENRENAME},
new int[]{R.id.book_item_title, R.id.book_item_author, R.id.book_item_genre}
);
listViewBooks.setAdapter(booksAdapter);
listViewBooks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent detailsIntent = new Intent(ListActivity.this, DetailsActivity.class);
detailsIntent.putExtra(DataStore.KEY_POSITION, position);
startActivity(detailsIntent);
}
});
}
#Override
protected void onPause(){
overridePendingTransition(R.anim.hold, R.anim.push_out_to_right);
super.onPause();
}
private void findViews(){
textViewInfo = findViewById(R.id.textViewInfo);
listViewBooks = findViewById(R.id.listViewBooks);
}
}
Mainactivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText textAuthor;
private EditText textTitle;
private EditText textGenre;
private Button buttonSearch;
private Spinner spinnerGenre;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataStore.Init(getApplicationContext());
textAuthor = findViewById(R.id.editTextAuthor);
textTitle= findViewById(R.id.editTextAuthor);
buttonSearch = findViewById(R.id.buttonSearch);
spinnerGenre = (Spinner) findViewById(R.id.spinnerGenre);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
this,
R.array.book_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterAuthor = textAuthor.getText().toString();
String filterTitle = textTitle.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("AUTHOR", filterAuthor);
intent.putExtra("TITLE", filterTitle);
intent.putExtra("GENREID", filterGenreId);
startActivity(intent);
}
});
}
}
Try this
pass value between two fragment using bundle
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeScreenFragment();
case 1:
return new SearchFormFragment();
case 2:
Fragment fragment = new SearchResultsFragment()
Bundle args = new Bundle();
args.putString("Key", "Value");
fragment.setArguments(args);
return fragment;
case 3:
return new DetailsScreenFragment();
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
in your onCreateView(....) of SearchResultsFragment
String value = getArguments().getString("Key");
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView =
inflater.inflate(R.layout.fragment_search_results, container, false);
String value = getArguments().getString("Key");
return searchResultsView;
}
private void findViews(){
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
hop its help you
There are many ways you can pass objects/values between fragments. In your case, the simplest solution would be to delegate those values to the holding Activity i.e MainActivity.
MainActivity:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//these will hold your values
String filterGameTitle;
int filterGenreId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_search_white_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//TabLayout function call
configureTabLayout();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
return true;
case R.id.menu_settings:
Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Tab Layout function declaration
private void configureTabLayout() {
//Getting the tab layout
TabLayout tabLayout = findViewById(R.id.tab_layout);
//Adding Tabs
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));
//The TabPagerAdapter instance is then
//assigned as the adapter for the ViewPager and the TabLayout component added
//to the page change listener
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Finally, the onTabSelectedListener is configured on the TabLayout instance and
//the onTabSelected() method implemented to set the current page on the
//ViewPager based on the currently selected tab number.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(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) {
}
});
}
}
SearchFormFragment:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchFormFragment extends Fragment {
private Button searchButton;
private EditText gameTitleEditText;
Spinner spinnerGenre;
public SearchFormFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);
searchButton = searchFormView.findViewById(R.id.searchButton);
gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);
spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
getActivity(),
R.array.game_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterGameTitle = gameTitleEditText.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
((MainActivity)getActivity()).filterGameTitle = filterGameTitle;
((MainActivity)getActivity()).filterGenreId = filterGenreId;
String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);
Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();
}
});
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_search_form, container, false);
return searchFormView;
}
}
SearchResultFragment:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
String filterGameTitle;
int filterGenreId;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context)
{
filterGameTitle = ((MainActivity)getActivity()).filterGameTitle;
filterGenreId = ((MainActivity)getActivity()).filterGenreId;
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);
return searchResultsView;
}
private void findViews()
{
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
You can use interface to send your search string to your activity from fragment 2, and from their you can call all methods in your fragment 3 as fragment3 object will be available to you in your activity, you can make performSearch() in your fragment3 and call it from your activity.
Alternatively you can use something like event bus to avoid the boiler plate code needed to setup interface.
Have a look at this event bus repo https://github.com/greenrobot/EventBus
Register event bus where you want the search string, in your case register the event bus in Fragment3 like this
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
In your Fragment 3 create a function like this
#Subscribe
public void onSearchEvent(String searchString){
//you will get your search string here
}
Now comeback to fragment2 from where you want to send the searchString, you have to put below code from where you want to send searchString, and this posted searchString will be received by fragment 3 in its onSearchEvent method
EventBus.getDefault().post(searchString);

Use CustomAdapter and OnItenClickListener. Listener is not responding

Here is my code.
I try to add OnItenClickListener to "lastCommand" listView but it is not responde. Any errors at compile.
package pl.globoox.sprawdzsprzedawce;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import pl.globoox.sprawdzsprzedawce.Utils.LastCommentHome;
import pl.globoox.sprawdzsprzedawce.Utils.QueryCheck;
import static pl.globoox.sprawdzsprzedawce.R.id.buttonCheckButton;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ListView lastComments;
LoginButton loginButton;
CallbackManager callbackManager;
ArrayList<String> comments_userList = new ArrayList();
ArrayList<String> comments_olxUserList = new ArrayList();
ArrayList<String> comments_dateList = new ArrayList();
ArrayList<String> comments_messageList = new ArrayList();
ArrayList<String> comments_statusList = new ArrayList();
ImageView imageViewFBUser;
TextView textViewFBName;
TextView textViewFBEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
initializeControls();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
loginWithFb();
// MENU DRAWER
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
textViewFBName = headerView.findViewById(R.id.textViewFBName);
textViewFBEmail = headerView.findViewById(R.id.textViewFBEmail);
imageViewFBUser = headerView.findViewById(R.id.imageViewFBUser);
imageViewFBUser.setVisibility(View.INVISIBLE);
textViewFBName.setText("");
textViewFBEmail.setText("");
// MAIN CONTENT APP
final SearchView editTextOfferLink = (SearchView) findViewById(R.id.editTextOfferLink);
final Button buttonCheck = (Button) findViewById(buttonCheckButton);
lastComments = (ListView) findViewById(R.id.listViewLastComments);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String offerLink = editTextOfferLink.getQuery().toString();
boolean error = false;
// CHECK FORM EMPTY
if (offerLink.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.formEmpty).setNegativeButton(R.string.tryAgain, null).create().show();
error = true;
return;
}
if (error == false) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
String userID = jsonResponse.getString("userID");
// CANT CONNECT TO DATABASE
if (errorCode == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.cantConnectToDatabase).setNegativeButton(R.string.tryAgain, null).create().show();
}
// USER NOT FOUND
else if (errorCode == 2) {
Boolean isBank = jsonResponse.getBoolean("isBank");
Intent i;
i = new Intent(getApplicationContext(), AddNewUserActivity.class);
if (isBank == true) {
i.putExtra("isBank", "true");
} else {
i.putExtra("isBank", "false");
}
String userName = jsonResponse.getString("userName");
String registerDate = jsonResponse.getString("registerDate");
i.putExtra("userID", userID);
i.putExtra("userName", userName);
i.putExtra("registerDate", registerDate);
finish();
startActivity(i);
}
// EMPTY OFFER VARIABLE
else if (errorCode == 3) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.omptyOfferVariable).setNegativeButton(R.string.tryAgain, null).create().show();
}
// BAD LINK
else if (errorCode == 4) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.badOfferLink).setNegativeButton(R.string.tryAgain, null).create().show();
}
// USER FOUND!
else if (errorCode == 5) {
Boolean isBank = jsonResponse.getBoolean("isBank");
Intent i;
i = new Intent(getApplicationContext(), UserAreaActivity.class);
i.putExtra("userID", userID);
i.putExtra("isBank", isBank.toString());
finish();
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
QueryCheck offerQueryRequest = new QueryCheck(offerLink, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(offerQueryRequest);
}
}
});
// LAST COMMENTS SHOW
Response.Listener<String> responseListenerLastComments = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
int count = jsonResponse.getInt("count");
Log.d("Tag", String.valueOf(errorCode));
JSONArray commentsArray = jsonResponse.getJSONArray("comments");
Log.d("TAG", String.valueOf(commentsArray));
for (int i = 0; i < count; i++) {
JSONObject jsonObject = commentsArray.getJSONObject(i);
comments_userList.add(jsonObject.getString("user"));
comments_olxUserList.add(jsonObject.getString("olxUser"));
comments_dateList.add(jsonObject.getString("date"));
comments_messageList.add(jsonObject.getString("message"));
comments_statusList.add(jsonObject.getString("status"));
}
MainActivity.CustomAdapter customAdapter = new MainActivity.CustomAdapter();
lastComments.setAdapter(customAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LastCommentHome lastCommentHome = new LastCommentHome("3", responseListenerLastComments);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(lastCommentHome);
}
private void loginWithFb() {
// LOGIN MANAGER FACEBOOK
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
String email = me.optString("email");
String name = me.optString("name");
String picture = me.optString("picture");
imageViewFBUser.setVisibility(View.VISIBLE);
imageViewFBUser.setImageURI(Uri.parse(picture));
textViewFBName.setText(name);
textViewFBEmail.setText(email);
}
}
}).executeAsync();
}
#Override
public void onCancel() {
textViewFBName.setText("Login canceled!");
}
#Override
public void onError(FacebookException error) {
textViewFBName.setText("Login error: " + error.getMessage());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
// FACEBOOK INITALZIZE LOGIN
private void initializeControls() {
callbackManager = CallbackManager.Factory.create();
loginButton = findViewById(R.id.login_button);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_search) {
// Handle the camera action
} else if (id == R.id.nav_best) {
} else if (id == R.id.nav_worst) {
} else if (id == R.id.nav_comments) {
} else if (id == R.id.nav_policy) {
} else if (id == R.id.nav_rules) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contact) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return comments_dateList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_lastcomment_homepage, null);
TextView textViewUser = (TextView) convertView.findViewById(R.id.textViewUser);
TextView textViewDate = (TextView) convertView.findViewById(R.id.textViewDate);
TextView textViewMessage = (TextView) convertView.findViewById(R.id.textViewMessage);
textViewUser.setText(comments_userList.get(position));
textViewDate.setText(comments_dateList.get(position));
textViewMessage.setText(comments_messageList.get(position));
lastComments.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Log.d("asdasdxxxxx", String.valueOf(position));
}});
return convertView;
}
}
}
You can create your own interface :
private interface OnListItemClickListener
{
void onListItemClicked(View view, int position);
}
Then use it in your adapter class this way:
class CustomAdapter extends BaseAdapter {
//create an instance
private OnListItemClickListener onListItemClickListener;
//define the object setter
void setOnListItemClickListener(OnListItemClickListener listener)
{
this.onListItemClickListener=listener;}
#Override
public int getCount() {
return comments_dateList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_lastcomment_homepage, null);
TextView textViewUser = (TextView) convertView.findViewById(R.id.textViewUser);
TextView textViewDate = (TextView) convertView.findViewById(R.id.textViewDate);
TextView textViewMessage = (TextView) convertView.findViewById(R.id.textViewMessage);
textViewUser.setText(comments_userList.get(position));
textViewDate.setText(comments_dateList.get(position));
textViewMessage.setText(comments_messageList.get(position));
//Then here trigger
convertView.setOnClickListener(new View.OnClickListener()
{
#override
void onClick(View v)
{
onListItemClickListener.onListItemClicked(v,position);
//you may be asked to set position as final
}
});
return convertView;
}
}
Then in your onCreate method where you attached the adapter, set the listener to your adapter:
MainActivity.CustomAdapter customAdapter = new MainActivity.CustomAdapter();
customAdapter.setOnListItemClickListener(new OnListItemClickListener()
{
#override
void onListItemClicked(View view,int position)
{
//then here place your desired action
}
});
lastComments.setAdapter(customAdapter);
I hope this may be helpful. You can still ask for clarifications in comment

How to add another FragmentActivity that is into MainActivity?

I got my MainActivity class extends as AppCompatActivity but I want to add a new activity as below. I tried to use intent to add it into the MainActivity. However, when I open the app, it crashes when I trigger the function. Here are the codes for two activities.
MainActivity.java
package com.michael.jared.navigationdrawerloginsqlite;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.michael.jared.navigationdrawerloginsqlite.database.DatabaseManagerUser;
import com.michael.jared.navigationdrawerloginsqlite.entity.User;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DatabaseManagerUser databaseManagerUser;
private User itemUsuario;
private String ident;
public ViewPagerActivity vpa;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//se agrego codigo del 39 al 68
Bundle b = getIntent().getExtras();
ident = b.getString("IDENT");
databaseManagerUser= new DatabaseManagerUser(getApplicationContext());
itemUsuario = databaseManagerUser.getUsuario(ident); // encuentra al usuario registrado en la bbdd
View header = ((NavigationView)findViewById(R.id.nav_view)).getHeaderView(0);
((TextView) header.findViewById(R.id.tv_nombre_usuario_menu)).setText(itemUsuario.getNombre());
((TextView) header.findViewById(R.id.tv_correo_menu)).setText(itemUsuario.getCorreo());
Bitmap bitmapsinfoto = BitmapFactory.decodeResource(getResources(),R.drawable.imagen);
RoundedBitmapDrawable roundedBitmapDrawablesinfoto = RoundedBitmapDrawableFactory.create(getResources(), bitmapsinfoto);
roundedBitmapDrawablesinfoto.setCircular(true);
((ImageView) header.findViewById(R.id.imageView)).setImageDrawable(roundedBitmapDrawablesinfoto);
if(itemUsuario.getBytes()!=null){
byte[] foodImage = itemUsuario.getBytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
((ImageView) header.findViewById(R.id.imageView)).setImageBitmap(bitmap);
Bitmap bitmap2 = ((BitmapDrawable)((ImageView) header.findViewById(R.id.imageView)).getDrawable()).getBitmap();
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap2);
roundedBitmapDrawable.setCircular(true);
((ImageView) header.findViewById(R.id.imageView)).setImageDrawable(roundedBitmapDrawable);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
} else if (id == R.id.nav_fourth_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FourthFragment())
.commit();
} else if (id == R.id.nav_share) {
startActivity(new Intent(this, ViewPagerActivity.class));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
ViewPagerActivity.java
package com.michael.jared.navigationdrawerloginsqlite;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AbsListView;
import android.widget.TextView;
#SuppressLint("NewApi")
public class ViewPagerActivity extends FragmentActivity implements
ScrollTabHolder, ViewPager.OnPageChangeListener {
public static final boolean NEEDS_PROXY = Integer.valueOf(Build.VERSION.SDK_INT).intValue() < 11;
private View mHeader;
private PagerSlidingTabStrip mPagerSlidingTabStrip;
private ViewPager mViewPager;
private PagerAdapter mPagerAdapter;
private int mMinHeaderHeight;
private int mHeaderHeight;
private int mMinHeaderTranslation;
private TextView info;
private int mLastY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
mMinHeaderTranslation = -mMinHeaderHeight;
setContentView(R.layout.activity_main);
mHeader = findViewById(R.id.header);
info = (TextView) findViewById(R.id.info);
mPagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(4);
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mPagerAdapter.setTabHolderScrollingContent(this);
mViewPager.setAdapter(mPagerAdapter);
mPagerSlidingTabStrip.setViewPager(mViewPager);
mPagerSlidingTabStrip.setOnPageChangeListener(this);
mLastY=0;
}
#Override
public void onPageScrollStateChanged(int arg0) {
// nothing
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffsetPixels > 0) {
int currentItem = mViewPager.getCurrentItem();
SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
ScrollTabHolder currentHolder;
if (position < currentItem) {
currentHolder = scrollTabHolders.valueAt(position);
} else {
currentHolder = scrollTabHolders.valueAt(position + 1);
}
if (NEEDS_PROXY) {
// TODO is not good
currentHolder.adjustScroll(mHeader.getHeight() - mLastY);
mHeader.postInvalidate();
} else {
currentHolder.adjustScroll((int) (mHeader.getHeight() + mHeader.getTranslationY()));
}
}
}
#Override
public void onPageSelected(int position) {
SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
ScrollTabHolder currentHolder = scrollTabHolders.valueAt(position);
if(NEEDS_PROXY){
//TODO is not good
currentHolder.adjustScroll(mHeader.getHeight()-mLastY);
mHeader.postInvalidate();
}else{
currentHolder.adjustScroll((int) (mHeader.getHeight() +mHeader.getTranslationY()));
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount, int pagePosition) {
if (mViewPager.getCurrentItem() == pagePosition) {
int scrollY = getScrollY(view);
if(NEEDS_PROXY){
//TODO is not good
mLastY=-Math.max(-scrollY, mMinHeaderTranslation);
info.setText(String.valueOf(scrollY));
mHeader.scrollTo(0, mLastY);
mHeader.postInvalidate();
}else{
mHeader.setTranslationY(Math.max(-scrollY, mMinHeaderTranslation));
}
}
}
#Override
public void adjustScroll(int scrollHeight) {
// nothing
}
public int getScrollY(AbsListView view) {
View c = view.getChildAt(0);
if (c == null) {
return 0;
}
int firstVisiblePosition = view.getFirstVisiblePosition();
int top = c.getTop();
int headerHeight = 0;
if (firstVisiblePosition >= 1) {
headerHeight = mHeaderHeight;
}
return -top + firstVisiblePosition * c.getHeight() + headerHeight;
}
public static float clamp(float value, float max, float min) {
return Math.max(Math.min(value, min), max);
}
public class PagerAdapter extends FragmentPagerAdapter {
private SparseArrayCompat<ScrollTabHolder> mScrollTabHolders;
private final String[] TITLES = { "Page 1", "Page 2", "Page 3", "Page 4"};
private ScrollTabHolder mListener;
public PagerAdapter(FragmentManager fm) {
super(fm);
mScrollTabHolders = new SparseArrayCompat<ScrollTabHolder>();
}
public void setTabHolderScrollingContent(ScrollTabHolder listener) {
mListener = listener;
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
ScrollTabHolderFragment fragment = (ScrollTabHolderFragment) SampleListFragment.newInstance(position);
mScrollTabHolders.put(position, fragment);
if (mListener != null) {
fragment.setScrollTabHolder(mListener);
}
return fragment;
}
public SparseArrayCompat<ScrollTabHolder> getScrollTabHolders() {
return mScrollTabHolders;
}
}
}

Navigation Drawer can't navigate

i'm trying to make a navigation to one of my fragment but I can't seem to invoke that fragment here's my code
MainActivity.java
package ics115_4ite_lim.bookings;
import android.app.Fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import ics115_4ite_lim.bookings.Fragments.ScheduleFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
int id = item.getItemId();
if (id == R.id.schedule_fragment) {
fragment = new ScheduleFragment();
} else if (id == R.id.driver_fragment) {
} else if (id == R.id.transaction_fragment) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and this is the fragment I want to go to
ScheduleFragment.java
package ics115_4ite_lim.bookings.Fragments;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;
import com.daimajia.swipe.util.Attributes;
import java.util.ArrayList;
import ics115_4ite_lim.bookings.DividerItemDecoration;
import ics115_4ite_lim.bookings.R;
import ics115_4ite_lim.bookings.Student;
/**
* Created by Mark Terrance on 12/7/2017.
*/
public class ScheduleFragment extends Fragment {
private ArrayList<Student> mDataSet;
private Toolbar toolbar;
private TextView tvEmptyView;
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment_packages
final View view = inflater.inflate(R.layout.schedule_fragment, container, false);
initScheduleView(view);
return view;
}
private void initScheduleView(View view){
mRecyclerView = view.findViewById(R.id.recycleView);
// Layout Managers:
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// Item Decorator:
//mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
mRecyclerView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));
mDataSet = new ArrayList<Student>();
loadData();
if (mDataSet.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
tvEmptyView.setVisibility(View.VISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
tvEmptyView.setVisibility(View.GONE);
}
// Creating Adapter object
SwipeRecyclerViewAdapter mAdapter = new SwipeRecyclerViewAdapter(getActivity(), mDataSet);
// Setting Mode to Single to reveal bottom View for one item in List
// Setting Mode to Mutliple to reveal bottom Views for multile items in List
((SwipeRecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);
mRecyclerView.setAdapter(mAdapter);
/* Scroll Listeners */
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
Log.e("RecyclerView", "onScrollStateChanged");
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
}
// load initial data
public void loadData() {
for (int i = 0; i <= 20; i++) {
mDataSet.add(new Student("Student " + i, "androidstudent" + i + "#gmail.com"));
}
}
private class SwipeRecyclerViewAdapter extends RecyclerSwipeAdapter<SwipeRecyclerViewAdapter.SimpleViewHolder> {
private Context mContext;
private ArrayList<Student> studentList;
public SwipeRecyclerViewAdapter(Context context, ArrayList<Student> objects) {
this.mContext = context;
this.studentList = objects;
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.swipe_row_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
final Student item = studentList.get(position);
viewHolder.tvName.setText((item.getName()) + " - Row Position " + position);
viewHolder.tvEmailId.setText(item.getEmailId());
viewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
// Drag From Left
viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Left, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper1));
// Drag From Right
viewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right, viewHolder.swipeLayout.findViewById(R.id.bottom_wrapper));
// Handling different events when swiping
viewHolder.swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
//when the SurfaceView totally cover the BottomView.
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
//you are swiping.
}
#Override
public void onStartOpen(SwipeLayout layout) {
}
#Override
public void onOpen(SwipeLayout layout) {
//when the BottomView totally show.
}
#Override
public void onStartClose(SwipeLayout layout) {
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
/*viewHolder.swipeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((((SwipeLayout) v).getOpenStatus() == SwipeLayout.Status.Close)) {
//Start your activity
Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
}
}
});*/
viewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, " onClick : " + item.getName() + " \n" + item.getEmailId(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.btnLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked on Map " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked on Share " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Clicked on Edit " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.tvDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mItemManger.removeShownLayouts(viewHolder.swipeLayout);
studentList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, studentList.size());
mItemManger.closeAllItems();
Toast.makeText(view.getContext(), "Deleted " + viewHolder.tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
// mItemManger is member in RecyclerSwipeAdapter Class
mItemManger.bindView(viewHolder.itemView, position);
}
#Override
public int getItemCount() {
return studentList.size();
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
// ViewHolder Class
public class SimpleViewHolder extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
TextView tvName;
TextView tvEmailId;
TextView tvDelete;
TextView tvEdit;
TextView tvShare;
ImageButton btnLocation;
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemView.findViewById(R.id.tvEmailId);
tvDelete = (TextView) itemView.findViewById(R.id.tvDelete);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
tvShare = (TextView) itemView.findViewById(R.id.tvShare);
btnLocation = (ImageButton) itemView.findViewById(R.id.btnLocation);
}
}
}
}
I have tried debugging it and I ended up on a null fragment
I don't know what's wrong because I just followed a tutorial
Help pls ? thanks :D
edit:
<?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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="ics115_4ite_lim.bookings.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
You need to actually do something with the Fragment you created.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
int id = item.getItemId();
if (id == R.id.schedule_fragment) {
fragment = new ScheduleFragment();
} else if (id == R.id.driver_fragment) {
} else if (id == R.id.transaction_fragment) {
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_id, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Make sure your fragment is not null, all your if branches should
initialize it to something
R.id.container_id should be an id of a ViewGroup in your layout that is empty and this is where the fragment will be placed.

Making my navigation list from the right

I have an activity that includes a navigation list and it slides from the left and it is working but I want the list to be at the right side.
I tried to change the gravity_layout from my xml file but the app crashed.
package com.parse.starter;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.ParseUser;
public class UserDrawer extends AppCompatActivity {
//Declaring Variables
private ListView DrawerList;
private ArrayAdapter<String> Adapter;
private ActionBarDrawerToggle DrawerToggle;
private DrawerLayout DrawerLayout;
private String ActivityTitle;
final ParseUser currentUser = ParseUser.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_drawer);
DrawerList = (ListView) findViewById(R.id.navList);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Button Sample = (Button) findViewById(R.id.button);
}
//Method To Add Items To The List View
private void addDrawerItems() {
String[] DArray = {"Job List", "Notifications", "Messages", "Log Out"};
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DArray);
DrawerList.setAdapter(Adapter);
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i0 = new Intent(UserDrawer.this, Set_Info.class);
startActivity(i0);
} else if (position == 1) {
//Intent i1 = new Intent(Drawer1.this, AddPatient.class);
//startActivity(i1);
} else if (position == 2) {
//Intent i2 = new Intent(Drawer1.this, Notifications.class);
//startActivity(i2);
} else if (position == 3) {
//Intent i3 = new Intent(Drawer1.this, Message_Log.class);
//startActivity(i3);
} else if (position == 4) {
Intent i4 = new Intent(UserDrawer.this, MainActivity.class);
startActivity(i4);
Toast.makeText(getApplicationContext(), "You are Logged Out", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
private void setupDrawer() {
DrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Menu");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(ActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerToggle.setDrawerIndicatorEnabled(true);
DrawerLayout.setDrawerListener(DrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Activate the navigation drawer toggle
if (DrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
DrawerToggle.onConfigurationChanged(newConfig);
}
#SuppressWarnings("ResourceType")
public void SampleClick(View view) {
try {
Intent i = new Intent(UserDrawer.this,Set_Info.class);
startActivity(i);
} catch (Exception e) {
}
}
}
http://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html
Drawer positioning and layout is controlled using the android:layout_gravity attribute on child views corresponding to which side of the view you want the drawer to emerge from: left or right. (Or start/end on platform versions that support layout direction.)
i.e. it's android:layout_gravity instead of gravity_layout and it should no longer crash.
try gravity:Endor Right instead of gravity:Startread this answer

Categories

Resources