So in NameList where it says "fragmentTransaction.add(android.R.id.content, fragment2, "login").commit();" I need to find the container of NameList when I try R.id.container a blank white screen appears. What should I put instead of android.R.id.content in this case?
NameList.java
package com.drdc1.medic;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* A simple {#link Fragment} subclass.
*/
public class NameList extends Fragment implements DataObserver {
private SoldierListAdapter adapter;
private HomeActivity homeActivity;
private ArrayList<Soldier> soldiers = new ArrayList<>();
public NameList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_name_list, container, false);
homeActivity = (HomeActivity) getActivity();
homeActivity.registerFragment(this);
final ListView listView = (ListView) rootView.findViewById(R.id.soldierList);
addListHeader(listView);
DataManager dbManager = ((AppContext) getActivity().getApplication()).getDataManager();
soldiers = dbManager.getActiveSoldier();
adapter = new SoldierListAdapter(getContext(), soldiers);
listView.setAdapter(adapter);
TextView nameHeader = (TextView) rootView.findViewById(R.id.name_header);
nameHeader.setOnClickListener(new ClickToSort());
TextView hrHeader = (TextView) rootView.findViewById(R.id.hr_header);
hrHeader.setOnClickListener(new ClickToSort());
TextView brHeader = (TextView) rootView.findViewById(R.id.br_header);
brHeader.setOnClickListener(new ClickToSort());
TextView skinTmpHeader = (TextView) rootView.findViewById(R.id.skin_tmp_header);
skinTmpHeader.setOnClickListener(new ClickToSort());
TextView core_tmp_header = (TextView) rootView.findViewById(R.id.core_tmp_header);
core_tmp_header.setOnClickListener(new ClickToSort());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO When item clicked, write code here
String idsol = null;
if (((Soldier) listView.getAdapter().getItem(position)) != null) {
idsol = ((Soldier) listView.getAdapter().getItem(position)).getId();
}
android.support.v4.app.FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
if (idsol != null){
bundle.putString("id", idsol); // Put anything what you want
}
IndividualSoldierTab fragment2 = new IndividualSoldierTab();
fragment2.setArguments(bundle);
fragmentTransaction.add(android.R.id.content, fragment2, "login").commit();
// getFragmentManager()
// .beginTransaction()
// .replace(R.id.container, fragment2)
// .commit();
}
});
return rootView;
}
#Override
public void onPause() {
super.onPause();
homeActivity.registerFragment(this);
}
#Override
public void onResume() {
super.onResume();
homeActivity.registerFragment(this);
}
#Override
public void onDestroyView() {
homeActivity.unregisterFragment(this);
super.onDestroyView();
}
#Override
public void update(Map data) {
Boolean soldierInTheList = false;
for (Soldier s : soldiers) {
if (data.get("ID").equals(s.getId())) {
s.setPhysioData(data);
soldierInTheList = true;
}
}
if (!soldierInTheList) {
Soldier newSol = new Soldier((String) data.get("name"), (String) data.get("ID"));
newSol.setPhysioData(data);
soldiers.add(newSol);
}
adapter.notifyDataSetChanged();
}
private void addListHeader(ListView lv) {
View headerView =
LayoutInflater.from(getContext()).inflate(R.layout.list_header, lv, false);
lv.addHeaderView(headerView);
}
private class SoldierListAdapter extends ArrayAdapter<Soldier> {
private final ArrayList<Soldier> soldiers;
private String sortedBy = "";
// the soldier list is only sorted by 1 attribute at a time. don't overthink about stable sorting
public SoldierListAdapter(Context context, ArrayList<Soldier> soldiers) {
super(context, R.layout.list_item, soldiers);
this.soldiers = soldiers;
}
public String getSortedBy() {
return sortedBy;
}
/***
* When the user click the header when soldiers are already sorted, reverse the order
*/
public void reverse() {
Collections.reverse(soldiers);
}
/***
* #param x "Sort by x" Sortby is an enum
*/
public void sort(SortBy x) {
switch (x) {
case NAME:
this.sort(new OrderByName());
sortedBy = "NAME";
break;
case HR:
this.sort(new OrderByHR());
sortedBy = "HR";
break;
case BR:
this.sort(new OrderByBR());
sortedBy = "BR";
break;
case SKINTMP:
this.sort(new OrderBySkinTmp());
sortedBy = "SKINTMP";
break;
case CORETMP:
this.sort(new OrderByCoreTmp());
sortedBy = "CORETMP";
break;
default:
}
}
#NonNull
#Override
public View getView(int position, View v, ViewGroup parent) {
// Get the data item for this position
Soldier soldier = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (v == null) {
v = LayoutInflater.from(getContext())
.inflate(R.layout.list_item, parent, false);
}
TextView name = (TextView) v.findViewById(R.id.name);
// name.setOnClickListener(new setFragmentTransition());
name.setText(soldier.getName());
ImageView overall = (ImageView) v.findViewById(R.id.overal_status);
switch (soldier.getOverallStatus()) {
case "RED":
overall.setImageResource(R.drawable.red);
break;
case "GREEN":
overall.setImageResource(R.drawable.green);
break;
case "YELLOW":
overall.setImageResource(R.drawable.yellow);
break;
default:
break;
}
if (soldier.getBodyOrientation() != null && !soldier.getBodyOrientation().isEmpty()) {
ImageView bodyPos = (ImageView) v.findViewById(R.id.body_position);
bodyPos.setImageResource(R.drawable.body);
switch (soldier.getBodyOrientation()) {
case "UP":
break;
case "DOWN":
bodyPos.setRotation(180);
break;
case "LEFT":
bodyPos.setRotation(270);
break;
case "RIGHT":
bodyPos.setRotation(90);
break;
default:
break;
}
}
String currentHR = soldier.getHeartRate();
String lastHR = soldier.getLastHeartRate();
if (!currentHR.equals("")) {
TextView heartRate = (TextView) v.findViewById(R.id.hr_text);
ImageView arrow = (ImageView) v.findViewById(R.id.hr_img);
if (!lastHR.equals("")) {
if (Integer.parseInt(currentHR) > Integer.parseInt(lastHR)) {
arrow.setImageResource(R.drawable.up_arrow);
heartRate.setTextColor(Color.RED);
} else if (Integer.parseInt(currentHR) < Integer.parseInt(lastHR)) {
arrow.setImageResource(R.drawable.down_arrow);
heartRate.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
heartRate.setTextColor(Color.BLACK);
}
}
heartRate.setText(currentHR);
}
//TODO replace image for down_arrow color not right
String currentBR = soldier.getBreathingRate();
String lastBR = soldier.getLastBreathingRate();
if (!currentBR.equals("")) {
TextView breathingRate = (TextView) v.findViewById(R.id.br_text);
ImageView arrow = (ImageView) v.findViewById(R.id.br_img);
if (!lastBR.equals("")) {
if (Integer.parseInt(currentBR) > Integer.parseInt(lastBR)) {
arrow.setImageResource(R.drawable.up_arrow);
breathingRate.setTextColor(Color.RED);
} else if (Integer.parseInt(currentBR) < Integer.parseInt(lastBR)) {
arrow.setImageResource(R.drawable.down_arrow);
breathingRate.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
breathingRate.setTextColor(Color.BLACK);
}
}
breathingRate.setText(currentBR);
}
String currentCoreTmp = soldier.getCoreTmp();
String lastCoreTmp = soldier.getLastCoreTmp();
if (!currentCoreTmp.equals("")) {
TextView coreTmp = (TextView) v.findViewById(R.id.core_tmp_text);
ImageView arrow = (ImageView) v.findViewById(R.id.core_tmp_img);
if (!lastCoreTmp.equals("")) {
if (Integer.parseInt(currentCoreTmp) > Integer.parseInt(lastCoreTmp)) {
arrow.setImageResource(R.drawable.up_arrow);
coreTmp.setTextColor(Color.RED);
} else if (Integer.parseInt(currentCoreTmp) < Integer.parseInt(lastCoreTmp)) {
arrow.setImageResource(R.drawable.down_arrow);
coreTmp.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
coreTmp.setTextColor(Color.BLACK);
}
}
coreTmp.setText(currentCoreTmp);
}
String currentSkinTmp = soldier.getSkinTmp();
String lastSkinTmp = soldier.getLastSkinTmp();
if (!currentSkinTmp.equals("")) {
TextView skinTmp = (TextView) v.findViewById(R.id.skin_tmp_text);
ImageView arrow = (ImageView) v.findViewById(R.id.skin_tmp_img);
if (!lastSkinTmp.equals("")) {
if (Integer.parseInt(currentSkinTmp) > Integer.parseInt(lastSkinTmp)) {
arrow.setImageResource(R.drawable.up_arrow);
skinTmp.setTextColor(Color.RED);
} else if (Integer.parseInt(currentSkinTmp) < Integer.parseInt(lastSkinTmp)) {
arrow.setImageResource(R.drawable.down_arrow);
skinTmp.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
skinTmp.setTextColor(Color.BLACK);
}
}
skinTmp.setText(currentSkinTmp);
}
//TextView tvHome = (TextView) v.findViewById(R.id.tvHome);
// Populate the data into the template view using the data object
// Return the completed view to render on screen
return v;
}
}
private class ClickToSort implements View.OnClickListener {
#Override
public void onClick(View v) {
String sortBy = (String) ((TextView) v).getText();
switch (sortBy.toLowerCase()) {
case "name":
if (adapter.getSortedBy().equals("NAME")) {
adapter.reverse();
} else {
adapter.sort(SortBy.NAME);
}
break;
case "hr":
if (adapter.getSortedBy().equals("HR")) {
adapter.reverse();
} else {
adapter.sort(SortBy.HR);
}
break;
case "br":
if (adapter.getSortedBy().equals("BR")) {
adapter.reverse();
} else {
adapter.sort(SortBy.BR);
}
break;
case "skintmp":
if (adapter.getSortedBy().equals("SKINTMP")) {
adapter.reverse();
} else {
adapter.sort(SortBy.SKINTMP);
}
break;
case "coretmp":
if (adapter.getSortedBy().equals("CORETMP")) {
adapter.reverse();
} else {
adapter.sort(SortBy.CORETMP);
}
break;
default:
}
adapter.notifyDataSetChanged();
}
}
/************************************************************************
* Comparator classes to support different ordering of soldiers
*************************************************************************/
private enum SortBy {
NAME, HR, BR, SKINTMP, CORETMP
}
private static class OrderByName implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return s1.getName().compareTo(s2.getName());
}
}
private static class OrderByHR implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.parseInt(s1.getHeartRate().equals("") ? "0" : s1.getHeartRate())
- Integer.parseInt(s2.getHeartRate().equals("") ? "0" : s2.getHeartRate());
}
}
private static class OrderByBR implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getBreathingRate().equals("") ? "0" : s1.getBreathingRate())
.compareTo(Integer.valueOf(
s2.getBreathingRate().equals("") ? "0" : s2.getBreathingRate()));
}
}
private static class OrderBySkinTmp implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getSkinTmp().equals("") ? "0" : s1.getSkinTmp())
.compareTo(Integer.valueOf(s2.getSkinTmp().equals("") ? "0" : s2.getSkinTmp()));
}
}
private static class OrderByCoreTmp implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getCoreTmp().equals("") ? "0" : s1.getCoreTmp())
.compareTo(Integer.valueOf(s2.getCoreTmp().equals("") ? "0" : s2.getCoreTmp()));
}
}
}
HomeActivity.java
package com.drdc1.medic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
// This is the home page of the tab application.
public class HomeActivity extends AppCompatActivity implements FragmentDataManager {
private SectionsPagerAdapter mSectionsPagerAdapter;
private DataReceiver dataReceiver;
private ArrayList<DataObserver> fragmentlist;
static private HashMap data; //one data shared by all fragments
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startBackgroundServices();
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
//register intent filter for LocalBroadbast Manager
IntentFilter PDAMESSAGE = new IntentFilter("PDAMessage");
dataReceiver = new DataReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(dataReceiver, PDAMESSAGE);
data = new HashMap();
fragmentlist = new ArrayList<>();
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
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();
}
});
}
#Override
public void registerFragment(DataObserver o) {
if (!fragmentlist.contains(o))
fragmentlist.add(o);
}
#Override
public void unregisterFragment(DataObserver o) {
if (fragmentlist.contains(o)) {
int observerIndex = fragmentlist.indexOf(o);
fragmentlist.remove(observerIndex);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void notifyObserver(Map data) {
for (DataObserver observer : fragmentlist) {
observer.update(data);
}
}
class DataReceiver extends BroadcastReceiver {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onReceive(Context context, Intent intent) {
data.put("bodypos", intent.getStringExtra("bodypos"));
data.put("overall", intent.getStringExtra("overall"));
data.put("coreTemp", intent.getStringExtra("coreTmp"));
data.put("skinTemp", intent.getStringExtra("skinTmp"));
data.put("br", intent.getStringExtra("br"));
data.put("hr", intent.getStringExtra("hr"));
data.put("ID",intent.getStringExtra("ID"));
data.put("name",intent.getStringExtra("name"));
notifyObserver(data);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(
getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
SquadStatus tab1 = new SquadStatus();
return tab1;
case 1:
NameList tab2 = new NameList();
return tab2;
case 2:
IndividualSoldierTab tab3 = new IndividualSoldierTab();
return tab3;
case 3:
TreatmentScreenTab tab4 = new TreatmentScreenTab();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Squad Status";
case 1:
return "Name List";
case 2:
return "Individual Soldier";
case 3:
return "Treatment Screen";
}
return null;
}
}
private void startBackgroundServices() {
Intent Serviceintent = new Intent();
Serviceintent.setClass(this, BackgroundServer.class);
startService(Serviceintent);
Intent sleepAlgo = new Intent();
sleepAlgo.setClass(this, BackgroundSleepAlgo.class);
startService(sleepAlgo);
Intent wellnessAlgo = new Intent();
wellnessAlgo.setClass(this, BackgroundWellnessAlgo.class);
startService(wellnessAlgo);
}
public void callHelp(View v) {
Intent callhelp = new Intent(HomeActivity.this, HelpActivity.class);
startActivity(callhelp);
}
}
What should the container?
You can simply use a FrameLayout as the container layout and add fragments dynamically.
Related
I want to click on a custom object in my RecycleView, which then starts a new Activity inclusive Data about the object clicked but i get no response on clicking.
I tried following this question but either I did something wrong or it doesn't work.
JokeCategory
package com.example.jokestarapplication;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class JokeCategory implements Parcelable{
private String name;
private List<Joke> jokes;
public JokeCategory(String name) {
this.name = name;
this.jokes= new ArrayList<>();
}
protected JokeCategory(Parcel in){
name=in.readString();
in.readList(jokes,List.class.getClassLoader());
}
public JokeCategory(String name, List<Joke> jokes) {
this.name = name;
this.jokes = jokes;
}
public static final Creator<JokeCategory> CREATOR = new Creator<JokeCategory>() {
#Override
public JokeCategory createFromParcel(Parcel in) {
return new JokeCategory(in);
}
#Override
public JokeCategory[] newArray(int size) {
return new JokeCategory[size];
}
};
public String getName() {
return name;
}
public String getJokeNumString() {
return String.valueOf(jokes.size());
}
public List<Joke> getJokes() {
return jokes;
}
#Override
public String toString() {
return name;
}
public void addJoke(Joke joke) {
jokes.add(joke);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeList(jokes);
}
}
CategoryListAdapter
package com.example.jokestarapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.CategoryViewHolder> {
private List<JokeCategory> mItems;
private Context mContext;
private ListItemClickListener mListItemClickListener;
public CategoryListAdapter(List<JokeCategory> mItems, Context mContext, ListItemClickListener mListItemClickListener) {
this.mItems = mItems;
this.mContext = mContext;
this.mListItemClickListener = mListItemClickListener;
}
#Override
public int getItemViewType(final int position) {
return R.layout.category_list_item;
}
#NonNull
#Override
public CategoryViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
mContext = context;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.category_list_item, parent, false);
return new CategoryViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CategoryViewHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
return (mItems==null) ? 0 : mItems.size();
}
interface ListItemClickListener {
void onListItemClick(JokeCategory item);
}
public void setOnListItemClickListener(ListItemClickListener listItemClickListener) {
mListItemClickListener = listItemClickListener;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView tvCatName, tvCatNum;
public CategoryViewHolder(#NonNull View itemView) {
super(itemView);
tvCatName = itemView.findViewById(R.id.tvCatName);
tvCatNum = itemView.findViewById(R.id.tvCatNum);
}
public TextView getTvCatName() {
return tvCatName;
}
public TextView getTvCatNum() {
return tvCatNum;
}
public void bind(int position) {
tvCatName.setText(mItems.get(position).getName());
tvCatNum.setText(mItems.get(position).getJokeNumString());
}
#Override
public void onClick(View v) {
if (mListItemClickListener!=null){
int clickedIndex = getAdapterPosition();
JokeCategory jokeCategory = mItems.get(clickedIndex);
mListItemClickListener.onListItemClick(jokeCategory);
}
}
}
}
MainFragment
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.LinkedList;
import java.util.List;
public class MainFragment extends Fragment implements CategoryListAdapter.ListItemClickListener {
private CategoryListAdapter mAdapter;
private RecyclerView rvcategories;
private List<JokeCategory> categories;
private onCategoryITemSelected listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
categories = (List<JokeCategory>) getArguments().getSerializable("Categories");
// Add the following lines to create RecyclerView
rvcategories = view.findViewById(R.id.rvcategories);
rvcategories.setHasFixedSize(true);
rvcategories.setLayoutManager(new LinearLayoutManager(view.getContext()));
mAdapter = new CategoryListAdapter(categories, getContext(), this);
rvcategories.setAdapter(mAdapter);
return view;
}
#Override
public void onResume() {
categories = (List<JokeCategory>) getArguments().getSerializable("Categories");
rvcategories.getAdapter().notifyDataSetChanged();
super.onResume();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
if (context instanceof onCategoryITemSelected)
listener = (onCategoryITemSelected) context;
else
throw new ClassCastException(context.toString() + "must implement listener");
}
#Override
public void onListItemClick(JokeCategory item) {
Intent i = new Intent(getContext(), ActivityCategory.class);
i.putExtra(ActivityCategory.KEY_EXTRACATEGORY, item);
startActivity(i);
}
public interface onCategoryITemSelected {
void onListItemClick(JokeCategory item);
}
private List<JokeCategory> DemoData() {
List<JokeCategory> data = new LinkedList<>();
data.add(new JokeCategory("Short Jokes"));
data.add(new JokeCategory("Long Jokes"));
data.add(new JokeCategory("One Liner"));
data.add(new JokeCategory("Dumb Jokes"));
data.add(new JokeCategory("Chuck Norris"));
return data;
}
}
MainActivity
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.material.navigation.NavigationView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
//global available user data
public static String displayUserName;
public static String displayUserEmail;
GoogleSignInClient mGoogleSignInClient;
private TextView displayName;
private TextView displayEmail;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar toolbar;
private NavigationView navigationView;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
private List<JokeCategory> categories;
private Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer);
navigationView = findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
actionBarDrawerToggle.syncState();
categories = DemoData();
bundle = new Bundle();
bundle.putSerializable("Categories", (Serializable) categories);
//load default fragment
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
MainFragment mainFragment = new MainFragment();
mainFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container_fragment, mainFragment);
fragmentTransaction.commit();
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// Side navigation elements (needs headerView since sidenav can be hidden (null)
View headerView = navigationView.getHeaderView(0);
displayName = (TextView) headerView.findViewById(R.id.displayName);
displayEmail = (TextView) headerView.findViewById(R.id.displayEmail);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (account != null) {
//account.getDisplayName()
Log.d("AUTH", "User is logged-in automatically");
Toast.makeText(this, "Google Login automatically (already signed in previously)",
Toast.LENGTH_LONG).show();
updateMainActivityUI(account);
} else {
Log.d("AUTH", "User is NOT logged-in automatically");
}
}
public void updateMainActivityUI(GoogleSignInAccount account) {
// Global vars
displayUserName = account.getDisplayName();
displayUserEmail = account.getEmail();
//Side nav vars
Log.d("AUTH", "side nav vars: " + displayUserName);
Log.d("AUTH", "side nav vars: " + displayUserEmail);
// if (displayUserName != null) {
displayName.setText(displayUserName);
// }
// if (displayUserEmail != null) {
displayEmail.setText(displayUserEmail);
// }
}
//move to new Fragment
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
bundle = new Bundle();
bundle.putSerializable("Categories", (Serializable) categories);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
switch (item.getItemId()) {
case R.id.home:
MainFragment mainFragment = new MainFragment();
mainFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container_fragment, mainFragment);
break;
case R.id.newJoke:
NewJokeFragment newJokeFragment = new NewJokeFragment();
newJokeFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container_fragment, newJokeFragment);
break;
case R.id.logInOut:
fragmentTransaction.replace(R.id.container_fragment, new LogInOutFragment());
break;
case R.id.aboutUs:
fragmentTransaction.replace(R.id.container_fragment, new AboutUsFragment());
break;
case R.id.register:
fragmentTransaction.replace(R.id.container_fragment, new RegisterFragment());
break;
}
fragmentTransaction.commit();
return true;
}
private List<JokeCategory> DemoData() {
List<JokeCategory> data = new ArrayList<>();
data.add(new JokeCategory("Short Jokes"));
data.add(new JokeCategory("Long Jokes"));
data.add(new JokeCategory("One Liner"));
data.add(new JokeCategory("Dumb Jokes"));
data.add(new JokeCategory("Chuck Norris"));
return data;
}
public void updateCategories(List<JokeCategory> list){
categories = list;
}
}
It looks like the itemView.onClickListener is never registered.
add the following line to the constructor.
itemView.setOnClickListener(this);
It would look like:
public CategoryViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
tvCatName = itemView.findViewById(R.id.tvCatName);
tvCatNum = itemView.findViewById(R.id.tvCatNum);
}
This is one of my tab fragment.
I just wanted to show the list of Movies & Tv Shows that includes the word in SearchView
And when I click one of the images, it moves to the Detail Activity.
The problem happens when I search two or more words continuously.
It moves to proper Detail Activity and when I close that Activity it comes with several other unrelated Detail Activity.
I need you guys help
First code is the Fragment Code
package com.example.endterm.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.endterm.ItemAdapter;
import com.example.endterm.Items;
import com.example.endterm.MovieDetail;
import com.example.endterm.R;
import com.example.endterm.TVDetail;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
SearchView searchView;
TextView tVQuery;
String queryWord;
//RecyclerView recyclerView7, recyclerView8;
ItemAdapter adapter7 = new ItemAdapter(7);
ItemAdapter adapter8 = new ItemAdapter(8);
public SearchFragment() {
// Required empty public constructor
}
class MyItmeDecoration extends RecyclerView.ItemDecoration{
#Override
public void getItemOffsets(#NonNull Rect outRect, #NonNull View view, #NonNull RecyclerView parent, #NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.set(10, 10, 10, 10);
view.setBackgroundColor(Color.BLACK);
}
}
// TODO: Rename and change types and number of parameters
public static SearchFragment newInstance(String param1, String param2) {
SearchFragment fragment = new SearchFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_search, container, false);
tVQuery = (TextView) rootView.findViewById(R.id.query);
searchView = (SearchView) rootView.findViewById(R.id.search);
//final MyItmeDecoration Deco = new MyItmeDecoration();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
queryWord = s;
tVQuery.setText("Searched by : " + s);
// 입력받은 문자열 처리
searchView.onActionViewCollapsed();
adapter7.empty();
adapter8.empty();
adapter7.notifyDataSetChanged();
adapter8.notifyDataSetChanged();
exp(adapter7, "https://api.themoviedb.org/3/search/movie?api_key=0a9a6b6bcc6ed2a798fb5401045dd81f&language=ko&query=" + s + "&page=1&include_adult=false", true);
exp(adapter8, "https://api.themoviedb.org/3/search/tv?api_key=0a9a6b6bcc6ed2a798fb5401045dd81f&language=ko&page=1&query=" + s + "&include_adult=false", false);
return true;
}
#Override
public boolean onQueryTextChange(String s) {
// 입력란의 문자열이 바뀔 때 처리
return false;
}
});
return rootView;
}
private void exp(final ItemAdapter adapterS, String urlE, final boolean movieortv){
final RecyclerView rec;
if(movieortv) {
rec = (RecyclerView) getActivity().findViewById(R.id.searchedMovie);
}
else{
rec = (RecyclerView) getActivity().findViewById(R.id.searchedTV);
}
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rec.setLayoutManager(linearLayoutManager);
MyItmeDecoration Deco = new MyItmeDecoration();
if(Deco != null){
rec.removeItemDecoration(Deco);
}
rec.addItemDecoration(Deco);
rec.setAdapter(adapterS);
RequestQueue queue= Volley.newRequestQueue(getActivity());
StringRequest fR=new StringRequest(Request.Method.GET, urlE, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
parseXMLForecast(rec, response, adapterS, movieortv);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(fR);
}
private void parseXMLForecast(RecyclerView rec, String response, ItemAdapter adaptersample, final boolean movieortv){
try{
final ArrayList<Items> items = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
String results = jsonObject.getString("results");
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject subJsonObject = jsonArray.getJSONObject(i);
String url = "https://image.tmdb.org/t/p/w300" + subJsonObject.getString("poster_path");
String title;
if(movieortv) {
title = subJsonObject.getString("title");
}
else{
title = subJsonObject.getString("name");
}
String id = subJsonObject.getString("id");
Items jump = new Items(url, title, id);
items.add(jump);
}
adaptersample.setItems(items);
adaptersample.notifyDataSetChanged();
rec.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), rec, new ClickListener() {
#Override
public void onClick(View view, int position) {
Items dict = items.get(position);
Intent intent;
if(movieortv == true) {
intent = new Intent(getActivity(), MovieDetail.class);
}
else{
intent = new Intent(getActivity(), TVDetail.class);
}
intent.putExtra("id", dict.getId());
intent.putExtra("url", dict.getUrl());
intent.putExtra("title", dict.getTitle());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
Items dict = items.get(position);
Toast.makeText(getActivity(), dict.getTitle()+' '+dict.getId()+' '+dict.getUrl(), Toast.LENGTH_LONG).show();
}
}));
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private SearchFragment.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final SearchFragment.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
And the Second one is the Adapter Code if you need
package com.example.endterm;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.endterm.Items;
import java.util.ArrayList;
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{
private ArrayList<Items> items = new ArrayList<>();
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
private int wheree;
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public ItemAdapter(int wheree){
this.wheree = wheree;
}
public ItemAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View itemView = null;
if(wheree == 1) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork1, parent, false);
}
else if(wheree == 2){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork2, parent, false);
}
else if(wheree == 3){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork3, parent, false);
}
else if(wheree == 4){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork4, parent, false);
}
else if(wheree == 5){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork5, parent, false);
}
else if(wheree == 6){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork6, parent, false);
}
else if(wheree == 7){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork7, parent, false);
}
else if(wheree == 8){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork8, parent, false);
}
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
public void onBindViewHolder(#NonNull ItemAdapter.ViewHolder viewHolder, int position) {
Items item = items.get(position);
Glide.with(viewHolder.itemView.getContext())
.load(item.getUrl())
.into(viewHolder.weatherImageView);
}
class ViewHolder extends RecyclerView.ViewHolder{
public ImageView weatherImageView;
public ViewHolder(View itemView){
super(itemView);
if(wheree == 1){
weatherImageView=(ImageView)itemView.findViewById(R.id.item_image1);
}
else if(wheree == 2){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image2);
}
else if(wheree == 3){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image3);
}
else if(wheree == 4){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image4);
}
else if(wheree == 5){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image5);
}
else if(wheree == 6){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image6);
}
else if(wheree == 7){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image7);
}
else if(wheree == 8){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image8);
}
}
}
public void empty(){
for(int i = 0; i < getItemCount(); i++){
items.remove(0);
}
}
public int getItemCount() {
return items.size();
}
public void setItems(ArrayList<Items> items){
this.items = items;
}
}
First of all, remove this code, you do not need this here
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
Then, you did not implement getItemId() correctly. You can change this like that:
#Override
public long getItemId(int position) {
return items.get(position).getId(); //if you have item id, of course
}
I think the problem is because you are not specifying the items id, that is why it is opening several activities. Try this out. Hope it helps
Problem
When I run on the phone, I press lib item(Bottom Menu Library Item). It shows correctly. Then, when I change the fragment (ex: Home Fragment(Bottom Menu Home Item) and reselect lib item(Bottom Menu Library Item) recycler view inside it disappears. To solve I need to wait or relaunch the app. Below my code in Java.
My Fragment Page Adapter
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>(); // this line can cause crashes
private final List<String> lstTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return lstFragment.get(i);
}
#Override
public int getCount() {
return lstFragment.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void AddFragment(Fragment fragment, String Title){
lstFragment.add(fragment); // this line can cause crashes
lstTitles.add(Title);
}
}
RecyclerView Adapter code
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>{
Context mContext;
List<Focus> mData;
public RecyclerViewAdapter(Context mContext, List<Focus> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.card_item_home, viewGroup, false);
MyViewHolder myViewHolder = new MyViewHolder(v);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.txtTitle.setText(mData.get(i).getTitle());
myViewHolder.imgView.setImageResource(mData.get(i).getImage());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView txtTitle;
ImageView imgView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txtTitle = itemView.findViewById(R.id.card_view_title);
imgView = itemView.findViewById(R.id.card_view_image);
}
}
}
Main Activity Code
public class MainActivity extends AppCompatActivity {
private Button music_ImageView;
private TextView music_title, music_state, music_duration, music_currentTime;
private SeekBar music_playerSeekbar;
private MediaPlayer mediaPlayer;
private Handler handler = new Handler();
private BottomNavigationView bottomNav;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNav = findViewById(R.id.bottom_nav_menu);
bottomNav.setOnNavigationItemSelectedListener(navListener);
/**-------------------------------------------------------------------------**/
music_ImageView = (Button) findViewById(R.id.music_player_btn);
music_currentTime = (TextView) findViewById(R.id.textCurrentTime);
music_duration = (TextView) findViewById(R.id.textTotalDuration);
music_playerSeekbar = (SeekBar) findViewById(R.id.music_player_seekbar);
music_title = (TextView) findViewById(R.id.music_player_title);
music_state = (TextView) findViewById(R.id.music_player_state);
mediaPlayer = new MediaPlayer();
music_playerSeekbar.setMax(100);
music_ImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
handler.removeCallbacks(Updater);
mediaPlayer.pause();
music_ImageView.setBackgroundResource(R.drawable.ic_pause);
music_state.setText("Pause");
} else {
mediaPlayer.start();
music_ImageView.setBackgroundResource(R.drawable.ic_play);
music_state.setText("Playing");
updateSeekBar();
}
}
});
prepareMediaPlayer();
music_playerSeekbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
SeekBar seekBar = (SeekBar) v;
int playPosition = (mediaPlayer.getDuration() / 100) * seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
music_currentTime.setText(milliSecondsToTimer(mediaPlayer.getCurrentPosition()));
return true;
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
music_playerSeekbar.setSecondaryProgress(percent);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
music_playerSeekbar.setProgress(0);
music_ImageView.setBackgroundResource(R.drawable.ic_play);
music_currentTime.setText(R.string.zero);
music_duration.setText(R.string.zero);
mediaPlayer.reset();
prepareMediaPlayer();
}
});
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new HomeFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
actionBar.setElevation(0);
actionBar.setTitle("Brain.Music");
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
RelativeLayout muz = (RelativeLayout)findViewById(R.id.music_player);
ActionBar actionBar;
switch (item.getItemId()){
case R.id.menu_home: {
bottomNav.getMenu().getItem(1).setIcon(R.drawable.ic_favorite_border);
selectedFragment = new HomeFragment();
actionBar = getSupportActionBar();
actionBar.setTitle("Brain.Music");
muz.setVisibility(View.VISIBLE);
}
break;
case R.id.menu_fav: {
item.setIcon(R.drawable.ic_favorite);
selectedFragment = new FavFragment();
actionBar = getSupportActionBar();
actionBar.setTitle("Favorite");
muz.setVisibility(View.VISIBLE);
}
break;
case R.id.menu_lib: {
bottomNav.getMenu().getItem(1).setIcon(R.drawable.ic_favorite_border);
selectedFragment = new LibFragment();
actionBar = getSupportActionBar();
actionBar.setTitle("Library");
}
break;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, selectedFragment)
.commit();
return true;
}
};
private void prepareMediaPlayer(){
try{
mediaPlayer.setDataSource("");
mediaPlayer.prepare();
music_duration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
}catch (Exception exception){
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private Runnable Updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
long currentDuration = mediaPlayer.getDuration();
music_currentTime.setText(milliSecondsToTimer(currentDuration));
}
};
private void updateSeekBar(){
if ( mediaPlayer.isPlaying()){
music_playerSeekbar.setProgress((int)((float)mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration() * 100));
handler.postDelayed(Updater, 1000);
}
}
private String milliSecondsToTimer(long milliSeconds){
String timerString = "";
String secondsString = "";
int hours = (int)(milliSeconds / (1000 * 60 * 60));
int minutes = (int)(milliSeconds % (1000 * 60 * 60) / (1000 * 60));
int seconds = (int)(milliSeconds % (1000 * 60 * 60) % ((1000 * 60)) / 1000);
if ( hours > 0 ){
timerString = hours + ":";
}
if ( seconds < 10 ){
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;
}
timerString = timerString + minutes + ":" + secondsString;
return timerString;
}
}
Lib Fragment
import android.app.ActionBar;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class LibFragment extends Fragment {
View v;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private BottomNavigationView btnNav;
private Fragment fragment;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_lib, container, false);
tabLayout = (TabLayout)v.findViewById(R.id.tabLayout);
viewPager = (ViewPager)v.findViewById(R.id.viewPager);
/// Adding fragments
/// Adapter Setting
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.getTabAt(2).select();
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewPagerAdapter = new ViewPagerAdapter(getFragmentManager());
viewPagerAdapter.AddFragment(new FragmentFocus(), "Focus"); // `FragmentFocus()` should be inside `FragmentPagerAdapter.getItem()`
viewPagerAdapter.AddFragment(new FragmentSleep(), "Sleep"); // `FragmentSleep()` should be inside `FragmentPagerAdapter.getItem()`
viewPagerAdapter.AddFragment(new FragmentRelax(), "Relax"); // `FragmentRelax()` should be inside `FragmentPagerAdapter.getItem()`
}
}
Fragment Focus Code
package com.xcube.demo_nav;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
public class FragmentFocus extends Fragment {
View v;
private RecyclerView recyclerView;
private List<Category> lstCategory;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.focus_fragment, container, false);
recyclerView = (RecyclerView)v.findViewById(R.id.recyclerView_library);
CategoryRecyclerView recyclerViewAdapter = new CategoryRecyclerView(getContext(), lstCategory);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lstCategory = new ArrayList<>();
lstCategory.add(new Category("Lo-FI", R.drawable.icon_focus));
lstCategory.add(new Category("Lo-FI", R.drawable.icon_focus));
lstCategory.add(new Category("Forest", R.drawable.icon_relax));
}
}
I recently started to write an application which let me to get information from a forum. I used JSoup library for scraping the data. My first part is going well.
When the app opens, it just gets data from the site(sub-forum names) and pass it so the listview is able to show them. When I press an item in the listview it just gets the thread list in the sub-forum. All the things are working properly excepts the listview doesn't get updated correctly.
As you can see when I press an item from the list(Just the first item in the list) then it set loadedSub to true then it gets the thread list using an async-task then in the postexecute it calls notifyDataSetChanged() on PagerAdapter. The problem is it just updates the UI perfectly, even leaving 1 tab only as I wanted, but the problem is that threadList doesn't appear in the listview. It only shows me the listview with previous data, not the threadlist.
Should I use another activity or is there something I am missing?
MainActivity.java
package com.ovnis.sscattered.elakiriunofficial;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
public static SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
public static ViewPager mViewPager;
public static String[][] forumListSubForumsList = new String[13][];
public static String[][] forumListSubForumListLinks = new String[13][];
public static String[][] threadListLinks = new String[2][];
static Context context;
public String[] forumNumbers = {"1", "86", "89", "6",
"66", "79", "70", "12",
"16", "33", "42", "25",
"22"};
public static String subforumLink;
static boolean loaded = false;
static boolean loadedSub = false;
static boolean subForumMode = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
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();
}
});
new GetSubForumList().execute();
context = getBaseContext();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class SubForumsFrag extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
static ListView listview;
static ForumListAdapter adapter;
int pos = 0;
public SubForumsFrag() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static SubForumsFrag newInstance(int pos) {
SubForumsFrag fragment = new SubForumsFrag();
Bundle args = new Bundle();
args.putInt("poskey", pos);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_base, container, false);
listview = (ListView) rootView.findViewById(R.id.listview);
pos = getArguments().getInt("poskey");
if(loaded){
adapter = new ForumListAdapter(getActivity(), forumListSubForumsList[pos]);
}
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), forumListSubForumListLinks[pos][position], Toast.LENGTH_SHORT).show();
subForumMode = true;
subforumLink = forumListSubForumListLinks[pos][position];
new GetThreadList().execute();
}
});
return rootView;
}
}
public static class ThreadListFrag extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
static ListView listview;
static ForumListAdapter adapter;
int pos = 0;
public ThreadListFrag() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static ThreadListFrag newInstance() {
ThreadListFrag fragment = new ThreadListFrag();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_base, container, false);
listview = (ListView) rootView.findViewById(R.id.listview);
if(loadedSub){
adapter = new ForumListAdapter(getActivity(), threadListLinks[0]);
}
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getContext(), forumListSubForumListLinks[pos][position], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a SubForumsFrag (defined as a static inner class below).
if(!subForumMode){
return SubForumsFrag.newInstance(position);
}else{
return ThreadListFrag.newInstance();
}
}
#Override
public int getCount() {
// Show 13 total pages.
if(!subForumMode){
return 13;
}else{
return 1;
}
}
#Override
public CharSequence getPageTitle(int position) {
if(!subForumMode){
switch (position) {
case 0:
return "Elakiri";
case 1:
return "Cooking";
case 2:
return "B & M";
case 3:
return "General";
case 4:
return "E. Traveler";
case 5:
return "Automobile";
case 6:
return "Motorcycles";
case 7:
return "Entertainment";
case 8:
return "C & I";
case 9:
return "S. Piyasa";
case 10:
return "Elakiri Magic";
case 11:
return "Games";
case 12:
return "Mobile";
}
}else{
return "Bitch Me";
}
return null;
}
#Override
public int getItemPosition(Object obj){
return POSITION_NONE;
}
}
class GetSubForumList extends AsyncTask<Void, Integer, String>
{
String TAG = getClass().getSimpleName();
ProgressDialog dialog;
protected void onPreExecute (){
Log.d(TAG + " PreExceute","On pre Exceute......");
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(Void...arg0){
Log.d(TAG + " DoINBackGround","On doInBackground...");
try {
Connection.Response response = Jsoup.connect("http://www.elakiri.com/forum/")
.execute();
Document parsedDoc = response.parse();
Element doc;
Elements doce;
for(int i = 0; i < forumNumbers.length; i++){
doc = parsedDoc.select("tbody#collapseobj_forumbit_" + forumNumbers[i]).first();
doce = doc.select("a[href] strong");
forumListSubForumsList[i] = new String[(doce.size()+1)/2];
forumListSubForumListLinks[i] = new String[(doce.size()+1)/2];
for(int q = 0; q < (doce.size()+1)/2; q++){
forumListSubForumsList[i][q] = doce.get(q*2).text();
forumListSubForumListLinks[i][q] = doce.get(q*2).parent().absUrl("href");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "Shot";
}
protected void onProgressUpdate(Integer...a){
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
Log.d(TAG + " onPostExecute", "" + result);
loaded = true;
mViewPager.invalidate();
mSectionsPagerAdapter.notifyDataSetChanged();
dialog.dismiss();
}
}
static class GetThreadList extends AsyncTask<Void, Integer, String>
{
String TAG = getClass().getSimpleName();
ProgressDialog dialog;
protected void onPreExecute (){
Log.d(TAG + " PreExceute","On pre Exceute......");
dialog = new ProgressDialog(context);
dialog.setTitle("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
// dialog.show();
}
protected String doInBackground(Void...arg0){
Log.d(TAG + " DoINBackGround","On doInBackground...");
try {
Connection.Response response = Jsoup.connect(subforumLink)
.execute();
Element doc = response.parse().select("tbody#threadbits_forum_2").first();
Elements doce = doc.select("a[id^=thread_title_]");
threadListLinks[0] = new String[doce.size()];
threadListLinks[1] = new String[doce.size()];
for(int i = 0; i < doce.size(); i++){
threadListLinks[0][i] = doce.get(i).text();
threadListLinks[1][i] = doce.get(i).absUrl("href");
}
} catch (IOException e) {
e.printStackTrace();
}
return "Shot";
}
protected void onProgressUpdate(Integer...a){
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
Log.d(TAG + " onPostExecute", "" + result);
loadedSub = true;
mViewPager.invalidate();
mSectionsPagerAdapter.notifyDataSetChanged();
}
}
}
ForumListAdapter.java
public class ForumListAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ForumListAdapter(Context context, String[] values) {
super(context, R.layout.main_adapter ,values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.main_adapter, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.firstLine);
textView.setText(values[position]);
return rowView;
}
}
Alright, I got it solved using FragmentStatePageAdapter instead of using FragmentPageAdapter
what i'm trying to do:
in FirstFragment the user can type in his weight.
in SecondFragment the weight should be shown in a TextView
the Value should be passed on swipe of the user.
i tried arround 3 how-to's and read a lot about fragments but i still couldn't find a suitable solution. As i'm kind of new to fragments it could also be that i made a uncommon way to generate fragments and it therefore doesn't work but i couldn't figure it out yet.
As you can se unerneath actually there is an error in the code because i tried to get access to the method of FirstFragment through the MainActivity
To simplyfy, i don't poste the whole code of the two fragment xlm's.
first_frag.xml have a EditText (id: getWeight) Box where you only can enter numbers up to 3 digits
second_frag.xml has a TextView (id: txtAlcLvl)
activity_main.xml:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
MainActivity.java:
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.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
Calculator calc = new Calculator();
ViewPager pager;
private MyPagerAdapter myPagerAdapter;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
public Calculator getCalc(){
return this.calc;
}
public void getWeight(){
FragmentManager fm = getSupportFragmentManager();
FirstFragment fragment = (FirstFragment)fm.findFragmentById(R.id.i_dont_know_the_id);
//failure because trying to get access to Method of FirstFragment
fragment.getWeight();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int i, final float v, final int i2) {
}
#Override
public void onPageSelected(final int i) {
YourFragmentInterface fragment = (YourFragmentInterface) pagerAdapter.instantiateItem(pager, i);
if (fragment != null) {
fragment.fragmentBecameVisible();
}
}
#Override
public void onPageScrollStateChanged(final int i) {
}
});
}
public interface YourFragmentInterface {
void fragmentBecameVisible();
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 1: return new SecondFragment(); //SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return new FirstFragment();
default: return new FirstFragment(); //FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
FirstFragment.java:
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.EditText;
public class FirstFragment extends Fragment implements MainActivity.YourFragmentInterface {
Button btnBeer;
Button btnBeerSmall;
Button btnWine;
Button btnLiq;
Button btnSch;
Button btnWater;
Button btnMale;
Button btnFemale;
Calculator calc;
EditText getWeight;
public String getWeight(){
return getWeight.getText().toString();
}
#Override
public void fragmentBecameVisible() {
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
btnBeer = (Button) v.findViewById(R.id.btnBeer);
btnBeerSmall = (Button) v.findViewById(R.id.btnBeerSmall);
btnWine = (Button) v.findViewById(R.id.btnWine);
btnLiq = (Button) v.findViewById(R.id.btnLiq);
btnSch = (Button) v.findViewById(R.id.btnSch);
btnWater = (Button) v.findViewById((R.id.btnWater));
btnMale = (Button) v.findViewById(R.id.btnMale);
btnFemale = (Button) v.findViewById(R.id.btnFemale);
getWeight = (EditText) v.findViewById(R.id.getWeight);
btnBeer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(0);
}
});
btnBeerSmall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(1);
}
});
btnWine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(2);
}
});
btnLiq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(3);
}
});
btnSch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(4);
}
});
btnWater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(5);
}
});
btnMale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnMale.setBackgroundResource(R.drawable.male_false);
btnFemale.setBackgroundResource(R.drawable.female);
}
});
btnFemale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnFemale.setBackgroundResource(R.drawable.female_false);
btnMale.setBackgroundResource(R.drawable.male);
}
});
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
SecondFragment.java:
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.ImageButton;
import android.widget.TextView;
public class SecondFragment extends Fragment implements MainActivity.YourFragmentInterface {
TextView txtAlcLvl;
TextView txtTimeToZero;
TextView txtPeak;
ImageButton btnReset;
Calculator calc;
String weight;
#Override
public void fragmentBecameVisible() {
calc.person.setSex(false);
calc.person.setWeight(80);
txtAlcLvl.setText(((MainActivity) getActivity()).getWeight());
//txtAlcLvl.setText(String.format("%.2f", calc.getCurrentLevel()) + "‰");
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
public void setSex(){
}
public void setWeight(){
try{
} catch(NumberFormatException e){
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
txtAlcLvl = (TextView) v.findViewById(R.id.txtAlcLvl);
txtTimeToZero = (TextView) v.findViewById(R.id.txtTimeToZero);
txtPeak = (TextView) v.findViewById(R.id.txtPeak);
btnReset = (ImageButton) v.findViewById((R.id.btnReset));
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.resetConsumption();
}
});
return v;
}
public void updateText(String t){
txtAlcLvl.setText(t);
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
You could do it the over way round.
Instead of trying to get the weight in activity from your fragment, try to set the weight on the activity from the fragment.
public class MainActivity extends FragmentActivity {
...
private float weight;
public void setWeight(float weight) {
this.weight = weight;
}
public float getWeight() {
return this.weight();
}
Then in your FirstFragment:
((MainActivity)getActivity()).setWeight(...);
And finally in your SecondFragment:
float weight = ((MainActivity)getActivity()).getWeight();
Don't try to "pass" the value like you would normally expect when an activity is invoking a new fragment.
Instead, consider using some persistent storage to store the value, such as SharedPreferences or a Sqlite database. Each fragment can read and write values out of there as needed.