使用其他类中的一个类的arraylist

时间:2014-06-25 17:04:04

标签: android arraylist android-asynctask

我已经在一个ArrayList中存储了json数组数据。我想在其他类中使用这个ArrayList。我怎么能实现。我确实使用它来使它静态但它不是一个好方法。我也做了一个将返回arrayList的方法,但每次我得到null值。我做什么

public class SearchJobAsync extends AsyncTask<String, String, String> {
    private String response;
    Context c;
    SearchModel data;
    ArrayList<SearchModel> values;

    public SearchJobAsync(Context c) {
        this.c = c;
    }

    public SearchJobAsync(Context c, ArrayList<SearchModel> values) {
        this.c = c;
        this.values = values;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute ();
        CommonFunctions.showProgress (c, "Please Wait...", true);

    }

    @Override
    protected void onPostExecute(String s) {
        values = new ArrayList<SearchModel> ();

        super.onPostExecute (s);
        if (!s.trim ().contains ("Table")) {
            Crouton.makeText ((android.app.Activity) c, "Nothing found", Style.INFO).show ();
        } else {
            try {

                JSONObject jsonObject = new JSONObject (s);
                JSONObject NewDataSet = jsonObject.getJSONObject ("NewDataSet");
                if (NewDataSet.get ("Table") instanceof JSONObject) {
                    JSONObject table = NewDataSet.getJSONObject ("Table");
                    data = new SearchModel (table.getString ("Job_Category"), table.getString ("Min_Exp"), table.getString ("Max_Exp"), table.getString ("Posted_On"), table.getString ("Candidate_Counts"), table.getString ("Applications"), table.getString ("No_Of_Pos"), table.getString ("Job_Desc"), table.getString ("Job_Type"), table.getString ("Job_Hours"), table.getString ("Job_Status"), table.getString ("Job_Exp_Date"), table.getString ("Address"), table.getString ("Gender_Name"), table.getString ("Religion_Name"), table.getString ("Exp_Summary"), table.getString ("IJob_Request_ID"), table.getString ("Requestor_Name"));
                    values.add (data);
                } else if (NewDataSet.get ("Table") instanceof JSONArray) {
                    JSONArray tableArray = NewDataSet.getJSONArray ("Table");

                    for (int i = 0; i < tableArray.length (); i++) {
                        JSONObject table = tableArray.getJSONObject (i);
                        data = new SearchModel (table.getString ("Job_Category"), table.getString ("Min_Exp"), table.getString ("Max_Exp"), table.getString ("Posted_On"), table.getString ("Candidate_Counts"), table.getString ("Applications"), table.getString ("No_Of_Pos"), table.getString ("Job_Desc"), table.getString ("Job_Type"), table.getString ("Job_Hours"), table.getString ("Job_Status"), table.getString ("Job_Exp_Date"), table.getString ("Address"), table.getString ("Gender_Name"), table.getString ("Religion_Name"), table.getString ("Exp_Summary"), table.getString ("IJob_Request_ID"), table.getString ("Requestor_Name"));
                        values.add (data);

                    }

                }


            } catch (JSONException e) {
                e.printStackTrace ();
            }
        }

        CommonFunctions.showProgress (c, "", false);
        Intent i = new Intent (c, SearchJobListActivity.class);
        c.startActivity (i);
    }

    @Override
    protected String doInBackground(String... s) {
        response = HttpRequest.post ("https://beta135.hamarisuraksha.com/web/WebService/HsJobService.asmx/FindJobForVendor").send ("Vendor_IEntity_Code=" + "34588A34-E969-4723-84FE-E5409B66A5B7" + "&Job_Code=" + "&Job_Category=1" + "&Exp_Years_From=0" + "&Exp_Months_From=0" + "&Exp_Years_To=0" + "&Exp_Months_To=0").body ();
        response = response.replaceAll ("<[^>]*>", "").replaceAll ("\n", "");
        Log.e ("Search Jobs", "" + response);
        return response;
    }

    public ArrayList<SearchModel> getList(){
        return values;
    }
}

ListFragment类

public class SearchJobList extends ListFragment {
    private View view;
    private ListView lvSearchJobs;
    private ArrayList<SearchModel> data;
    SearchJobCustomList customList;
    SearchJobAsync searchJobAsync;
    private Context c;

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated (savedInstanceState);
        c = getActivity ();
        lvSearchJobs = (ListView) getActivity ().findViewById (android.R.id.list);
        data = new ArrayList<SearchModel> ();
        searchJobAsync = new SearchJobAsync (c);
        data = searchJobAsync.getList ();

        customList = new SearchJobCustomList (c, data);
        setListAdapter (customList);

    }
}

ListFragment活动

public class SearchJobListActivity extends FragmentActivity {
    private FragmentTransaction fragmentTransaction;

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

    private void initialize() {
        fragmentTransaction = getSupportFragmentManager ().beginTransaction ();
        SearchJobList searchJobList = new SearchJobList ();
        fragmentTransaction.replace (R.id.container, searchJobList, "searchJobList").commit ();
    }
}

我调用Async .execute()方法的类

public class SearchJobsFragment extends Fragment implements View.OnClickListener {

    private View view;
    private Spinner spCategory;
    private Button btSearch;
    private Spinner spToYrs;
    private Spinner spFromMonths;
    private Spinner spFromYrs;
    private Spinner spToMonths;
    private EditText etJobCode;
    private String[] yrsArray, monthArray, professionArray;
    private ArrayAdapter<String> toYrs, toMonths, profession;
    private Context c;

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

    private void initialize() {

        c = getActivity ();
        spCategory = (Spinner) getActivity ().findViewById (R.id.sp_category);
        btSearch = (Button) getActivity ().findViewById (R.id.bt_search);
        spToYrs = (Spinner) getActivity ().findViewById (R.id.sp_to_yrs);
        spFromMonths = (Spinner) getActivity ().findViewById (R.id.sp_from_months);
        spFromYrs = (Spinner) getActivity ().findViewById (R.id.sp_from_yrs);
        spToMonths = (Spinner) getActivity ().findViewById (R.id.sp_to_months);
        etJobCode = (EditText) getActivity ().findViewById (R.id.et_job_code);
        btSearch.setOnClickListener (this);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated (savedInstanceState);
        initialize ();
        spinnerSetup ();
    }

    private void spinnerSetup() {

        //for to/from yrs

        yrsArray = getResources ().getStringArray (R.array.Experience_yrss);
        toYrs = new ArrayAdapter<String> (c, R.layout.spinner_textview, yrsArray);
        toYrs.setDropDownViewResource (android.R.layout.simple_list_item_single_choice);
        spToYrs.setAdapter (toYrs);
        spFromYrs.setAdapter (toYrs);


        // for to/from months
        monthArray = getResources ().getStringArray (R.array.Experience_months);
        toMonths = new ArrayAdapter<String> (c, R.layout.spinner_textview, monthArray);
        toMonths.setDropDownViewResource (android.R.layout.simple_list_item_single_choice);
        spToMonths.setAdapter (toMonths);
        spFromMonths.setAdapter (toMonths);


        //for category

        professionArray = getResources ().getStringArray (R.array.Profession);
        Arrays.sort (professionArray, 1, professionArray.length);
        profession = new ArrayAdapter<String> (c, R.layout.spinner_textview, professionArray);
        profession.setDropDownViewResource (android.R.layout.simple_list_item_single_choice);
        spCategory.setAdapter (profession);


    }

    @Override
    public void onClick(View view) {
        SearchJobAsync searchJobAsync = new SearchJobAsync (c);
        searchJobAsync.execute ();
    }
}

我该如何从其他类访问ArrayList?

2 个答案:

答案 0 :(得分:0)

你可以将arraylist包装成一个单独的单例类。

http://en.wikipedia.org/wiki/Singleton_pattern

关于列表为空.....

在这一行:

searchJobAsync = new SearchJobAsync (c);

我认为你可能打算启动asynctask所以它应该是这样的:

searchJobAsync = new SearchJobAsync (c);
searchJobAsync.execute();

为了回应评论线程(为了保持这个类简单,我结合创建并在相同的代码中获得单例,但这将起作用):

public class DataHolder(){
ArrayList<SearchModel> list;
private static DataHolder instance;

private DataHolder(ArrayList<SearchModel> list){
this.list = list;
}

public getInstance(ArrayList<SearchModel> list){
if(instance == null){
instance = new DataHolder(list);
}
return instance;
}

public ArrayList<SearchModel> getList(){
return list
}

}

然后在asynctask中获取该列表的数据持有者的新实例:

DataHolder.getInstance(list);

答案 1 :(得分:0)

您应该使用观察者模式并处理片段类中的结果。只需修改你的AsyncTask如下:

public class SearchJobAsync extends AsyncTask<String, String, String> {
private String response;
Context c;
SearchModel data;

SearchDataListener searchDataListener;

public static interface SearchDataListener {
    void onSearchSuccess(List<SearchModel> data);
    void onSearchFailed();
}

public SearchJobAsync(Context c) {
    this.c = c;
}

public void setSearchDataListener(SearchDataListener searchDataListener) {
    this.searchDataListener = searchDataListener;
}

@Override
protected void onPreExecute() {
    super.onPreExecute ();
    CommonFunctions.showProgress (c, "Please Wait...", true);
}

@Override
protected void onPostExecute(String s) {
    List<SearchModel> values = new ArrayList<SearchModel> ();

    super.onPostExecute (s);
    if (!s.trim ().contains ("Table")) {
        Crouton.makeText ((android.app.Activity) c, "Nothing found", Style.INFO).show ();
    } else {
        try {

            JSONObject jsonObject = new JSONObject (s);
            JSONObject NewDataSet = jsonObject.getJSONObject ("NewDataSet");
            if (NewDataSet.get ("Table") instanceof JSONObject) {
                JSONObject table = NewDataSet.getJSONObject ("Table");
                data = new SearchModel (table.getString ("Job_Category"), table.getString ("Min_Exp"), table.getString ("Max_Exp"), table.getString ("Posted_On"), table.getString ("Candidate_Counts"), table.getString ("Applications"), table.getString ("No_Of_Pos"), table.getString ("Job_Desc"), table.getString ("Job_Type"), table.getString ("Job_Hours"), table.getString ("Job_Status"), table.getString ("Job_Exp_Date"), table.getString ("Address"), table.getString ("Gender_Name"), table.getString ("Religion_Name"), table.getString ("Exp_Summary"), table.getString ("IJob_Request_ID"), table.getString ("Requestor_Name"));
                values.add (data);
            } else if (NewDataSet.get ("Table") instanceof JSONArray) {
                JSONArray tableArray = NewDataSet.getJSONArray ("Table");

                for (int i = 0; i < tableArray.length (); i++) {
                    JSONObject table = tableArray.getJSONObject (i);
                    data = new SearchModel (table.getString ("Job_Category"), table.getString ("Min_Exp"), table.getString ("Max_Exp"), table.getString ("Posted_On"), table.getString ("Candidate_Counts"), table.getString ("Applications"), table.getString ("No_Of_Pos"), table.getString ("Job_Desc"), table.getString ("Job_Type"), table.getString ("Job_Hours"), table.getString ("Job_Status"), table.getString ("Job_Exp_Date"), table.getString ("Address"), table.getString ("Gender_Name"), table.getString ("Religion_Name"), table.getString ("Exp_Summary"), table.getString ("IJob_Request_ID"), table.getString ("Requestor_Name"));
                    values.add (data);
                }

            }
            // call the listener here
            if(values.size() > 0) {               
                searchDataListener.onSearchSuccess(values);
            } else
                searchDataListener.onSearchFailed();
            }
        } catch (JSONException e) {
            e.printStackTrace ();
        }
    }

    CommonFunctions.showProgress (c, "", false);
    Intent i = new Intent (c, SearchJobListActivity.class);
    c.startActivity (i);
}

@Override
protected String doInBackground(String... s) {
    response = HttpRequest.post ("https://beta135.hamarisuraksha.com/web/WebService/HsJobService.asmx/FindJobForVendor").send ("Vendor_IEntity_Code=" + "34588A34-E969-4723-84FE-E5409B66A5B7" + "&Job_Code=" + "&Job_Category=1" + "&Exp_Years_From=0" + "&Exp_Months_From=0" + "&Exp_Years_To=0" + "&Exp_Months_To=0").body ();
    response = response.replaceAll ("<[^>]*>", "").replaceAll ("\n", "");
    Log.e ("Search Jobs", "" + response);
    return response;
}

public ArrayList<SearchModel> getList(){
    return values;
}
}

并在你的片段类中调用它:

    @Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated (savedInstanceState);
    c = getActivity ();
    lvSearchJobs = (ListView) getActivity ().findViewById (android.R.id.list);
    searchJobAsync = new SearchJobAsync (c);
    searchJobAsync.setSearchListener(new SearchListener(){
        @Override
        public void onSearchSuccess(List<SearchModel> data) {
            // handler result
            customList = new SearchJobCustomList (c, data);
            setListAdapter (customList);
        }
        @Override
        public void onSearchFailed() {
            // handler failure
        }   
}

希望这有帮助!