Not able to initialize parse two times in two another activity to call data from two classes of parse and put them in different list views. at second time when opening contact activity by action item then the app stops
Main Activity.java
public class MainActivity extends ActionBarActivity {
private CountryAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.initialize(this, "0FgKGokshcBPQSpY**********", "f1hZ9W4c***********");
ParseObject.registerSubclass(Country.class);
mAdapter = new CountryAdapter(this, new ArrayList<Country>());
ListView mListView = (ListView) findViewById(R.id.country_list);
mListView.setAdapter(mAdapter);
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_contact) {
Intent i = new Intent(this, ContactActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateData() {
ParseQuery<Country> query = ParseQuery.getQuery(Country.class);
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Country>() {
#Override
public void done(List<Country> countrys, com.parse.ParseException e) {
if (countrys != null) {
mAdapter.clear();
for (int i = 0; i < countrys.size(); i++) {
mAdapter.add(countrys.get(i));
}
}
}
});
}
}
ContactActivity.java
public class ContactActivity extends ActionBarActivity {
private ContactAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
Parse.initialize(this, "0FgKGoksh********************", "f1hZ9W4cKO2Ag*******************");
ParseObject.registerSubclass(Contact.class);
mAdapter = new ContactAdapter(this, new ArrayList<Contact>());
ListView mListView = (ListView) findViewById(R.id.contact_list);
mListView.setAdapter(mAdapter);
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_contact, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void updateData() {
ParseQuery<Contact> query = ParseQuery.getQuery(Contact.class);
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Contact>() {
#Override
public void done(List<Contact> contact, com.parse.ParseException e) {
if (contact != null) {
mAdapter.clear();
for (int i = 0; i < contact.size(); i++) {
mAdapter.add(contact.get(i));
}
}
}
});
}
}
You should initialize parse in a class which extends Application class like this
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(this, "xxxxxxxxxxxx", "xxxxxxxxx");
}
}
and put application class name in manifest file like
<application
android:name=".MyApplication" />
Related
My problem is that i have a recyclerview implemented on a fragment that uses Room. RecyclerView, Adapter and Database need to be together in one class (i guess).
My problem is that if I put them into StudentActivity,
recyclerView = findViewById(R.id.SubjectRecyclerView);
will be null, because the Fragment won't be available by the time this function called.
If i put them into StudentSubjectsFragment,
everything would be good, but NewSubjectDialogFragment tells me that StudentActivity needs to implement NewSubjectDialogFragment because of this:
private NewSubjectDialogListener listener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentActivity activity = getActivity();
if (activity instanceof NewSubjectDialogListener) {
listener = (NewSubjectDialogListener) activity;
} else {
throw new RuntimeException("Activity must implement the NewSubjectDialogListener interface!");
}
}
If at the
FragmentActivity activity = getActivity();
line somehow I would be able to call the getActivity() function of StudentSubjectsFragment class, I think it would solve my problem, and then the class that would implement the NewSubjectDialogFragment would be the StudentSubjectsFragment instead of StudentActivity.
I tried this:
FragmentActivity activity = getActivity().getSupportFragmentManager().findFragmentByTag("StudentSubjectsFragment").getActivity();
But activity is null.
StudentSubjectsFragment class:
public class StudentSubjectsFragment extends Fragment
implements NewSubjectDialogFragment.NewSubjectDialogListener,
SubjectAdapter.SubjectClickListener {
public static final String TAG = "StudentSubjectsFragment";
private RecyclerView recyclerView;
private SubjectAdapter adapter;
private SubjectDatabase database;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.student_subjects, container, false);
FloatingActionButton fab = rootView.findViewById(R.id.fabbb);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new NewSubjectDialogFragment().show(getActivity().getSupportFragmentManager(), NewSubjectDialogFragment.TAG);
}
});
database = Room.databaseBuilder(
getActivity(),
SubjectDatabase.class,
"subject-list"
).build();
recyclerView = rootView.findViewById(R.id.SubjectRecyclerView);
adapter = new SubjectAdapter(this);
loadItemsInBackground();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return rootView;
}
private void loadItemsInBackground() {
new AsyncTask<Void, Void, List<Subject>>() {
#Override
protected List<Subject> doInBackground(Void... voids) {
return database.subjectDao().getAll();
}
#Override
protected void onPostExecute(List<Subject> subjects) {
adapter.update(subjects);
}
}.execute();
}
#Override
public void onItemChanged(final Subject item) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
database.subjectDao().update(item);
return true;
}
#Override
protected void onPostExecute(Boolean isSuccessful) {
Log.d("StudentActivity", "Subject update was successful");
}
}.execute();
}
#Override
public void onItemDeleted(final Subject item) {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
database.subjectDao().deleteItem(item);
return true;
}
}.execute();
}
#Override
public void onSubjectCreated(final Subject newItem) {
new AsyncTask<Void, Void, Subject>() {
#Override
protected Subject doInBackground(Void... voids) {
newItem.id = database.subjectDao().insert(newItem);
return newItem;
}
#Override
protected void onPostExecute(Subject subject) {
adapter.addItem(subject);
}
}.execute();
}
}
StudentActivity class:
public class StudentActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
ViewPager vpProfile = findViewById(R.id.vpStudent);
vpProfile.setAdapter(new StudentPagerAdapter(getSupportFragmentManager()));
}
}
NewSubjectDialogFragment class:
public class NewSubjectDialogFragment extends DialogFragment {
private EditText nameEditText;
public static final String TAG = "NewSubjectDialogFragment";
public interface NewSubjectDialogListener {
void onSubjectCreated(Subject newItem);
}
private NewSubjectDialogListener listener;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentActivity activity = getActivity().getSupportFragmentManager().findFragmentByTag("StudentSubjectsFragment").getActivity();
if (activity instanceof NewSubjectDialogListener) {
listener = (NewSubjectDialogListener) activity;
} else {
throw new RuntimeException("Activity must implement the NewSubjectDialogListener interface!");
}
}
private boolean isValid() {
return nameEditText.getText().length() > 0;
}
private Subject getSubject() {
Subject subject = new Subject();
subject.name = nameEditText.getText().toString();
return subject;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(requireContext())
.setTitle(R.string.new_subject_item)
.setView(getContentView())
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (isValid()) {
listener.onSubjectCreated(getSubject());
}
}
})
.setNegativeButton(R.string.cancel, null)
.create();
}
private View getContentView() {
final View contentView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_new_subject_item, null);
nameEditText = contentView.findViewById(R.id.SubjectNameEditText);
return contentView;
}
}
I think there is a way to change NewSubjectDialogFragment to work with StudentSubjectsFragment but I am a beginner in android developing and don't know how to do it.
Solution of Mike M. worked perfectly.
The working code parts are the following:
NewSubjectDialogFragment:
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fragment fragment = getParentFragment();
if (fragment instanceof NewSubjectDialogListener) {
listener = (NewSubjectDialogListener) fragment;
} else {
throw new RuntimeException("Fragment must implement the NewSubjectDialogListener interface!");
}
}
StudentSubjectFragment:
FloatingActionButton fab = rootView.findViewById(R.id.fabbb);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new NewSubjectDialogFragment().show(getChildFragmentManager(), NewSubjectDialogFragment.TAG);
}
});
Hi I developed one app where I want to display folder wise all photos from storage. I implemented the code for it but the problem is that when activity is created it display black blank screen for 5 sec and then display all folder.
Here is my code:
public class ImageWithFolder extends AppCompatActivity implements AdapterView.OnItemClickListener {
List<GridViewItem> gridItems = new ArrayList<GridViewItem>();
String redirect;
GridView gridView;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imagefolder);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
Intent ii = getIntent();
redirect = ii.getStringExtra("next_activity");
gridView = (GridView) findViewById(R.id.gridView);
setGridAdapter();
}
private void setGridAdapter() {
createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
}
private void createGridItems(String directoryPath) {
File[] files = new File(directoryPath).listFiles(new ImageFileFilter());
for (File file : files) {
if (file.isDirectory()) {
if (file.listFiles((new DirFilter())).length > 0) {
createGridItems(file.getAbsolutePath());
}
if (file.listFiles((new ImageFilter())).length > 0) {
gridItems.add(new GridViewItem(file.getAbsolutePath(), true, null));
}
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isImageFile(String filePath) {
if (filePath.endsWith(".jpg") || filePath.endsWith(".png") || filePath.endsWith(".jpeg")) {
return true;
}
return false;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (redirect.equalsIgnoreCase("1")) {
Intent ii = new Intent(ImageWithFolder.this, SelectPhotos.class);
ii.putExtra("path", gridItems.get(i).getPath());
startActivity(ii);
} else if (redirect.equalsIgnoreCase("2")) {
Intent ii = new Intent(ImageWithFolder.this, AlbumSelectPhotos.class);
ii.putExtra("path", gridItems.get(i).getPath());
startActivity(ii);
}
}
private class ImageFileFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
private class ImageFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
private class DirFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
return false;
}
}
}
I am not getting what is going wrong with the code.
Can anyone give solution regarding black screen appear at the first time.
Thanks in advance.
Put your read file method in async..
Call Aysnc:
new LoadData().execute()
public class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
}
}
If you are comfortable with RxJava then use Observal, This is the best soluton.
I've a listview with some static data. When the refresh activity is done, some data need to be updated in listview. The problem is once the refresh gets completed, the new items are not updated.
MainActivity.class
public class MainActivity extends ActionBarActivity {
SwipeRefreshLayout swipeLayout;
String[] players = {"Dravid","Ganguly","Sachin","Irfan pathan","Balaji","Bhuvi","Praveen"};
ListView listView;
ArrayAdapter<String> adapter = null;
ArrayList al = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
for (int i =0; i<players.length; i++)
{
Bean b = new Bean();
b.setName(players[i]);
al.add(b);
}
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,players);
listView.setAdapter(adapter);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeLayout.setRefreshing(true);
new updateItems().execute();
}
});
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
class updateItems extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
String[] newitems = {"Ishant sharma","Ramesh power","Kaif"};
// adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,newitems);
for (int j=0;j<newitems.length;j++)
{
Bean bb = new Bean();
bb.setName(newitems[j]);
al.add(bb);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
listView.invalidateViews();
}
});
swipeLayout.setRefreshing(false);
}
}
#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);
}
}
Bean.class
public class Bean {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Where i am making mistake?
This is the adapter that you're setting initially :
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,players);
Inside your doInBackground() method, you update the a1 ArrayList but your players Array on which the adapter depends remains the same hence no changes are reflected in the listview even when you do adapter.notifyDataSetChanged().
Secondly, the onPostExecute method runs on the ui thread so you do not need to do that explicitly.
I'm writing a tip app where the user selects a check, and then on the second activity the subtotal is displayed. However, I'm completely lost on how I display my subtotal. I have a getSubtotal() method but I don't know how to call it.
First Activity
public class TableListActivity extends Activity {
private ListView mListView;
private TableListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_list);
// Find the ListView, create an adapter that reads our list of checks,
// and connect the two
mListView = (ListView)findViewById(R.id.listView);
mAdapter = new TableListAdapter(this, DataStore.CHECKS);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent (TableListActivity.this, PayCheckActivity.class);
intent.putExtra(PayCheckActivity.Extra_check, arg2);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.table_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
// TODO do stuff here
Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}}
Second Activity
public class PayCheckActivity extends Activity{
String Thank;
Button Sign;
Button fifteen;
Button eighteen;
Button twenty;
String sample;
public static final String Extra_check= "abc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paycheck);
Sign = (Button)findViewById(R.id.Sign);
fifteen= (Button)findViewById(R.id.fifteen);
eighteen= (Button)findViewById(R.id.eighteen);
twenty= (Button)findViewById(R.id.twenty);
Sign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank You", Toast.LENGTH_LONG);
msg.show();
}});
fifteen.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank Yolllllu", Toast.LENGTH_LONG);
msg.show();
}});}}
Check.java
public class Check {
private long id;
private String tableName;
private ArrayList<MenuItem> mItems = new ArrayList<MenuItem>();
private boolean hasBeenSigned = false;
public static class MenuItem {
public String name;
public Amount cost;
public MenuItem(String itemDescription, double cost) {
this.name = itemDescription;
this.cost = new Amount(cost);
}
}
public Check(long id, String tableName) {
this.id = id;
this.tableName = tableName;
}
public long getId() {
return id;
}
#Override
public String toString() {
// The ArrayAdapter uses toString to get the text to display in the list item
// We override toString here to display the table name
return tableName;
}
public void addItem(String itemDescription, double cost) {
mItems.add(new MenuItem(itemDescription, cost));
}
public String getTableName() {
return tableName;
}
public Amount getSubtotal() {
double total = 0;
for (MenuItem item : mItems) {
total += item.cost.getRawValue();
}
return new Amount(total);
}
public void markAsSigned() {
hasBeenSigned = true;
}
public int getItemCount() {
return mItems.size();
}
public MenuItem getMenuItemAt(int index) {
return mItems.get(index);
}}
Just a quick hint: You are sending some data to the second activity via Intent (onItemClick). In the second activity in onCreate, you can pick this data and call your getSubtotal method. Since it's not quite clear, what "Check" does, it's up to you how to instantiate it:
public class PayCheckActivity extends Activity{
// ...
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if(intent != null) {
String value = intent.getStringExtra(PayCheckActivity.Extra_check);
Check check = .....
check.getSubtotal()
}
}
// ...
}
I have a problem regarding with FragmentActivity and mutltiple Fragments inside a ViewPager.
In the FragmentActivity an object is loaded, with a AsyncTask which is used in all the other fragments. I have used the android:configChanges="orientation|keyboardHidden|keyboard" "hack" to make sure the object is only loaded once, even during a screen rotation.
However, now I would to like to display more infromation in landscape modus in one of the Fragments, so now that hack doesn't work.
I've tried implementing a AsyncLoader and the FragmentRetainInstanceSupport from the Android samples. But none of the things work:
1 - I can't get the FragmentRetainInstanceSupport get to work within the ViewPager, when I follow the sample code the onCreate() method isn't called in the worker-fragment
2 - The AsyncLoader crashes during a screen rotation...
Here is my code in which I (tried to) implement the AsyncLoader:
public class TeamActivity extends SherlockFragmentActivity implements LoaderManager.LoaderCallbacks<Response<Team>> {
ViewPager mPager;
PageIndicator mIndicator;
FragmentPagerAdapter mAdapter;
private final int MENU_FOLLOW = Menu.FIRST;
private final int MENU_UNFOLLOW = Menu.FIRST + 1;
Team team = null;
static int team_id;
public Team getTeam(){
return team;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
team_id = this.getIntent().getIntExtra("index", 0);
Log.d("Teamid",""+team_id);
getSupportLoaderManager().initLoader(0, null, this);//.forceLoad();
//getSupportLoaderManager().getLoader(0).startLoading();
//new getTeam().execute();
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(team != null) {
team.getNaam();
SharedPreferences keyValues = this.getSharedPreferences("teams_follow", Context.MODE_PRIVATE);
MenuItem menuItem_volg = menu.findItem(MENU_FOLLOW);
MenuItem menuItem_delete = menu.findItem(MENU_UNFOLLOW);
if(keyValues.contains(String.valueOf(team.getStartnummer()))) {
menuItem_volg.setVisible(false);
menuItem_delete.setVisible(true);
} else {
menuItem_volg.setVisible(true);
menuItem_delete.setVisible(false);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,MENU_UNFOLLOW,Menu.NONE, R.string.ab_verwijderen)
.setIcon(R.drawable.ic_action_delete)
.setVisible(false)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(0,MENU_FOLLOW,Menu.NONE, R.string.ab_volgen)
.setIcon(R.drawable.ic_action_star)
.setVisible(false)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Utils.goHome(getApplicationContext());
break;
case MENU_FOLLOW:
Utils.addFavoTeam(getApplicationContext(), team);
invalidateOptionsMenu();
break;
case MENU_UNFOLLOW:
Utils.removeFavoteam(getApplicationContext(), team.getID());
invalidateOptionsMenu();
break;
}
return super.onOptionsItemSelected(item);
}
class TeamFragmentAdapter extends FragmentPagerAdapter implements TitleProvider {
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
ArrayList<String> titels = new ArrayList<String>();
public TeamFragmentAdapter(FragmentManager fm) {
super(fm);
fragments.add(new TeamInformatieFragment());
titels.add("Informatie");
fragments.add(new TeamLooptijdenFragment());
titels.add("Routetijden");
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public String getTitle(int position) {
return titels.get(position);
}
}
private class getTeam extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
Response<Team> response;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TeamActivity.this,
"Bezig met laden", "Team wordt opgehaald...", true);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
cancel(true);
Utils.goHome(TeamActivity.this);
}
});
}
#Override
protected Void doInBackground(Void... arg0) {
if(!isCancelled())
response = api.getTeamByID(team_id);
return null;
}
#Override
protected void onPostExecute(Void result) {
if(Utils.checkResponse(TeamActivity.this, response)) {
setContentView(R.layout.simple_tabs);
team = response.getResponse();
mAdapter = new TeamFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
invalidateOptionsMenu();
progressDialog.dismiss();
}
}
}
public static class AppListLoader extends AsyncTaskLoader<Response<Team>> {
Response<Team> response;
public AppListLoader(Context context) {
super(context);
}
#Override public Response<Team> loadInBackground() {
response = api.getTeamByID(team_id);
return response;
}
#Override public void deliverResult(Response<Team> response) {
if (isReset()) {
return;
}
this.response = response;
super.deliverResult(response);
}
#Override protected void onStartLoading() {
if (response != null) {
deliverResult(response);
}
if (takeContentChanged() || response == null) {
forceLoad();
}
}
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
response = null;
}
}
private ProgressDialog progressDialog;
#Override
public Loader<Response<Team>> onCreateLoader(int arg0, Bundle arg1) {
progressDialog = ProgressDialog.show(TeamActivity.this,
"Bezig met laden", "Team wordt opgehaald...", true);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
finish();
}
});
return new AppListLoader(this);
}
#Override
public void onLoadFinished(Loader<Response<Team>> loader, Response<Team> response) {
//Log.d("Loader", "Klaar");
if(Utils.checkResponse(TeamActivity.this, response)) {
team = response.getResponse();
setContentView(R.layout.simple_tabs);
mAdapter = new TeamFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
invalidateOptionsMenu();
progressDialog.dismiss();
}
}
#Override
public void onLoaderReset(Loader<Response<Team>> arg0) {
//Utils.goHome(this);
}
}
Fragment (example):
public class TeamInformatieFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Team team = ((TeamActivity)this.getActivity()).getTeam();
//ERROR ON NEXT LINE AFTER SCREEN ROTATION:
getSherlockActivity().getSupportActionBar().setTitle(team.getNaam());
View view = inflater.inflate(R.layout.team_informatie, container, false);
return view;
}
}
The method is called from the fragments (with getActivity().getTeam()) but after a screen rotation getTeam() returns null;
I think the fragments are calling getTeam() too fast, before the variable team has been initialized(?)
Can you please help me?
Thank you!
This is probably not what you want to hear, but I recommend getting rid of
android:configChanges="orientation|keyboardHidden|keyboard"
It's an ugly hack, and a lot of the newer SDK elements like Loaders will break if you don't handle configuration changes correctly. Let Android handle the config changes, and design your code around that.