0

Hi I have an Activity which user open upon click on a TAB. Actually I have a ViewGroup and Tabactivity as Main Activity. on the first tab I have three activity.

Now in an activity I have a list view (custom) populating on Oncreate and a ViewFlipper (only adding view) in Onresume using AsyncTask.

In that asynctask in Pre Execute if I add code for loader it gives error. Also If I do not show the loader the screen is freezing until the Async task finished.

I actually want to load the list view first and then in background run the async task with a loader. Also does not want to freeze the screen.

Here Is My Acivity

package thai.phrasi.ctech.com.phrasi;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
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.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;


public class WordActivity extends ActionBarActivity {

    categories category_obj;
    word word_obj;
    wordDB wordDb;
    WordAdapter adapter;
    MediaPlayer mPlayer;
    boolean doubleBackToExitPressedOnce = false;
    public static ViewFlipper viewFlipper;
    public View view;
    private static ProgressDialog pleaseWaitDialog;

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

        viewFlipper = new ViewFlipper(this);
        viewFlipper.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));



        TextView txt = (TextView) findViewById(R.id.phraseListHeading);
        Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");

        String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase();

        wordDb = new wordDB(getApplicationContext());
        getAllWords();

        //asyncLoadWordList task2 = new asyncLoadWordList(getApplicationContext());
        //task2.execute();


        txt.setTypeface(font);
        txt.setText(categoryName);


        ListView wordListView;
        wordListView = (ListView)findViewById(R.id.list_view_word);
        wordListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Object o = parent.getItemAtPosition(position);
                word_obj = (word) o;
                if(Integer.valueOf(word_obj.getCategoryId())>=0) {
                    Intent myIntent = new Intent(WordActivity.this, WordDetailsActivity.class);
                    myIntent.putExtra("word_obj", word_obj);
                    myIntent.putExtra("position",position);
                    myIntent.putExtra("currentClickedId", word_obj.getCsvWordId().toString());
                    myIntent.putExtra("favouriteFlag",0);
                    myIntent.putExtra("searchFlag",0);
                    myIntent.putExtra("searchString", "");
                    WordActivity.this.startActivity(myIntent);


                }

            }
        });

        ImageView backButton = (ImageView) findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent backIntent = new Intent(WordActivity.this, CategoryActivity.class);
                View vw = FirstGroup.group.getLocalActivityManager().startActivity("CategoryActivity", backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
                FirstGroup.group.replaceView(vw);
                viewFlipper.removeAllViews();
                System.runFinalization();
                Runtime.getRuntime().gc();
                System.gc();
            }
        });


    }

    @Override
    protected void onPause() {
        super.onPause(); // Don't forget this line
        stop();
    }

    public void stop(){
        mPlayer=adapter.getMPlayerInstace();
        if(mPlayer!=null){
            mPlayer.stop();
            mPlayer.release();
        }
    }

    @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_word, 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);
    }

    protected void onResume(){
        super.onResume();

        new Thread(new Runnable() {
            public void run(){
                //All your heavy stuff here!!!
                category_obj = (categories) getIntent().getSerializableExtra("category_obj");
                if(viewFlipper.getChildCount() == 0) {
                    asyncFlipperView task = new asyncFlipperView(getApplicationContext());
                    task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
                }
            }
        }).start();



    }


    public void getAllWords(){

        category_obj = (categories) getIntent().getSerializableExtra("category_obj");
        ArrayList<word> words = new ArrayList<word>();
        Cursor row =  wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
        words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
        words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
        row.moveToFirst();
        while (!row.isAfterLast()) {
            //Log.d("Data id: ", row.getString(2));
            words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5), row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
            row.moveToNext();
        }
        row.close();

        adapter = new WordAdapter(WordActivity.this, words);

        ListView listView = (ListView) findViewById(R.id.list_view_word);
        listView.setAdapter(adapter);

    }

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

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

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root));

        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Double tap back button to exit.");

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();


        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }




    public class asyncLoadWordList extends  AsyncTask<ArrayList<word>, Void, ArrayList<word>>{


        private Context mContext;
        public asyncLoadWordList(Context context) {
            mContext = context;

        }


        protected void onPreExecute() {
            //Start the splash screen dialog
           /* if (pleaseWaitDialog == null)
                pleaseWaitDialog= ProgressDialog.show(WordActivity.this,
                        "PLEASE WAIT",
                        "Getting results...",
                        false);
                        */

        }



        @Override
        protected ArrayList<word> doInBackground(ArrayList<word>... params) {

            wordDb = new wordDB(mContext);
            category_obj = (categories) getIntent().getSerializableExtra("category_obj");
            ArrayList<word> words = new ArrayList<word>();
            Cursor row =  wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
            words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
            words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
            row.moveToFirst();
            while (!row.isAfterLast()) {
                //Log.d("Data id: ", row.getString(2));
                words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
                row.moveToNext();
            }
            row.close();

            return words;
        }
        protected void onPostExecute(ArrayList<word> result) {

            adapter = new WordAdapter(WordActivity.this, result);

            ListView listView = (ListView) findViewById(R.id.list_view_word);
            listView.setAdapter(adapter);


            if (pleaseWaitDialog != null) {
                pleaseWaitDialog.dismiss();
                pleaseWaitDialog = null;

            }


            asyncFlipperView task = new asyncFlipperView(getApplicationContext());
            task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
        }
    }

    public class asyncFlipperView extends AsyncTask<String, Void, String[]> {


        String categoryId;
        private Context mContext;
        wordDB wordDb;
        Cursor row;
        JSONObject json;
        View view;

        //private ProgressDialog dialog = new ProgressDialog(WordActivity.this);

        public asyncFlipperView(Context context) {
            mContext = context;
        }


        protected void onPreExecute() {
            //Start the splash screen dialog


        }

        @Override
        protected String[] doInBackground(String... params) {

            categoryId = params[0];


            json = new JSONObject();
        /*do application level task*/
            GlobalState state = ((GlobalState) mContext);
            state.doAction();
        /*Ends*/

            wordDb = new wordDB(mContext);
            row = wordDb.selectWordList(categoryId);
            Log.d("Tag: search result", row.getString(2).toString());
            return new String[]{categoryId};
        }

        protected void onPostExecute(String[] result) {

            categoryId = result[0];
            ImageView phraseImage = null;
            Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
            row.moveToFirst();
            while (!row.isAfterLast()) {


            /*phrase Image*/
                Integer fileNameLength = row.getString(5).toString().length();
                String fileName = row.getString(5).toString();
                String imageFile = fileName.substring(0, fileNameLength - 4);

                //viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
                LayoutInflater inflater = getLayoutInflater();
                view = inflater.inflate(R.layout.word_details_flipper_view, null);

                TextView tv = (TextView) view.findViewById(R.id.text_english);
                tv.setTypeface(font);
                tv.setText(row.getString(2).toString());


                String picName = row.getString(6).toString();
                picName = picName.replace(".png", "");

                Uri url1 = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + picName);
                ImageView backgroundImage = (ImageView) view.findViewById(R.id.backgroundImage);
                Picasso.with(mContext).load(url1).fit().centerCrop().into(backgroundImage);

                TextView tvTranslated = (TextView) view.findViewById(R.id.translated_phrase);
                tvTranslated.setTypeface(font);
                tvTranslated.setText(row.getString(3).toString());

                TextView pronounce = (TextView) view.findViewById(R.id.pronounce);
                pronounce.setTypeface(font);
                pronounce.setText(row.getString(4).toString());

                phraseImage = (ImageView) view.findViewById(R.id.phrase_image);

                Uri url = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + imageFile);
                Picasso.with(mContext).load(url).resize(576, 888).into(phraseImage);

                view.setTag(R.string.csvId, row.getString(0).toString());
                viewFlipper.addView(view);
                row.moveToNext();
            }
            row.close();


        }

        private Context getDialogContext() {
            Context context;
            if (getParent() != null) context = getParent();
            else context = WordActivity.this;
            return context;
        }


    }


}
Parangan
  • 148
  • 1
  • 15
  • 1
    please paste code. – Shubham AgaRwal Apr 05 '16 at 07:08
  • I have added the code here! – Parangan Apr 05 '16 at 07:12
  • you want to show loader.. and want to other work too? – Jishant Apr 05 '16 at 07:23
  • On create I want to Call the function which create a list view. Then in OnResume I want to populate the viewFlippers. That what I have done. But when I opens the app It get freeze for a while for the AsyncTask in Onresume. I do not want the screen to be freezed. – Parangan Apr 05 '16 at 07:27
  • you are using asynctask in on resume,, so of course when you will use progress dilog it will end when onpost will call... and why are you using Runnable thread in onresume? – Jishant Apr 05 '16 at 07:35

0 Answers0