java - 将新数据追加到 ArrayList 的简单方法

标签 java android eclipse android-asynctask append

我正在制作一个应用程序,显示来自 Tumblr 帐户的图像。它加载前 20 个项目,然后底部有一个“加载更多”按钮。单击“加载更多”按钮时,我使用 AsyncTask 来处理它。我已经按照我认为应该的方式设置了所有内容,但我未能将接下来的 20 张图像 append 到列表中。我见过一些其他项目使用自定义 listAdapter 类,但我一直在寻找一种更简单的方法来实现它。

这是我的代码:

public class Example extends Activity {

Context context = null;
ListView listView = null;
TextView footer;
int offset = 0;
ProgressDialog pDialog;

private String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ArrayList<Tumblr> tumblrs;
    try {
        tumblrs = getTumblrs();
        listView = (ListView) findViewById(R.id.list);
        View v = getLayoutInflater().inflate(R.layout.footer_layout, null);
        footer = (TextView) v.findViewById(R.id.tvFoot);
        listView.addFooterView(v);
        listView.setAdapter(new UserItemAdapter(this, R.layout.listitem,
                tumblrs));

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

    footer.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new loadMoreListView().execute();
        }
    });

}

public class UserItemAdapter extends ArrayAdapter<Tumblr> {
    private ArrayList<Tumblr> tumblrs;

    public UserItemAdapter(Context context, int imageViewResourceId,
            ArrayList<Tumblr> tumblrs) {
        super(context, imageViewResourceId, tumblrs);
        this.tumblrs = tumblrs;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {

            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.listitem, null);

        }

        Tumblr tumblr = tumblrs.get(position);
        if (tumblr != null) {

            ImageView image = (ImageView) v.findViewById(R.id.avatar);

            if (image != null) {
                image.setImageBitmap(getBitmap(tumblr.image_url));
            }
        }
        return v;
    }
}

public Bitmap getBitmap(String bitmapUrl) {
    try {
        URL url = new URL(bitmapUrl);
        return BitmapFactory.decodeStream(url.openConnection()
                .getInputStream());
    } catch (Exception ex) {
        return null;
    }
}

public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException,
        IOException, JSONException {
    searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset=0";

    ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>();

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(searchUrl);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String responseBody = null;
    try {
        responseBody = client.execute(get, responseHandler);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject(responseBody);

    JSONArray posts = jsonObject.getJSONObject("response").getJSONArray(
            "posts");
    for (int i = 0; i < posts.length(); i++) {
        JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
        for (int j = 0; j < photos.length(); j++) {
            JSONObject photo = photos.getJSONObject(j);
            String url = photo.getJSONArray("alt_sizes").getJSONObject(0)
                    .getString("url");

            Tumblr tumblr = new Tumblr(url);
            tumblrs.add(tumblr);
        }
    }
    return tumblrs;
}

public class Tumblr {

    public String image_url;

    public Tumblr(String url) {

        this.image_url = url;
    }
}

private class loadMoreListView extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        // Showing progress dialog before sending http request
        pDialog = new ProgressDialog(Example.this);
        pDialog.setMessage("Please wait..");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... unused) {
        // TODO Auto-generated method stub
        runOnUiThread(new Runnable() {
            public void run() {
                // increment current page
                offset += 20;

                // Next page request

                searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY&offset="
                        + offset;



                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(searchUrl);

                ResponseHandler<String> responseHandler = new BasicResponseHandler();

                String responseBody = null;
                try {
                    responseBody = client.execute(get, responseHandler);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(responseBody);

                    JSONArray posts = jsonObject.getJSONObject("response")
                            .getJSONArray("posts");
                    for (int i = 0; i < posts.length(); i++) {
                        JSONArray photos = posts.getJSONObject(i)
                                .getJSONArray("photos");
                        for (int j = 0; j < photos.length(); j++) {
                            JSONObject photo = photos.getJSONObject(j);
                            String url = photo.getJSONArray("alt_sizes")
                                    .getJSONObject(0).getString("url");

                            Tumblr tumblr = new Tumblr(url);
                            tumblrs.add(tumblr);

                        }
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // get listview current position - used to maintain scroll
                // position
                int currentPosition = listView.getFirstVisiblePosition();

                // Appending new data to tumblrs ArrayList


                // Setting new scroll position
                listView.setSelectionFromTop(currentPosition + 1, 0);

            }
        });

        return null;
    }

    protected void onPostExecute(Void unused) {
        pDialog.dismiss();
    }

}

 }

感谢任何帮助!

最佳答案

  • ArrayList设为静态
  • 将值添加到名为 tumblrsArrayList 中,然后在 Adapter 上执行 notifyDataSetChanged()(此处它的 UserItemAdapter)

///////////////已编辑部分//////////////////////////////

我的这个项目相当大,所以只发布从你的角度来看很重要的两个类......

适配器类:

public class ProductAdapter extends ArrayAdapter<ProductListPojo> {


    Activity a;
    Context context;
    int layoutResourceId;    
    ArrayList<ProductListPojo> plp = null;
    ImageLoader iLoader;
    public YoutubeImageLoader imageLoader;
    public ProductAdapter(Context context, int resource, ArrayList<ProductListPojo> listy) {
        super(context, resource, listy);

        this.layoutResourceId = resource;
        this.context = context;
        this.plp = listy;

    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        iLoader = new ImageLoader(context);
        WeatherHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            imageLoader =   new YoutubeImageLoader(context);
            holder = new WeatherHolder();

            holder.imgIcon = (ImageView)row.findViewById(R.id.imageView_PrefImage);
            holder.imgIsPreffered = (ImageView)row.findViewById(R.id.imageView_isPreffered);

            holder.txtTitle = (TextView)row.findViewById(R.id.textView_HeadingPref);
            holder.txtprovider = (TextView)row.findViewById(R.id.textView_Provider);
            holder.counterParty = (TextView)row.findViewById(R.id.textView_counterparty);
            holder.closingDate = (TextView)row.findViewById(R.id.textView_ClosingDate);
            holder.term = (TextView)row.findViewById(R.id.textView_Term);
            holder.indexLink = (TextView)row.findViewById(R.id.textView_IndexLink);
            holder.investmentType = (TextView)row.findViewById(R.id.textView_InvestmentType);
            holder.productType = (TextView)row.findViewById(R.id.textView_ProductType);
            holder.li          = (LinearLayout)row.findViewById(R.id.linearLayout_IsPreferred);

            row.setTag(holder);
        }
        else
        {
            holder = (WeatherHolder)row.getTag();
        }


        ProductListPojo product = plp.get(position);

        try{

            holder.imgIcon.setTag(product.getpId());
            imageLoader.DisplayImage("http://www.xxxxxxxx.com/Resources/Covers/FullSize/"+product.getpId()+"."+"jpg", a, holder.imgIcon);   

        }catch(Exception ex){

         holder.imgIcon.setImageResource(R.drawable.milkywhite);
        }

        holder.imgIsPreffered.setBackgroundResource(R.drawable.correct);
        if (product.isPref()){

            //holder.imgIsPreffered.setVisibility(View.VISIBLE);

            holder.li.setVisibility(View.VISIBLE);


        }else{
            //holder.imgIsPreffered.setVisibility(View.INVISIBLE);

            holder.li.setVisibility(View.INVISIBLE);
        }

       holder.txtTitle.setText(product.getOverview());
       holder.txtprovider.setText(product.getProvider());
       holder.counterParty.setText(product.getCounterparty());
       holder.closingDate.setText(dateKoKaro(product.getClosingDate().toString()));
       holder.term.setText(product.getTerm());
       holder.indexLink.setText(product.getIndexLink());
       holder.investmentType.setText(product.getInvestmentType());
       holder.productType.setText(product.getProductType());



        return row;
    }


    public String dateKoKaro(String datu){

        /*Pattern pat = Pattern.compile("\\d.?.?.?.?-.?.?.?.?.?");
        Matcher mat = pat.matcher(datu);
        String dx = new String();

        while(mat.find()){

            dx = mat.group();
        }

        System.out.println(dx);*/
        String l = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(datu)));
        System.out.println("THE TIME: "+l);
        String[] dxxx = l.split("-");

        Calendar c = Calendar.getInstance();
        System.out.println("Y: "+Integer.parseInt(dxxx[0])+" - "+"M: "+Integer.parseInt(dxxx[1])+" - "+"D: "+Integer.parseInt(dxxx[2]));
        if(Integer.parseInt(dxxx[1])==0){
        c.set(Integer.parseInt(dxxx[0]), Integer.parseInt(dxxx[1]), Integer.parseInt(dxxx[2]));
        }
        else{

            c.set(Integer.parseInt(dxxx[0]), Integer.parseInt(dxxx[1])-1, Integer.parseInt(dxxx[2]));

        }
        Date d = c.getTime();

        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);

        String InDate = df.format(d);

        return InDate;
    }

    static class WeatherHolder
    {
        ImageView imgIcon;
        ImageView imgIsPreffered;

        TextView txtTitle;
        TextView txtprovider;
        TextView counterParty;
        TextView closingDate;
        TextView term;
        TextView indexLink;
        TextView investmentType;
        TextView productType;
        LinearLayout li;
    }

    private Drawable LoadImageFromWebOperations(String url) {

        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }

    }
}

将适配器设置为 ListView 的 Activity :

public class ProductActivity extends Activity{

    public APIHandlingClass api = APIHandlingClass.getInstance();
    public static ArrayList<ProductListPojo> apList = new ArrayList<ProductListPojo>();
    public ListView lv;

    int count = 0;
    ProductListPojo pPojo;
    ProductAdapter adpt;
    View mheader;
    View mfooter;
    boolean isInternet = false;
    Intent i;
    Button mbuttFilter;
    Button mback;
    /*Button mbuttonLiterature;
    Button mbuttonQuestion;*/
    Handler h;
    ProgressDialog pd;


    DataBaseHelper dkarkeB = new DataBaseHelper(this);

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

                /*mbuttonLiterature = (Button)findViewById(R.id.buttonLiterature);
                mbuttonQuestion = (Button)findViewById(R.id.buttonQuestion);*/

                mheader = View.inflate(ProductActivity.this, R.layout.headerproductlist, null);
                mfooter = View.inflate(ProductActivity.this, R.layout.giraffeimg, null);
                lv = (ListView)findViewById(R.id.listView_ProductList);
                adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);

                lv.addHeaderView(mheader,null,false);
                lv.addFooterView(mheader,null,false);
                lv.addFooterView(mfooter,null,false);
                mback = (Button)findViewById(R.id.button_Filter);
                h = new Handler();

                pd = new ProgressDialog(getParent());
                pd.setTitle("Loading...");


                apList.clear();

                if(InternetAvailable()){ 

                    System.out.println("Net hai");

                   pd.show();

                   DownloadWebPageTask task = new DownloadWebPageTask();
                   task.execute();






                }else{

                    System.out.println("Net nahi hai");

                    DownloadWebPageNewTask t = new DownloadWebPageNewTask();
                    t.execute();
                    //adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);

                    //fillList();
                    /*adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
                    lv.setAdapter(adpt);
                    adpt.notifyDataSetChanged();*/
                     AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(getParent());
                     myAlertDialog.setTitle("--- Network Erro ---");
                     myAlertDialog.setMessage("We were unable to connect to the Internet to download product information. Please ensure you have an active data connection and restart the app.");
                     myAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                      public void onClick(DialogInterface arg0, int arg1) {

                        arg0.dismiss();

                      }});
                        System.out.println("No Internet Connectivity");

                        myAlertDialog.show();           



                }

                mbuttFilter = (Button)findViewById(R.id.button_Filter);
                /*mbuttFilter.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        i = new Intent(ProductActivity.this, ResetActivity.class);
                        startActivity(i);

                    }
                });*/


                mback.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        i = new Intent(ProductActivity.this, ResetActivity.class);
                        startActivity(i);

                    }
                });



                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                            int arg2, long arg3) {


                        i = new Intent(ProductActivity.this,ProductDetails.class);
                        //i.putExtra("keyAapo", arg2 );


                        i.putExtra("keyAapo", (int)lv.getItemIdAtPosition(arg2) );

                        startActivity(i);


                    }




                });




                /*mbuttonLiterature.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        i = new Intent(ProductActivity.this, GetLiteratureActivity.class);
                        startActivity(i);

                    }
                });

                mbuttonQuestion.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        i = new Intent(ProductActivity.this, AnyQuestionActivity.class);
                        startActivity(i);

                    }
                });
                */






    }


    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
          String response = "";
          parseJson();
          fillList();

          return response;
        }

        @Override
        protected void onPostExecute(String result) {

        h.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                pd.dismiss();   
            }
        }, 3000);   


          adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);

            /*lv.addHeaderView(mheader,null,false);
            lv.addFooterView(mheader,null,false);
            lv.addFooterView(mfooter,null,false);*/
          lv.setAdapter(adpt);
          adpt.notifyDataSetChanged();
        }
      }


    /////--------------------------------------------------------------------------------------------------

    private class DownloadWebPageNewTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
          String response = "";

          fillList();

          return response;
        }

        @Override
        protected void onPostExecute(String result) {

        h.postDelayed(new Runnable() {

            @Override
            public void run() {

                pd.dismiss();   
            }
        }, 3000);   


        adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
        lv.setAdapter(adpt);
        adpt.notifyDataSetChanged();
        }
      }

    /////--------------------------------------------------------------------------------------------------


    public void parseJson(){

        JSONArray jarr;
        dkarkeB.openDataBase();
        dkarkeB.deleteAll();
        dkarkeB.close();

        try {

            jarr = api.go();

            for(int i=0 ; i<jarr.length() ; i++){



                JSONObject jobj = jarr.getJSONObject(i);
                String mainText = new String();
                String provText = new String();
                String couText = new String();
                String fDatu = new String();
                String termText = new String();
                String indexText = new String();
                String insvText = new String();
                String prodText = new String();
                String isPref = new String();
                String jDesc = new String();
                String jCb1 = new String();
                String jCb2 = new String();
                String jCb3 = new String();
                String jCb4 = new String();
                String jspRating = new String();
                String jFRating = new String();
                String jMRating = new String();
                String jFs = new String();
                String jColl = new String();
                String jSIndex = new String();
                String jEIndex = new String();
                String jCashISA = new String();
                String jEquityISA = new String();
                String jDirect = new String();
                String jTransfer = new String();
                String jSipp = new String();
                String jCapitalAtRiskProDetails = new String();
                String jCapitalAtRiskProPercentage = new String();
                String jProValue = new String();
                String jInitialsCharges = new String();
                String jEarlyISATransfer = new String();
                String pid= new String();
                String jOpinionExplanation = new String();
                String jName = new String();
                String jTaxTreat = new String();
                String jDownSide = new String();
                String jProtectionDetails = new String();
                String jEarlySurrender = new String();
                String jOtherCharges = new String();

                try{
                 mainText = jobj.getString("Overview");
                System.out.println(mainText);
                }catch(Exception ex){

                }

                try{

                JSONObject jProv = jobj.getJSONObject("Provider");
                provText = jProv.getString("Name");
                System.out.println(provText);
                }catch(Exception ex){

                }

                try{
                JSONObject jCou = jobj.getJSONObject("Counterparty");
                couText = jCou.getString("Value");
                System.out.println(couText);
                }catch(Exception ex){

                }

                try{
                String cloText = jobj.getString("ClosingDate");
                fDatu = giveMeDate(cloText);
                System.out.println(fDatu);
                }catch(Exception ex){

                }

                try{
                termText = jobj.getString("Term");
                System.out.println(termText);
                }catch(Exception ex){

                }

                try{
                indexText = jobj.getString("IndexLink");
                System.out.println(indexText);
                }catch(Exception ex){

                }

                try{
                JSONObject jInsv = jobj.getJSONObject("InvestmentType");
                insvText = jInsv.getString("Value");
                System.out.println(insvText);
                }catch(Exception ex){

                }

                try{
                JSONObject jProd = jobj.getJSONObject("ProductType");
                prodText = jProd.getString("Value");
                System.out.println(prodText);
                }catch(Exception ex){

                }

                try{
                isPref = BooleanToString(jobj.getBoolean("IsPreferred"));
                System.out.println(isPref);
                }catch(Exception ex){

                }

                try{
                jDesc = jobj.getString("Description");
                System.out.println(jDesc);
                }catch(Exception ex){

                }

                try{
                jCb1 = jobj.getString("CashBackTier1");
                System.out.println(jCb1);
                }catch(Exception ex){

                }

                try{
                jCb2 = jobj.getString("CashBackTier2");
                System.out.println(jCb2);
                }catch(Exception ex){

                }

                try{
                jCb3 = jobj.getString("CashBackTier3");
                System.out.println(jCb3);
                }catch(Exception ex){

                }

                try{
                jCb4 = jobj.getString("CashBackTier4");
                System.out.println(jCb4);
                }catch(Exception ex){

                }               

                try{
                JSONObject jSP = jobj.getJSONObject("SPRating");
                jspRating = jSP.getString("Rating");
                System.out.println(jspRating);
                }catch(Exception ex){

                }

                try{
                JSONObject jFr = jobj.getJSONObject("FitchRating");
                jFRating = jFr.getString("Rating");
                System.out.println("I am the Fitch:"+jFRating);
                }catch(Exception ex){

                }

                try{
                JSONObject jMdy = jobj.getJSONObject("MoodyRating");
                jMRating = jMdy.getString("Rating");
                System.out.println(jMRating);
                }catch(Exception ex){

                }

                try{
                jFs = BooleanToString(jobj.getBoolean("IsFSCSProtected"));
                System.out.println(jFs);
                }catch(Exception ex){

                }

                try{
                jColl = BooleanToString(jobj.getBoolean("IsCollateralised"));
                System.out.println(jColl);
                }catch(Exception ex){

                }

                try{
                jSIndex = jobj.getString("StartingIndices");
                System.out.println(jSIndex);
                }catch(Exception ex){

                }

                try{
                jEIndex = jobj.getString("FinalIndices");
                System.out.println(jEIndex);
                }catch(Exception ex){

                }

                try{
                jCashISA = jobj.getString("MinimumCashISA");
                System.out.println(jCashISA);
                }catch(Exception ex){

                }

                try{
                jEquityISA = jobj.getString("MinimumEquityISA");
                System.out.println(jEquityISA);
                }catch(Exception ex){

                }

                try{
                jDirect = jobj.getString("MinimumDirect");
                System.out.println(jDirect);
                }catch(Exception ex){

                }

                try{
                jTransfer = jobj.getString("MinimumTransfer");
                System.out.println(jTransfer);
                }catch(Exception ex){

                }

                try{
                jSipp = jobj.getString("MinimumSIPP");
                System.out.println(jSipp);
                }catch(Exception ex){

                }

                try{
                jCapitalAtRiskProDetails = jobj.getString("ProtectionDetails");
                System.out.println(jCapitalAtRiskProDetails);
                }catch(Exception ex){

                }

                try{
                jCapitalAtRiskProPercentage = jobj.getString("ProtectionPercentage");
                System.out.println(jCapitalAtRiskProPercentage);
                }catch(Exception ex){

                }

                try{
                JSONObject jVal = jobj.getJSONObject("ProtectionType");
                jProValue = jVal.getString("Value");
                System.out.println(jProValue);
                }catch(Exception ex){

                }

                try{
                jInitialsCharges = jobj.getString("InitialCharge");
                System.out.println(jInitialsCharges);
                }catch(Exception ex){

                }

                try{
                jEarlyISATransfer = jobj.getString("EarlyISATransferCharge");
                System.out.println(jEarlyISATransfer);
                }catch(Exception ex){

                }

                try{

                jOpinionExplanation = jobj.getString("OpinionExplanation");
                System.out.println("xxxxXXXX"+jOpinionExplanation);
                }catch(Exception ex){

                }


                try{
                pid = jobj.getString("ID");
                }catch(Exception ex){

                }

                try{
                     jName = jobj.getString("Name");
                    System.out.println(jName);
                    }catch(Exception ex){

                    }

                try{
                    jTaxTreat = jobj.getString("TaxTreatment");
                    System.out.println(jTaxTreat);
                    }catch(Exception ex){

                    }

                try{
                     jDownSide = jobj.getString("Downside");
                    System.out.println(jDownSide);
                    }catch(Exception ex){

                    }

                try{

                    jProtectionDetails = jobj.getString("ProtectionDetails");
                    System.out.println(jProtectionDetails);
                }catch(Exception ex){


                }

                try{
                    jEarlySurrender = jobj.getString("SurrenderCharge");
                    System.out.println(jEarlySurrender);

                }catch(Exception ex){


                }

                try{
                    jOtherCharges = jobj.getString("OtherCharge");
                    System.out.println(jOtherCharges);

                }catch(Exception ex){


                }

                dkarkeB.openDataBase();


                dkarkeB.insertTitle( mainText,  jDesc,
                        jCb1,  jCb2,  jCb3,
                        jCb4,  jspRating,  jFRating,
                        jMRating, jFs ,  jColl,
                        jSIndex,  jEIndex,  jCashISA,
                        jEquityISA,  jDirect,  jTransfer,
                        jSipp,jCapitalAtRiskProDetails,
                         jCapitalAtRiskProPercentage,  jProValue,
                         jInitialsCharges,  jEarlyISATransfer,
                         provText,  couText,  fDatu,
                         termText,  indexText,  insvText,
                         prodText,  isPref,  pid, jOpinionExplanation,jName, jTaxTreat, jDownSide, jProtectionDetails, jEarlySurrender, jOtherCharges);


                dkarkeB.close();
                }

            System.out.println("SIZE DOES MATTER IN LIST: "+jarr.length());
        } catch (IOException e) {

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

            e.printStackTrace();
        }



    }

    public void fillList(){

        dkarkeB.openDataBase();
        apList = dkarkeB.getMyProductList();
        dkarkeB.close();


        }









    public String BooleanToString(boolean isKaro){

        String holdIt = new String();

        if(isKaro){

            holdIt = "true";
        }
        else{

            holdIt = "false";
        }

        return holdIt;



    }
    public String giveMeDate(String str){

        String s = str;

        Pattern pat = Pattern.compile("\\d.?.?.?.?-.?.?.?.?.?");
        Matcher mat = pat.matcher(s);
        String datu = new String();

        while(mat.find()){

            datu = mat.group();

        }

        String dtx = new String();
        ////-----------------------------------------

        try {

              //String str_date="2012-09-12";
              DateFormat formatter ; 
              Date date ; 
              formatter = new SimpleDateFormat("yyyy-MM-dd");
              date = (Date)formatter.parse(datu); 
              long longDate=date.getTime();
              System.out.println("Today is " +longDate );
              System.out.println("New "+new SimpleDateFormat("yyyy-MM-dd").format(new Date(longDate)));
              dtx = longDate+"";
              }
              catch (ParseException e){
              System.out.println("Exception :"+e); 
              }


       ////------------------------------------------
        /*String[] dxxx = datu.split("-");

        Calendar c = Calendar.getInstance();
        c.set(Integer.parseInt(dxxx[0]), Integer.parseInt(dxxx[1]), Integer.parseInt(dxxx[2]));
        Date d = c.getTime();

        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);

        String InDate = df.format(d);*/

        return dtx;

    }


    //////----------------------------------------------------Internet-------------------------------------------

    public boolean InternetAvailable() {

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                // while(isStopMe){
                System.out.println("This is inside ................. :");
                try {
                    if (!checkConnection()) {
                        System.out.println("No Internet Connectivity");
                        ProductActivity.this.isInternet = false;
                        System.out.println("First");
                    } else {
                        if (inetAddr()) {
                            System.out.println("Net Connectivity is Present");
                            ProductActivity.this.isInternet = true;
                            System.out.println("Second");
                        } else {
                            if (mobileConnect()) {
                                System.out.println("THIRD");
                                if (inetAddr()) {
                                    System.out
                                            .println("Net Connectivity is Present");
                                    ProductActivity.this.isInternet = true;
                                    System.out.println("FOURTH");
                                } else {
                                    System.out
                                            .println("No Internet Connectivity");
                                    ProductActivity.this.isInternet = false;
                                    System.out.println("FIFTH");
                                }
                            } else {
                                System.out.println("No Internet Connectivity");
                                ProductActivity.this.isInternet = false;
                                System.out.println("SIX");
                            }
                        }
                    }
                } catch (Exception ex) {
                    System.out.println("Leak ko catch");
                }

            }
        });
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ProductActivity.this.isInternet;
    }

    public boolean checkConnection() {
        boolean connected = false;
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni
                        .getTypeName().equalsIgnoreCase("MOBILE"))
                        & ni.isConnected() & ni.isAvailable()) {
                    connected = true;
                }
            }
        }
        return connected;
    }

    public boolean inetAddr() {
        boolean x1 = false;

        try {
            Socket s = new Socket();
            s.connect(new InetSocketAddress("ntp-nist.ldsbc.edu",37),3000);
            InputStream is = s.getInputStream();

            Scanner scan = new Scanner(is);

            while(scan.hasNextLine()){

                System.out.println(scan.nextLine());
                x1 = true;
            }
        } catch (IOException e) {

            x1 = false;

        }
        return x1;
    }
    public boolean mobileConnect() {
        boolean conn = false;
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNet = cm
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (activeNet != null) {
            conn = true;
        } else {
            conn = false;
        }
        return conn;
    }





    /////-----------------------------------------------------Internet-------------------------------------------

    @Override
    protected void onResume() {

        super.onResume();
        //adpt.notifyDataSetChanged();
        System.out.println("The List is: "+apList+"::"+apList.size());
        if(count>0){
        adpt = new ProductAdapter(ProductActivity.this, R.layout.productitem , apList);
        lv.setAdapter(adpt);

        }
        count++;
        System.out.println("The List is: "+apList+"::"+apList.size());
    }
}

关于java - 将新数据追加到 ArrayList 的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12517995/

相关文章:

android - 如何解决致命异常 : Thread-11

android - Android Studio补丁安装方法

android - ADT 插件没有出现在 Eclipse 中

java - 在 Windows 7 上运行 Eclipse 未找到 JRE 和 JDK

java - 如何关闭(禁用)jdk.event.security 日志?

java - 如何向二维 ArrayList 中的元素添加 (+) 整数?

java - 从A点直接移动到B点

java - Codenameone 上的文本字段未正确更新/重新绘制

Android 通知重建而不是更新?

Java多线程赛车模拟问题