I do not understand why my code are not working ?
I always have class must either be declared abstract or implement abstract method :
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
case R.id.navigation_public:
return true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
mTextMessage = findViewById(R.id.message);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList<String> mImageUrls = new ArrayList<>();
ArrayList<String> mNames = new ArrayList<>();
mImageUrls.add("https://c1.staticflickr.com/5/4636/25316407448_de5fbf183d_o.jpg");
mNames.add("Havasu Falls");
mImageUrls.add("https://i.redd.it/tpsnoz5bzo501.jpg");
mNames.add("Trondheim");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.recycler_public);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, mImageUrls);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
}
I found the answer... I forget this :
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
Sorry...
Related
I'm trying to send a value from TextView to RecyclerView (in an another Activity).
MainActivity.class
There is i want to use a method onClickYes for send each of word to my recyclerView in an another activity.
public class MainActivity extends AppCompatActivity {
TextView display, progress;
private List<String> worldList;
private ArrayList<RecyclerItems> recyclerItems;
private WordDataBase wordDatabaseForYes;
int counter = 1;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = findViewById(R.id.dispalay);
progress = findViewById(R.id.progress);
recyclerItems = new ArrayList<>();
worldList = new ArrayList<>();
worldList.add("cat");//i want to display this word firstly
worldList.add("dog");//it after click
worldList.add("monkey");//after it
worldList.add("bird");//after it
worldList.add("fish");//etc
worldList.add("home");//etc
worldList.add("car");//etc
}
public void onClickYes(View view) {
if (i >= worldList.size()) return;
display.setText(worldList.get(i));
progress.setText(counter + "");
//заполняем наш recyclerView
//Intent intent = new Intent(MainActivity.this, YesActivity.class);
//intent.putExtra("word", user + ", вам передали: " + gift);
//startActivity(intent);
i++;
counter++;
}
public void onClickNo(View view) {
Toast.makeText(this, "Size is " + worldList.size(), Toast.LENGTH_SHORT).show();
//recyclerItems.add(new RecyclerItems(worldList.get(i)));
i = 0;
counter = 0;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.yes:
recyclerItems.add(new RecyclerItems(worldList.get(i)));
intent = new Intent(MainActivity.this, YesActivity.class);
startActivity(intent);
break;
case R.id.no:
intent = new Intent(MainActivity.this, NoActivity.class);
startActivity(intent);
break;
case R.id.about:
Toast.makeText(this, "By SaturnPRO", Toast.LENGTH_SHORT).show();
//openDialogAbout
break;
}
return true;
}
}
My Second Activity
public class YesActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<RecyclerItems> yesWordList;
private WordDataBase wordDatabaseForYes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yesWordList = new ArrayList<>();
recyclerView = findViewById(R.id.rvYes);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(yesWordList);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
}
}
Also i have an Adapter but i couldn't show it here.
How can i do it? enter code here Please help.
Send the word in intent extras:
case R.id.yes:
recyclerItems.add(new RecyclerItems(worldList.get(i)));
intent = new Intent(MainActivity.this, YesActivity.class);
intent.putExtra("key", worldList.get(i));
startActivity(intent);
break;
In your second activity:
String name = intent.getStringExtra("key");
You can make the wordList a static member. Then you can access it in your adapter.
I got a problem with updating ViewPager fragments. We need to show fragments with data to registered user, when he doesn't registered we need to show fragments with message to register. I use this method to check it in MainActivity:
#Override
public void setAdapter(boolean isUserExist) {
Log.d("RegDebug", "In setAdapter");
mainPagerAdapter.clearData();
mainPagerAdapter.addFragment(searchFragment, getString(R.string.search_title));
if (isUserExist) {
Log.d("RegDebug", "In setAdapter reg");
mainPagerAdapter.addFragment(new ChatsFragment(), getString(R.string.chats_title));
mainPagerAdapter.addFragment(new ActionsFragment(), getString(R.string.actions_title));
Toast.makeText(getApplicationContext(), "Registered!", Toast.LENGTH_SHORT).show();
} else {
Log.d("RegDebug", "In setAdapter unreg");
mainPagerAdapter.addFragment(RegisterFragment.newInstance(Consts.CHATS_TAB_NAME), getString(R.string.chats_title));
mainPagerAdapter.addFragment(RegisterFragment.newInstance(Consts.ACTIONS_TAB_NAME), getString(R.string.actions_title));
Toast.makeText(getApplicationContext(), "Unregistered!!!", Toast.LENGTH_SHORT).show();
}
mainPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(mainPagerAdapter);
}
I call this method in presenter with setting value from firebase auth, checking if user exists:
public void checkForUserExist() {
if (mainInteractor.isUserExist()) {
getViewState().setRegAdapter();
} else getViewState().setUnregAdapter();
}
And then call presenter method in onCreate of MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialogFragment = new FilterDialogFragment();
searchFragment = new SearchFragment();
//UI
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.main_view_pager);
tabLayout = findViewById(R.id.main_tabs);
//mainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
mainPresenter.checkForUserExist();
tabLayout.setupWithViewPager(viewPager);
}
I try to log the boolean result and it returns exactly value that must be, but pager adapter can't update its content.Code of MainPagerAdapter:
public class MainPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentTitleList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
public void clearData(){
fragmentList.clear();
fragmentTitleList.clear();
notifyDataSetChanged();
Log.d("RegDebug", " fragmentList size is " + fragmentList.size()
+ " fragmentTitleList size is " + fragmentTitleList.size());
}
}
Use OnPageChangeListener of ViewPager class & notify to your current fragment from there using interface.
I am trying to refresh a RecyclerView by assigning a new adapter to the RecyclerView but it is throwing a NullPointerException.
I have created a TabLayout which has three tabs and when you reselect the first tab the method is called to refresh the RecyclerView. But, I am getting a NullPointerException on recyclerViewAdapter.notifyDataSetChanged();. I have initialized recyclerViewAdapter in the onCreateView(); but I still get an Exception.
EDIT :
This is a fragment not an Activity, I cannot setContentView();. Please read the question before down voting or doing anything not helpful.
Please suggest a proper way if I am doing it wrong.
Fragment which has the RecyclerView :
Tab1.class :
public class Tab1 extends Fragment {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private List<World> worldList;
private OnFragmentInteractionListener mListener;
private DBHelper helper;
private Context myContext;
private View view;
#Override
public void onStart() {
this.helper = new DBHelper(getContext());
recyclerViewAdapter = new RecyclerViewAdapter(getContext(), helper.getList());
super.onStart();
}
public Tab1() {
}
public void update() {
recyclerViewAdapter.notifyDataSetChanged();
}
#Override
public void onCreate(Bundle savedInstanceState) {
this.helper = new DBHelper(getContext());
this.worldList = new ArrayList<>();
this.worldList = helper.getList();
this.recyclerViewAdapter = new RecyclerViewAdapter(getContext(), this.worldList);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_tab1, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewAdapter = new RecyclerViewAdapter(getContext(), worldList);
recyclerView.setAdapter(recyclerViewAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
The method is called from the MainActivity.class(When the Tab is re selected).
MainActivty.class :
public class MainActivity extends AppCompatActivity implements Tab1.OnFragmentInteractionListener, Tab2.OnFragmentInteractionListener, Tab3.OnFragmentInteractionListener {
DBHelper helper;
World world;
Location location;
GPSTracker tracker;
RecyclerViewAdapter adapter;
public static Context CONTEXT = null;
RecyclerView recyclerView;
public Tab1 tab1;
public static final String BROADCAST_ACTION = "e.wolverine2.thewalkingapp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
CONTEXT = getApplicationContext();
MessageReciever reciever = new MessageReciever(new Message());
Intent intent = new Intent(this, MyService.class);
intent.putExtra("reciever", reciever);
startService(intent);
tracker = new GPSTracker(getApplicationContext());
location = tracker.getLocation();
helper = new DBHelper(getApplicationContext());
tab1 = new Tab1();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
adapter = new RecyclerViewAdapter(getApplicationContext(), helper.getList());
final TabLayout tabLayout = (TabLayout) findViewById(R.id.myTabLayout);
tabLayout.addTab(tabLayout.newTab().setText("LOCATIONS"));
tabLayout.addTab(tabLayout.newTab().setText("TOTAL DISTANCE"));
tabLayout.addTab(tabLayout.newTab().setText("CALS"));
tabLayout.getTabAt(0).setIcon(R.drawable.ic_list);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_person_pin);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_fitness_excercise);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//onError();
final ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
final PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
Tab1 tab1 = new Tab1();
tab1.update();
}
}
});
}
public void locationChanged(double longi, double lati) {
final Location location = new Location("");
location.setLatitude(lati);
location.setLongitude(longi);
world = new World();
String timeStamp = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date());
world.setLongitude(location.getLongitude());
world.setLatitiude(location.getLatitude());
world.setDate(timeStamp);
world.setTime(timeStamp);
world.setLocation("Anonymous");
helper.addRow(world);
//tab1.update(getApplicationContext());
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public class Message {
public void displayMessage(int resultCode, Bundle resultData) throws NullPointerException {
double longi = resultData.getDouble("longitude");
double lati = resultData.getDouble("latitude");
locationChanged(longi, lati);
//Toast.makeText(MainActivity.this, "TOASTY X : " + e.getMessage(), Toast.LENGTH_SHORT).show();
//Log.v("TOASTY X : ","" + e.getMessage());
}
}
public void onError() {
helper.onDropTable();
Toast.makeText(this, "TABLE DROPED!", Toast.LENGTH_SHORT).show();
}
}
Logcat :
java.lang.NullPointerException: Attempt to invoke virtual method 'void e.wolverine2.thewalkingapp.RecyclerViewAdapter.notifyDataSetChanged()' on a null object reference
at e.wolverine2.thewalkingapp.Tab1.update(Tab1.java:57)
at e.wolverine2.thewalkingapp.MainActivity$1.onTabReselected(MainActivity.java:101)
at android.support.design.widget.TabLayout.dispatchTabReselected(TabLayout.java:1177)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1136)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
at android.view.View$PerformClick.run(View.java:23985)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6816)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
Java Tip: When it gets here:
Tab1 tab1 = new Tab1();
tab1.update();
A new Tab is instantiated using the cunstructor:
public Tab1() {
}
in your Tab class. as you see the recyclerView is not initialized up to this point.So the recyclerView is actually Null!
Answer: To correctly implement fragment take a look at this:
https://stackoverflow.com/a/5161143/6094503
What you looking for is the following lines:
Fragment newFragment = new DebugExampleTwoFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(CONTENT_VIEW_ID, newFragment).commit();
but I think you need more study about fragments and how they're added to (or removed from) an activity
I'm trying to bookmark my app but I have some charges in my code, below I'll explain my problems.
Let's start with my adapter memes.class
public class memes{
private String nome;
private int resID;
private Boolean mIsFavourite;
public memes(String nome, int resID){
this.nome = nome;
this.resID = resID;
}
public Boolean getmIsFavourite() {
return mIsFavourite;
}
public void setmIsFavourite(Boolean mIsFavouriteResource) {
this.mIsFavourite = mIsFavouriteResource;
}
public String getNome(){
return nome;
}
public int getResId(){
return resID;
}
#Override
public String toString(){
return nome;
}
}
Main activity
public class MainActivity extends AppCompatActivity {
ListView lv;
MediaPlayer mp;
ArrayList<memes> item;
ArrayAdapter<memes> arrayAdapter;
String[] Nomes = new String[]{"Compartilhar", "Add Favoritos"};
List<memes> favoriteMemes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
lv = findViewById(R.id.lv);
mp = new MediaPlayer();
item = new ArrayList<>();
//itens
item.add(new memes("item 1", R.raw.audio1));
item.add(new memes("item 2", R.raw.audio2));
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, item);
lv.setAdapter(arrayAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long l) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Menu");
builder.setItems(MainActivity.this.Nomes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
sendWhatsAppAudio(position);
return;
case 1:
//set item true
item.get(position).setmIsFavourite(true);
return;
default:
}
}
});
builder.show();
return true;
}
});
}
This is where I send the items to the other activity
//Here is the mess.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.abreFavoritos:
for(int i=0;i<lv.getAdapter().getCount();i++){
memes fMeme = (memes)lv.getAdapter().getItem(i);
//mIsFavourite in my code it turns red
//what should I put after the item. to work?
if (item.mIsFavourite()) {
favoriteMemes.add(fMeme);
}
}
intent = new Intent(this, Favoritos.class);
intent.putExtra("favoritos", new Gson().toJson(favoriteMemes));
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Now finally activity in which we place the Favoritos.class
public class Favoritos extends AppCompatActivity {
ListView lv;
ArrayAdapter<memes> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
lv = findViewById(R.id.lv);
String memesString = getIntent().getStringExtra("favoritos");
memes[] fMemes = new Gson().fromJson(memesString,memes[].class);
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, fMemes);
lv.setAdapter(arrayAdapter);
}
}
Items are not displayed with this code.
I think my problem is in if (item.mIsFavorite ()) but I have no idea what to put here.
one more thing, on the second activity how would I remove the items?
and tbm could I recommend a good tutorial from SharedPreferences so I can use that case.
Thank you
When I want to get a name of list which I pressed, I get "com.example.oleksandr.dream.DB.DreamDetails#528f8a90". How can I get a String value from my list? The problem is in "the onItemClick" methode.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DBHelper mDbHelper = null;
private DreamDetails dreamDetails;
private ListView mListView;
private DrawerLayout drawerLayout;
private Toolbar mToolbar;
private Dao<DreamDetails, Integer> dreamDetailsDao;
private List<DreamDetails> dreamList;
private int selectedRecordPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listViewAllDreams);
try {
//Getting all Data from DB
dreamDetailsDao = getHelper().getDreamDetailsesDao();
dreamList = dreamDetailsDao.queryForAll();
// Set the header of the ListView
final LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.list_view, mListView, false);
mListView.addHeaderView(view);
// my own adapter!
mListView.setAdapter(new AdapterArrayDream(this,R.layout.list_view,dreamList,dreamDetailsDao));
mListView.setOnItemClickListener(this);
} catch (SQLException e) {
e.printStackTrace();
}
initToolbar();
initNavigationView();
FloatingActionButton myFab = (FloatingActionButton)findViewById(R.id.fab);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewDream.class);
startActivity(intent);
}
});
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(i > 0)
{
selectedRecordPosition = i - 1;
// final Intent intent = new Intent(this, ViewDream.class);
Log.i("TAAAAAAG", "onClick " + adapterView.getItemAtPosition(selectedRecordPosition));
// intent.putExtra("D", String.valueOf(adapterView.getItemAtPosition(selectedRecordPosition)));
// startActivity(intent);
}
}
private void initNavigationView() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawlerLayout);
}
private void initToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle(R.string.app_name);
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
// mToolbar.inflateMenu(R.menu.menu);
}
// This is how, DatabaseHelper can be initialized for future use
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_list_dreams, menu);
return true;
}
private DBHelper getHelper() {
if (mDbHelper == null) {
mDbHelper = OpenHelperManager.getHelper(this, DBHelper.class);
}
return mDbHelper;
}
}
To create a query which looks up an account by name and password you would do the following:
QueryBuilder<Account, String> qb = accountDao.queryBuilder();
Where where = qb.where();
// the name field must be equal to "foo"
where.eq(Account.NAME_FIELD_NAME, "foo");
// and
where.and();
// the password field must be equal to "_secret"
where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();