-2

Hello I am new in Android development as well in Stack Overflow. I well understand concept of asynctask from Tutorial. But I am still confused how can I use asynctask on my existing code.


I am using Json to fetch data from my server. So basically my app perform some data fetching and showing on layout. I want to use asynctask because in logcat my app's Choreographer keep telling me 250 frames skipping, and my application freeze for few seconds. So, Basically my UI Thread is busy with that and it's happen.

I have Two Activity

1) Main Activity

2) Team Activity

I am using Navigation Drawer in my activity. On the navigation I have Team in item list.

My Main Activity code:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{


private boolean doubleBackToExitPressedOnce;
private Handler mHandler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
        drawerLayout.setDrawerListener(toggle);
        toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


}

private final Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
        doubleBackToExitPressedOnce = false;
    }
};

@Override
protected void onDestroy()
{
    super.onDestroy();

    if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}


@Override
public void onBackPressed(){
   // DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    mHandler.postDelayed(mRunnable, 2000);


}

@Override
public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.nav_drawer, menu);
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem){
    int id = menuItem.getItemId();
    if(id == R.id.action_settings){
        return true;
    }
    return super.onOptionsItemSelected(menuItem);

}

public boolean onNavigationItemSelected(MenuItem menuItem){
    int id = menuItem.getItemId();
    if(id == R.id.home1){
        Intent searchIntent = new Intent(MainActivity.this,Home.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.service1){
        Intent searchIntent = new Intent(MainActivity.this,OurService.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.team1){
        Intent searchIntent = new Intent(MainActivity.this,Team.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.port1){
        Intent searchIntent = new Intent(MainActivity.this,OurPort.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.price1){
        Intent searchIntent = new Intent(MainActivity.this,Price.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.contact1){
        Intent searchIntent = new Intent(MainActivity.this,Contact.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.location){
        Intent searchIntent = new Intent(MainActivity.this,OurLocation.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.facebook){
        Intent searchIntent = new Intent(MainActivity.this,OurFacebook.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }
    else if(id == R.id.linkedin){
        Intent searchIntent = new Intent(MainActivity.this,OurLinkedin.class);
        startActivity(searchIntent);
        overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
    }

    DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerLayout.closeDrawer(GravityCompat.START);
    return true;
}
}

My Team Activity code:

public class Team extends AppCompatActivity { 

private RecyclerView recyclerView;
private TeamAdapter adapter;
private List<TeamAlbum> albumList;
private TeamAlbum teamAlbum;
ProgressDialog pd;


@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_team);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    final CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
  
    initViews();

}
    public class GridSpacingItemDecoration extends 
    RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }


    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }


}


private int dpToPx(int dp) {
    Resources r = getResources();
    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}

@Override
public void onBackPressed(){
  Intent intent = new Intent(this,MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    return;
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem){
    int id = menuItem.getItemId();

    if(id == R.id.action_settings){

        return true;
    }
    return super.onOptionsItemSelected(menuItem);

}


private void initViews(){


    pd = new ProgressDialog(this);
    pd.setMessage("Fetching Data....");
    pd.setCancelable(false);
    pd.show();

    try {
        Glide.with(this).load(R.drawable.te).into((ImageView) findViewById(R.id.backdrop));
    } catch (Exception e) {
        e.printStackTrace();
    }
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    albumList = new ArrayList<>();
    adapter = new TeamAdapter(this, albumList);

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);

    loadJSON();

}

private  void loadJSON(){




    try{
        Client client = new Client();
        Service service = client.getClient().create(Service.class);

        Call<TeamResponse> call = service.getAlbums();
        call.enqueue(new Callback<TeamResponse>() {
            @Override
            public void onResponse(Call<TeamResponse> call, Response<TeamResponse> response) {
                List<TeamAlbum> iteams = response.body().getAlbums();
                recyclerView.setAdapter(new TeamAdapter(getApplicationContext(), iteams));
                pd.dismiss();
            }

            @Override
            public void onFailure(Call<TeamResponse> call, Throwable t) {
                Log.d("Error", t.getMessage());
                Toast.makeText(Team.this,"Error Fetching Data!", Toast.LENGTH_SHORT).show();
                pd.dismiss();

            }
        });
    }
    catch (Exception e){
        Log.d("Error", e.getMessage());
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }

}
}

So, I have two methods in my Team Activity

1. initViews() 2. loadJson()

So, as you can see in my code I am calling loadJson() method in initViews() method and initViews() in onCreate() of my activity.

But I don't know how can I use asynctask with these two methods.

Please somebody help me out how can I implement asynctask with explanation. Thanks in Advance.

Community
  • 1
  • 1
  • 1
    Maybe you can take a look [here](https://stackoverflow.com/questions/47575399/doinbackground-not-updating-variable/) – elmorabea Dec 01 '17 at 10:15
  • @MahmoudElmorabea: But I am just confused with which part of code will go in which method of AsyncTask. – Cloudformation Dec 01 '17 at 10:17
  • @MahmoudElmorabea I am trying to figure out how can I make structure with Asynctask. because I am confuse with my methods which method I should put in Asynctask and which is not.... can you please demonstrate an example with my Team Activity code. – Cloudformation Dec 01 '17 at 10:20

2 Answers2

1

It could be something like that, let me know if you need more clarification

class FantasticAsyncTask extends AsyncTask<Void, Void, TeamResponse> {

    @Override
    protected void onPreExecute() {
        pd = new ProgressDialog(YourActivity.this);
        pd.setMessage("Fetching Data....");
        pd.setCancelable(false);
        pd.show();
    }

    @Override
    protected TeamResponse doInBackground(final Void... voids) {
        Service service = client.getClient().create(Service.class);
        Call<TeamResponse> call = service.getAlbums();
        TeamResponse response = call.execute();
        return response;
    }

    @Override
    protected void onPostExecute(final TeamResponse response) {
        List<TeamAlbum> iteams = response.body().getAlbums();
        recyclerView.setAdapter(new TeamAdapter(getApplicationContext(), iteams));
        pd.dismiss();
    }
}
elmorabea
  • 3,243
  • 1
  • 14
  • 20
1
class LoadAlbumsAsync extends AsyncTask<Void, Void, List<TeamAlbum>>{

 @Override
    protected void onPreExecute() {
        pd = new ProgressDialog(this);
    pd.setMessage("Fetching Data....");
    pd.setCancelable(false);
    pd.show();
    }

    @Override
    protected List<TeamAlbum> doInBackground(Void... voids) {
        Client client = new Client();
        Service service = client.getClient().create(Service.class);

// Note: modify getAlbums() retrofit method to return the TeamResponse obj directly.
        TeamResponse response = service.getAlbums();
        return response.getAlbums();
    }

@Override
protected void onPostExecute(List<TeamAlbum> list) {
    recyclerView.setAdapter(new TeamAdapter(getApplicationContext(), list));
    pd.dismiss();
}

}

private  void loadJSON(){
       new LoadAlbumsAsync().execute();
}

Hope this helps..

GRK
  • 204
  • 1
  • 6