I've created a tabbed activity in Android Studio, selecting it from the "New activity" window dialog.
The tabs number is not fixed, but it is read from a file, so that there is a random number of tabs. For this purpose, I used a FragmentStatePagerAdapter.
In this activity I want to show a listview populated differently for each tab, but the problem is that the listview is not shown.
As you can see below, this is the java class, where I handle the operations within the tabs.
public class TournamentActivity extends AppCompatActivity {
private int returnT = 0, goingT = 0;
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tournament);
Intent intent = this.getIntent();
String committee = intent.getStringExtra(TournamentsAdapter.EXTRA_COMMITTEE);
String tournament = intent.getStringExtra(TournamentsAdapter.EXTRA_TOURNAMENT);
String roundName = intent.getStringExtra(TournamentsAdapter.EXTRA_ROUNDNAME);
int roundId = intent.getExtras().getInt("EXTRA_ROUNDID");
int roundAr = intent.getExtras().getInt("EXTRA_ROUNDAR");
int matchDay = intent.getExtras().getInt("EXTRA_MATCHDAY");
int roundStage = intent.getExtras().getInt("EXTRA_ROUNDSTAGE");
new GetDataFromURL(this, "tournament.html").execute("http://www.fip.it/AjaxGetDataCampionato.asp?com=" + committee + "&camp=" + tournament + "&fase=" + roundStage + "&girone=" + roundId + "&ar=" + roundAr + "&turno=" + matchDay);
//parse del file per vedere titolo e quante schede fare (numero di giornate del campionato)
try{
FileReader fr = new FileReader(getFilesDir() + "/ImportData/tournament.html");
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine())!= null){
if(line.contains("tableTopBkg")){
while((line = br.readLine())!= null){
Pattern pattern = Pattern.compile(">(.+?)</div>");
Matcher matcher = pattern.matcher(line);
while (matcher.find()){
String s = matcher.group(1);
s = s.substring(s.lastIndexOf(">") + 1);
returnT = Integer.parseInt(s);
}
if(line.equals("</tr>") && goingT == 0){
goingT += returnT;
}
else if(line.equals("</tr>")){
break;
}
}
}
}
System.out.println(returnT);
}catch (IOException ignored){}
catch (Exception e){e.printStackTrace();}
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);
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();
}
});
if(roundAr == 1)
mViewPager.setCurrentItem(matchDay - 1);
else if(roundAr == 0)
mViewPager.setCurrentItem((matchDay + goingT) - 1);
}
#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_tournament, 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 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;
}
// +++++ QUI SI POPOLANO LE TABS +++++
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tournament, 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;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView listViewGames = (ListView) view.findViewById(R.id.listViewGames);
GamesAdapter adapter = new GamesAdapter(getActivity(), android.R.layout.simple_list_item_1);
listViewGames.setAdapter(adapter);
}
/*
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
GamesAdapter adapter = new GamesAdapter(getContext(), R.layout.activity_tournament);
listViewGames.setAdapter(adapter);
}*/
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
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 PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show N total pages.
return goingT + returnT;
}
}
}
In the onViewCreated method I get the reference of the listview and then create my custom adapter. Subsequently, with listViewGames.setAdapter(adapter); I set the adapter.
At this point when onViewCreated is called, the setAdapter method doesn't call getView in the adapter.
I also tried to set the adapter in the onCreateView method, but it still does not work.
This is the adapter class:
public class GamesAdapter extends ArrayAdapter{
private Context context;
public GamesAdapter(Context context, int resource) {
super(context, resource);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.fragment_games, null);
ImageView imageViewStatus = (ImageView) convertView.findViewById(R.id.imageViewStatus);
ImageView imageViewTeamA = (ImageView) convertView.findViewById(R.id.imageViewTeamA);
ImageView imageViewTeamB = (ImageView) convertView.findViewById(R.id.imageViewTeamB);
TextView textViewGameId = (TextView) convertView.findViewById(R.id.textViewGameId);
TextView textViewDateTime = (TextView) convertView.findViewById(R.id.textViewDateTime);
TextView textViewTeamA = (TextView) convertView.findViewById(R.id.textViewTeamA);
TextView textViewTeamB = (TextView) convertView.findViewById(R.id.textViewTeamB);
TextView textViewScoreA = (TextView) convertView.findViewById(R.id.textViewScoreA);
TextView textViewScoreB = (TextView) convertView.findViewById(R.id.textViewScoreB);
FileReader fr = null;
String gameId = "";
try {
fr = new FileReader(context.getFilesDir() + "/ImportData/tournament.html");
BufferedReader br = new BufferedReader(fr);
String line;
int hops = 0;
while((line = br.readLine())!= null){
if(line.contains("<div class=\"risTrCode\">") && hops == position){
Pattern pattern = Pattern.compile(">(.+?)</a></div>");
Matcher matcher = pattern.matcher(line);
gameId = matcher.group(1);
System.out.println(gameId);
hops++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textViewGameId.setText(gameId);
return convertView;
}
}
Related
First of all, I'm sorry for my english, but I need your help.
I got a recyclerView gallery with photos and option to show the selected photo in another activity.
I`m trying to share an image that activity to somewhere, e.g. email, but I receive an empty message with no image.
Could you help me to find out, what am I doing wrong?
Below is the code of gallery activity and single image activity.
Thank you for answers.
public class MainActivity extends AppCompatActivity {
GalleryAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<ImageModel> data = new ArrayList<>();
public static String getURLForResource(int resourceId) {
return Uri.parse("android.resource://" + R.class.getPackage().getName() + "/" + resourceId).toString();
}
public static String IMGS[];
public static String MAYF[] = {
"file:///android_asset/mayf1.jpg",
"file:///android_asset/mayf2.gif",
"file:///android_asset/mayf3.jpg",
"file:///android_asset/mayf4.jpg",
"file:///android_asset/mayf5.gif",
"file:///android_asset/mayf6.gif",
"file:///android_asset/mayf7.jpg",
"file:///android_asset/mayf8.jpg",
"file:///android_asset/mayf9.jpg",
"file:///android_asset/mayf10.jpg"
};
public static String APRF[] = {
"file:///android_asset/apr1.jpg",
"file:///android_asset/apr2.gif",
"file:///android_asset/apr3.jpg",
"file:///android_asset/apr4.jpg",
"file:///android_asset/apr5.gif",
"file:///android_asset/apr6.gif",
"file:///android_asset/apr7.jpg",
"file:///android_asset/apr8.jpg",
"file:///android_asset/apr9.jpg",
"file:///android_asset/apr10.jpg"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (StartingActivity.count == 1)
IMGS = Arrays.copyOf(APRF, APRF.length);
else if (StartingActivity.count == 2) {
IMGS = Arrays.copyOf(MAYF, MAYF.length);
} else {
Toast.makeText(getBaseContext(), "not filled yet",
Toast.LENGTH_LONG).show();
}
for (int i = 0; i < IMGS.length; i++) {
ImageModel imageModel = new ImageModel();
imageModel.setName("Image " + i);
imageModel.setUrl(IMGS[i]);
data.add(imageModel);
}
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
intent.putExtra("superUri", IMGS[position]);
startActivity(intent);
}
}));
}
#Override
public void onBackPressed() {
super.onBackPressed();
StartingActivity.count = 0;
}
}
This part is a part of a single image.
public class DetailActivity 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private ShareActionProvider mShareActionProvider;
public ArrayList<ImageModel> data = new ArrayList<>();
int pos;
String shPos;
Toolbar toolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
// setSupportActionBar(toolbar);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
shPos = getIntent().getStringExtra("superUri");
setTitle("Открытки");
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
//setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#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_detail, menu);
// Fetch and store ShareActionProvider
// Return true to display 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
return super.onOptionsItemSelected(item);
}
public void onShClick(MenuItem item) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(shPos));
shareIntent.setType("image/*");
startActivity(shareIntent);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageModel> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageModel> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUri());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
#Override
public CharSequence getPageTitle(int position) {
return data.get(position).getName();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
final ImageView imageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).into(imageView);
return rootView;
}
}
}
Here is an example of trying to share image via gmail. I can see the image "attached", but can`t open it. Another email receives an empty message with no attachment inside.
sharing example
This is the MainActivity upon launch. The user puts in a number then clicks the button and the Intent brings them to a swipe view with the number they entered.
public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
continueButton = (Button) findViewById(R.id.ContinueButton);
NumberET = (EditText) findViewById(R.id.etTotalAmount);
continueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
number = NumberET.getText().toString();
if (number.equals("")) {
Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
} else {
Bundle bundle = new Bundle();
bundle.putString("AMOUNT_KEY", number);
FixedCosts fragment = new FixedCosts();
fragment.setArguments(bundle);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.container, fragment).commit();
Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
intent.putExtra("NUMBER", number);
startActivity(intent);
}
}
});
}
In the fragment, I would like to set the text of a textview to display that number. I cannot get this number to send from this Activity class to the Fragment. How can I fix this?
Fragment:
ublic class FixedCosts extends Fragment {
String amount;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fixed_costs_fragment, container, false);
amount = this.getArguments().getString("AMOUNT_KEY");
TextView TitletextView = (TextView) view.findViewById(R.id.amountTitle);
TitletextView.setText(amount);
return view;}}
Here is the FragmentActivity that sets the swipe view:
public class FragmentActivity extends AppCompatActivity {
public static final String MY_CUSTOM_FRAGMENT_KEY = "I_GOT_THE_KEYS";
String MoneyAmount;
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment);
/*MoneyAmount = getIntent().getExtras().getString("AmountMoney");*/
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);
}
private Fragment createCustomFragment(){
Bundle bundle = new Bundle();
bundle.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
PlaceholderFragment placeholderFragment = new PlaceholderFragment();
placeholderFragment.setArguments(bundle);
return placeholderFragment;
}
#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_, 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 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, String MoneyAmount) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Bundle bundle = getArguments();
/*String amount = bundle.getString(MY_CUSTOM_FRAGMENT_KEY);
TextView TitletextView = (TextView) FixedCosts.class.findViewById(R.id.amountTitle);
TitletextView.setText(amount);*/
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
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) {
switch (position){
case 0:
FixedCosts fixedCosts = new FixedCosts();
return fixedCosts;
}
return PlaceholderFragment.newInstance(position + 1, MoneyAmount);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Fixed Costs";
case 1:
return "Long term investments";
case 2:
return "SECTION 3";
}
return null;
}
}
}
Remove activity start code in continueButton.setOnClickListener listener and add view container in same layout for parent activity not in fragment activity:
public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
continueButton = (Button) findViewById(R.id.ContinueButton);
NumberET = (EditText) findViewById(R.id.etTotalAmount);
continueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
number = NumberET.getText().toString();
if (amount.equals("")) {
Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
} else {
Bundle bundle = new Bundle();
bundle.putString("AMOUNT_KEY", number);
FixedCosts fragment = new FixedCosts();
fragment.setArguments(bundle);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.container, fragment).commit();
}
}
});
}
Hope it will help you.
I fixed the issue by saving the value to SharedPreferences.
In the MainActivity.class:
SharedPreferences saveAmount = getSharedPreferences("MyPrefs", 0);
final SharedPreferences.Editor editor = saveAmount.edit();
editor.putString("AMOUNT", amount);
editor.commit();
In the Fragment class:
SharedPreferences sharedPrefs = this.getActivity().getSharedPreferences("MyPrefs", 0);
String amount = (sharedPrefs.getString("AMOUNT", "Ummmmm"));
I am trying to make my tabbed activity content to change dynamically, depended on the user choices in the other tabs.
All tabs are using the same fragment. only the content in the view is supposed to change (in this case a ListView)
Now the main problem is that when I make a choice (click on some line in the ListView) the next tab shows all of the content instead of filtering the data according to my choice in the previous tab, though when I click on a not-neighbor tab and then go back, the tab is filtered like I wanted.
From what I understand, the activity load the neighbor tabs of the current tab even if those are not focused and this is why I get the default result.
To simplify things:
Then I choose some line from the ListView and the focus automatically goes to the next tab.
The listView will show me the default contet, as if I chose nothing. But if I move the focus to the forth tab, and then again back to the second, the listView will be filtered as I wanted
Here is my code
public class Catalog_actbartabs 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
public static String PACKAGE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog_actbartabs);
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();
}
});
PACKAGE_NAME = getApplicationContext().getPackageName();
}
public void setCurrentItem(int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
#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_catalog_actbartabs, 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 PlaceholderFragment extends Fragment {
protected ClogListAdapter2 clogListAdapter2;
protected ArrayList<String[]> stringArrayList;
protected static String topic = null;
protected static String rName = null;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String EXTRA_ITEM_INFO = "com.dstudio.dvir.EXTRA_ITEM_INFO";
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;
rootView = inflater.inflate(R.layout.fragment_catalog, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
try {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
stringArrayList = Utils.getNamesList(super.getContext());
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
stringArrayList = Utils.getTopicsList(super.getContext(), rName);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3)
stringArrayList = Utils.getClassesList(super.getContext(), rName, topic);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4)
stringArrayList = Utils.getFilesList(super.getContext());
} catch (Throwable t) {
Toast.makeText(super.getContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
if (savedInstanceState != null) {
String[] values = savedInstanceState.getStringArray("myKey");
if (values != null) {
stringArrayList = ClogListAdapter2.bmListFromArray(values);
}
} else if (stringArrayList == null) {
stringArrayList = new ArrayList<String[]>();
}
clogListAdapter2 = new ClogListAdapter2(super.getContext(), stringArrayList, getArguments().getInt(ARG_SECTION_NUMBER));
ListView listV = (ListView) rootView.findViewById(R.id.listView);
listV.setAdapter(clogListAdapter2);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
rName = null;
else rName = clogListAdapter2.getItem(position)[0];
topic = null;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
topic = null;
else topic = clogListAdapter2.getItem(position)[0];
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
Intent intent = new Intent(parent.getContext(), AudioPlayerActivity.class);
intent.putExtra(EXTRA_ITEM_INFO, clogListAdapter2.getItem(position));
startActivityForResult(intent, 1);
}
((Catalog_actbartabs) getActivity()).setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER), true);
}
});
return rootView;
}
}
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 PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "page 1";
case 1:
return "page 2";
case 2:
return "page 3";
case 3:
return "page 4";
}
return null;
}
}
}
UPDATE
Working Solution From #AmeyShirke
I added the var _hasLoadedOnce= false; to the rest of the vars in PlaceholderFragment class:
public static class PlaceholderFragment extends Fragment {
protected ClogListAdapter2 clogListAdapter2;
protected ArrayList<String[]> stringArrayList;
protected View rootView;
protected static String topic = null;
protected static String rName = null;
private boolean _hasLoadedOnce= false;
//Rest of the code
}
Now All the data setting code is inside setUserVisibleHint() without changing _hasLoadedOnce so it look like this:
#Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
// we check that the fragment is becoming visible
if (isFragmentVisible_ && !_hasLoadedOnce) {
Log.i("visable: ", getArguments().getInt(ARG_SECTION_NUMBER)+"");
try {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
stringArrayList = Utils.getNamesList(super.getContext());
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
stringArrayList = Utils.getTopicsList(super.getContext(), rName);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3)
stringArrayList = Utils.getClassesList(super.getContext(), rName, topic);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4)
stringArrayList = Utils.getFilesList(super.getContext());
} catch (Throwable t) {
Toast.makeText(super.getContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
clogListAdapter2 = new ClogListAdapter2(super.getContext(), stringArrayList, getArguments().getInt(ARG_SECTION_NUMBER));
ListView listV = (ListView) rootView.findViewById(R.id.listView);
listV.setAdapter(clogListAdapter2);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: 23/12/2016 remember to also give the needed info to get the asked next category
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
rName = null;
else rName = clogListAdapter2.getItem(position)[0];
topic = null;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
topic = null;
else topic = clogListAdapter2.getItem(position)[0];
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
Intent intent = new Intent(parent.getContext(), AudioPlayerActivity.class);
intent.putExtra(EXTRA_ITEM_INFO, clogListAdapter2.getItem(position));
startActivityForResult(intent, 1);
}
((Catalog_actbartabs) getActivity()).setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER), true);
}
});
//Notify that _hasLoadedOnce = true; is now gone
}
}
}
I also added the line mViewPager.setOffscreenPageLimit(3); in the activity's onCreate() because if I chose to go directly to the forth tab after the first filtering it wouldn't filter it, so that way the activity will filter it correctly.
This is default behaviour of ViewPager. To load only single tab use:
mViewPager.setOffscreenPageLimit(1);
If that doesnt work, then you have to create your own sub-class of ViewPager and override the below method:
private boolean _hasLoadedOnce= false; // your boolean field
#Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
// we check that the fragment is becoming visible
if (isFragmentVisible_ && !_hasLoadedOnce) {
//your code here
_hasLoadedOnce = true;
}
}
}
I want to load category and products like the image shown:
frag
/**
* 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) {
Category ctID = mSubCategory.get(position);
int id = ctID.getCategory_id();
return PlaceholderFragment.newInstance(getBaseContext(),id);
}
#Override
public int getCount() {
// Set number of fragments to be created
if(SubCategoriesCount == 0) {
Category ct;
ct = mSubCategory.get(0);
if (ct != null)
return 1;
}
return SubCategoriesCount;
}
}
Creating Fragment using newInstance with different Data.
PlaceholderFragment.java
public class PlaceholderFragment extends Fragment {
private static final String FragmentCategoryID = "CategoryID";
private static Context cTx;
private static String catName;
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(Context ctx, int id){
PlaceholderFragment fragment = new PlaceholderFragment();
cTx = ctx;
Log.d("New Fragment Created ", ":" + id );
Bundle args = new Bundle();
args.putInt(FragmentCategoryID, id);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_category_products_view, container, false);
RealmResults<Product> ProductList;
ProductList = GetProducts(getArguments().getInt(FragmentCategoryID));
Log.d("Fragment Arguments", "" + getArguments().getInt(FragmentCategoryID));
GridView gv = (GridView) rootView.findViewById(R.id.gridViewFrg);
gv.setAdapter(new AdapterRealmProduct(getActivity(), R.layout.grid_view_main, ProductList, true));
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(FragmentCategoryID))+ ":::"+catName);
return rootView;
}
private RealmResults<Product> GetProducts(int CategoryID){
RealmConfiguration realmConfigs;
realmConfigs = new RealmConfiguration.Builder(getActivity()).build();
Realm realmtm = Realm.getInstance(realmConfigs);
Category camt = realmtm.where(Category.class).equalTo("category_id", CategoryID).findFirst();
catName = camt.getName();
RealmResults<Product> results = realmtm.where(Product.class).equalTo("category_id", CategoryID).findAll();
try{
if(results != null && results.isValid()) {
return results;
}
}catch (IllegalStateException e){
e.printStackTrace();
}finally {
//realmtm.close();
}
return results;
}
}
It loads creates multiple fragments as value of SubCategoriesCount. But data in all fragments is same. Means All gridViews on all fragments have same grid data.
textView.setText(getString(R.string.section_format, getArguments().getInt(FragmentCategoryID))+ ":::"+catName);
CategoryName and ID displays.. but data does not change...
it might be Realm data. how to handle realm handle in different activitis.
there was repeated data in realm. So there is no problem in above code. I didn't notice what is coming to realm database.
I have one list of elements and one AbsListView. How I can load my elements of list just when I scroll?
this is my list: private List<Database_elem> database_elemList = new ArrayList<Database_elem>();
public class PlacesFragment extends Fragment implements AbsListView.OnItemClickListener {
// 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;
private List<Database_elem> database_elemList = new ArrayList<Database_elem>();
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
ImageView imageView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private ListAdapter mAdapter;
// TODO: Rename and change types of parameters
public static PlacesFragment newInstance(String param1, String param2) {
PlacesFragment fragment = new PlacesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public PlacesFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// TODO: Change Adapter to display your content
// mAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
}
String[] test;
String text = "Central Park";
Date data = new Date();
String data_database = String.valueOf(data);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_place, container, false);
Context ctx = view.getContext();
DataBase dataBase = new DataBase(getActivity().getApplicationContext());
// SQLiteDatabase db = dataBase.getReadableDatabase();
Cursor cr = dataBase.getInformation(dataBase);
cr.moveToFirst();
// dataBase.onCreate(db);
// ctx.deleteDatabase(DataBase.TABLE_NAME);
final DetectionLocation detectionLocation = new DetectionLocation(ctx);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
Integer val = Integer.valueOf(prefs.getString("sync_frequency", ""));
String sync_status = String.valueOf(val);
dataBase.insertInformation(dataBase, "Guid", String.valueOf(detectionLocation.getLongitude()), String.valueOf(detectionLocation.getLatitude()), "Sincronizare", data, sync_status);
while (true) {
if (!cr.isLast()) {
database_elemList.add(new Database_elem(cr.getString(0), cr.getString(1), cr.getString(2), cr.getString(3), cr.getString(4), cr.getString(5)));
cr.moveToNext();
} else {
break;
}
}
test = new String[database_elemList.size()];
//System.out.println(cr.getString(1));
for (int i = 0; i < database_elemList.size(); i++) {
CustomListAdapter adapter = new CustomListAdapter(getActivity(), test, database_elemList.get(0).getLat() + " " + database_elemList.get(0).getLon(), database_elemList.get(0).getSync_date());
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(adapter);
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// DataBase dataBase = new DataBase(getActivity().getApplicationContext());
// Cursor cr = dataBase.getInformation(dataBase);
// cr.moveToFirst();
for (int i = 0; i < database_elemList.size(); i++) {
CustomListAdapter adapter = new CustomListAdapter(getActivity(), test, database_elemList.get(0).getLat() + " " + database_elemList.get(0).getLon(), database_elemList.get(0).getSync_date());
mListView = (AbsListView) view.findViewById(android.R.id.list);
mListView.setAdapter(adapter);
}
}
});
}
}
, val);
mListView.setOnItemClickListener(this);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
}
You could just use a CursorAdapter...