Issue
in my application, i have main_activity with a FrameLayout
, and a Fragment
public class Fragment1 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
return view;
}
public class StartAsyncTask extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... voids) {
Log.e("startAsyncTask", "start");
return null;
}
}
}
I need to call the AsyncTask
from the MainActivity
,
so i use:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.replace(R.id.fragment, fragment1).commit();
new Fragment1.StartAsyncTask().execute();
}
but it dosn't work. new Fragment1.StartAsyncTask().execute();
is in red with (is not enclosing class) error.
Solution
You Can Do Like this, From your MainActivity You can Call your AsyncTask indirectly
ublic class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
BlankFragment fragment1 = new BlankFragment();
fragmentTransaction.replace(R.id.activity_main, fragment1).commit();
fragment1.startASycnc();
}
}
And Your Fragment Looks Like This:
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
public void startASycnc() {
new StartAsyncTask().execute();
}
public class StartAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
Log.e("startAsyncTask", "start");
return null;
}
}
}
Answered By - Rakshith Kumar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.