在AsyncTask中保存和读取对象

时间:2015-04-06 02:26:18

标签: java android android-asynctask

我是一名初学者,在编码方面,我遇到了一个已经写入android文件的对象的问题。那个对象(arraylist)来自一个api,我可以通过执行我的asynctask来连接互联网时填充我的文本视图。问题是,如果没有互联网连接,我希望asynctask从本地文件中提取数据。我的问题是我不确定将IF语句放入检查连接并从保存的文件中提取的最佳位置。任何帮助将不胜感激。

public class SearchFrag extends Fragment实现了View.OnClickListener {

final String TAG = "micgrams";

//INSTAGRAM AUTHENTICATION
private static final String CLIENT_ID = "e79ad9e2173443deb8eea89ef21b15e9";
private static final String CLIENT_SECRET = "d2d64643a7ec4595b4c871d28c59bbf3";
private static final String REDIRECT_URI = "http://clear.com/instagram/access-token";


boolean isConnected;
boolean newtworkBool;
Button search;
EditText searchText;
ConnectionTest connection;
Communicator comm;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.frag_search, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    connection = new ConnectionTest(getActivity());
    isConnected = connection.isConnectedToInternet();
    comm = (Communicator) getActivity();
    searchText = (EditText) getActivity().findViewById(R.id.searchInput);
    search = (Button) getActivity().findViewById(R.id.searchBtn);
    search.setOnClickListener(this);


}

@Override
public void onClick(View v) {

    Log.d(TAG, " CLICKED!");
    Log.d(TAG, "it's Working");

    //GETS VALUE OF SEARCHFIELD AND SENDS IT TO
    String result = searchText.getText().toString();

    Log.d(TAG, "result: " + result);

    URL searchForURL = null;
    try {
        isConnected = connection.isConnectedToInternet();
        searchForURL = new URL((makeUrl(result)));

        if (isConnected) {
            Log.d(TAG, "New CONNECTED!");
            Toast.makeText(getActivity(), " Connected!", Toast.LENGTH_LONG).show();
            new getInstadata().execute(searchForURL);

        } else if (!isConnected) {


                Log.d(TAG, "NO CONNECTION FOUND");
                Toast.makeText(getActivity(), " NO CONNECTION FOUND!", Toast.LENGTH_LONG).show();
                FileInputStream fis = getActivity().openFileInput("myFile");
            new getInstadata().execute(searchForURL);


            }


    } catch (Exception e) {

    }
}

//ASYNCTASK CLASS THAT PARSES THE DATA FROM INSTAGRAM
public class getInstadata extends AsyncTask<URL, Integer, JSONObject> {

    final String TAG = "realfragments ASYNCTASK";
    //DECLARES THE VARIABLES FROM THE ITEMS THAT WILL BE RECEIVE FROM INSTAGRAM
    public ArrayList<String> pics = new ArrayList<String>();
    public ArrayList<String> user = new ArrayList<String>();
    public ArrayList<String> fullname = new ArrayList<String>();
    public ArrayList<Bitmap> searchPic = new ArrayList<Bitmap>();

    @Override
    protected JSONObject doInBackground(URL... urls) {


        String jsonString = "";
        for (URL searchURL : urls) {
            try {
                URLConnection conn = searchURL.openConnection();
                jsonString = IOUtils.toString(conn.getInputStream());
                newtworkBool = true;
                break;
            } catch (Exception e) {
                Log.e(TAG, "Could not establish URLConnection for " + searchURL.toString());

            }
        }

        Log.d(TAG, "Received Data: " + jsonString);

        JSONObject instagInfo;
        JSONArray instaArray;
        MicSearch readMic;

        try {
            instagInfo = new JSONObject(jsonString);

            //TARGETS INSTAGRAM DATA ARRAY
            instaArray = instagInfo.getJSONArray("data");
            String thisPic;
            String thisBio;
            String thisUser;
            for (int i = 0; i < 5; i++) {

                instagInfo = instaArray.getJSONObject(i);

                //GETS IMAGE FROM INSTAGRAM AND ADD IT TO THE ARRAYLIST
                thisPic = instagInfo.getJSONObject("images").getJSONObject("standard_resolution").getString("url");
                pics.add(thisPic);

                //GETS FULL NAME FROM INSTAGRAM AND ADD IT TO THE ARRAYLIST
                thisBio = instagInfo.getJSONObject("user").getString("full_name");
                fullname.add(thisBio);

                //GETS USER NAME FROM INSTAGRAM AND ADD IT TO THE ARRAYLIST
                thisUser = instagInfo.getJSONObject("user").getString("username");
                user.add(thisUser);


            }

            Log.d(TAG, "username" + user);
            Log.d(TAG, "full_name" + fullname);
            Log.d(TAG, "url" + pics);

        } catch (JSONException e) {
            instagInfo = null;
        }

        try {
            Bitmap pulledImage = getBitmapFromURL(pics.get(0));
            searchPic.add(pulledImage);

        } catch (Exception e) {


        }

        try {

            if (newtworkBool) {

                readMic = new MicSearch(user.get(0), fullname.get(0), pics.get(0));
                readMic.setUserName(user.get(0));
                readMic.setRealName(fullname.get(0));
                readMic.setUserImg(pics.get(0));

                FileOutputStream fos = getActivity().openFileOutput("myFile", Context.MODE_PRIVATE);
                ObjectOutputStream of = new ObjectOutputStream(fos);
                of.writeObject(readMic);
                of.flush();
                of.close();
                fos.close();
                Log.d(TAG, "saving......." + readMic);
                Log.d(TAG, "......" + readMic.getUserName() + readMic.getRealName());



        }else if (!newtworkBool) {


            FileInputStream fis = getActivity().openFileInput("myFile");
            ObjectInputStream ois = new ObjectInputStream(fis);
            readMic = (MicSearch) ois.readObject();
            ois.close();


            Log.d(TAG, "readingOff....." + readMic);
            Log.d(TAG, "......." + readMic.getUserName() + readMic.getRealName());

            Bitmap pulledImage = getBitmapFromURL(readMic.getUserImg());
            searchPic.add(pulledImage);
            //comm.Communicate(readMic.getUserName(), readMic.getRealName(), searchPic.get(0));





            }




        }catch (Exception e) {
        }


        return instagInfo;
        }


    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar3);
        //progress.setVisibility(View.VISIBLE);

    }

    //SETS THE INSTAGRAM/ARRAY ITEMS FOR DISPLAY TO THE USER
    @Override
    protected void onPostExecute(JSONObject jsonObject ) {
        super.onPostExecute(jsonObject);
      MicSearch readMic = null;
        if(newtworkBool){
            comm.Communicate(user.get(0), fullname.get(0), searchPic.get(0));
        }else if(!newtworkBool){
            comm.Communicate(readMic.getUserName(), readMic.getRealName(), searchPic.get(0));
        }

            doInstagram();
        }

    }

1 个答案:

答案 0 :(得分:0)

  

我不确定将IF语句检查的最佳位置   连接并从保存的文件中拉出

doInBackground

因为检查网络连接和从api获取数据都与网络相关的任务有关。系统将花费时间执行这两项任务。