0
public class NewsScreenActivity extends Activity{

    ListView list;
    //AdView adView;
    ProgressDialog progressDialog;
    ImageView refresh_btn;
    WebView newwebview;
    public static NewsScreenActivity activity;
    public static String  ac;
    NewsScreenAdapter adapter;
    String tag = "NewsScreenActivity"; 
    int seconds=10;
    public static NewsScreenActivity na;
    AlertDialog connection1;
    int t;

    public class MainData {
      public String catId, nextCatId, prevCatId, catDisplay;
      public ArrayList<StoryData> storyArr = new ArrayList<StoryData>();
    }

  public class StoryData {
       public String storyid, date, title, description,advertising,contenthtml;
       public  ArrayList<ImagesData> imageArr = new ArrayList<ImagesData>();
       public AdvertiseData adData;
    }

  public class ImagesData {

        public String caption, bigurl, smallurl, mimetype;
        public int height, width;
    }

  public class AdvertiseData{
      public String title,desc,targeturl,imageurl;
  }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.newsscreen);


        list = (ListView)findViewById(R.id.first_listview);        
        refresh_btn=(ImageView)findViewById(R.id.refresh_btn);
        activity = this;
        na=this;
        final String url = "http://maritimeglobalnews.com/json";

        new AllDataAsyn().execute(url);

        refresh_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                    new AllDataAsyn().execute(url);  
                     //adapter.IL.clearCache();
                    // adapter.notifyDataSetChanged();
            }
        }) ;

         list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
                // TODO Auto-generated method stub
                int storyLenght = ((NewsScreenActivity.MainData)NewsScreenActivity.TotalDataArray.get(position)).storyArr.size();

                ac=((NewsScreenActivity.MainData)NewsScreenActivity.TotalDataArray.get(position)).storyArr.get(position).storyid;
            }            
        });       
    }

    public class AllDataAsyn extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub

            if (!isNetworkConnected()) {

                runOnUiThread(new Runnable() {
                    public void run() {
                        // Your Alert Code

                        AlertDialog connection = new AlertDialog.Builder(
                                NewsScreenActivity.this)
                                .setTitle("No Network Found")
                                .setMessage(
                                        "Internet Connection Reqired To Use this Application")
                                .setPositiveButton("Ok",
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int whichButton) {

                                                progressDialog.dismiss();
                                            }
                                        }).create();
                        connection.show();
                    }
                });

            } else {

                Log.e("arraylist", "" + arrayList_advertising);
                arrayList_advertising.clear();
                getData(params[0].toString());

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            // TODO Auto-generated method stub
            super.onPostExecute(result);               

              if(arrayList_title.size()>0)
             {

                  if (isNetworkConnected() == true) {

                progressDialog.dismiss();               
                adapter = new NewsScreenAdapter(NewsScreenActivity.this);
                list.setAdapter(adapter);                  
                }                  
              } else{

                  runDialog(30);
              }
        }  
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

                progressDialog = new ProgressDialog(NewsScreenActivity.this);
                progressDialog.setMessage("Loading ...");
                progressDialog.setCancelable(false);
                progressDialog.show();  
        }
        public boolean isNetworkConnected(){

            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo ni = cm.getActiveNetworkInfo();

            if(ni == null){              
                return false;
            } else              
                return true;
            }
        }

    public void getData(String url){

        try
        {
                   //String url = params[0].toString();
                    HttpParams httpParameters = new BasicHttpParams();
                // Set the timeout in milliseconds until a connection is established.
                // The default value is zero, that means the timeout is not used.
                    int timeoutConnection = 10000;
                    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                    //HttpPost request = new HttpPost("http://maritimeglobalnews.com/json");
                    HttpPost request = new HttpPost(url);

                    // Send request to WCF service
                    DefaultHttpClient httpClient = new DefaultHttpClient();

                    HttpResponse res = httpClient.execute(request);
                 //   Log.i("Request", request.toString());
                    TotalDataArray.clear();
                    String JsonResponseData = EntityUtils.toString(res.getEntity());

                    JSONArray mainDataArr = new JSONArray(JsonResponseData);

                    for (int k = 0; k < mainDataArr.length(); k++) {

                        MainData mainData = new MainData();
                        // Limit
                        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

                        try {
                            JSONObject mainJsonObj = mainDataArr.getJSONObject(k);

                        //    Log.i("CategoryEID", mainJsonObj.getString("CategoryEID"));
                            mainData.catId = mainJsonObj.getString("CategoryEID");
                            category_id=mainJsonObj.getString("CategoryEID");
                            arrayList_category_id.add(category_id);

                      //      Log.i(tag,"NextCategoryEID "+ mainJsonObj.getString("NextCategoryEID") + " ");                  
                            mainData.nextCatId = mainJsonObj.getString("NextCategoryEID");

                      //      Log.i(tag, "PrevCategoryEID"+mainJsonObj.getString("PrevCategoryEID") + " ");
                            mainData.prevCatId = mainJsonObj.getString("PrevCategoryEID");

                     //       Log.i("CategoryDisplay", mainJsonObj.getString("CategoryDisplay"));
                            mainData.catDisplay = mainJsonObj.getString("CategoryDisplay");

                            header=mainJsonObj.getString("CategoryDisplay");
                   //         Log.e("temp",""+header);

                            arrayList_header.add(header);

                            JSONArray storyJsonArr = mainJsonObj.getJSONArray("storiesShort");
                            ArrayList<StoryData> tempStoryArr = new ArrayList<StoryData>();
               //             Log.i("storiesShort Array Lenght", storyJsonArr.length()+ "");

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

                                StoryData tmpObjStr = new StoryData();
                                JSONObject storyJsonObj = storyJsonArr.getJSONObject(i);

                 //               Log.i("", "Story Number : " + i);
                 //               Log.i("StoryEID", storyJsonObj.getString("StoryEID"));                      
                                tmpObjStr.storyid = storyJsonObj.getString("StoryEID");
                                story_id=storyJsonObj.getString("StoryEID");
                                arrayList_story_id.add(story_id);

                  //              Log.i("Date", storyJsonObj.getString("Date"));
                                tmpObjStr.date = storyJsonObj.getString("Date");
                                date_time=storyJsonObj.getString("Date");
                                arrayList_date_time.add(date_time);

                                Date parsed = new Date(Long.parseLong(date_time.substring(6,date_time.length() - 2)));

                   //             Log.e("date parsed", ""+parsed);                               
                                arrayList_convert_date.add(parsed.toString());

                  //              Log.i("Title", storyJsonObj.getString("Title"));
                                tmpObjStr.title = storyJsonObj.getString("Title");
                                title=storyJsonObj.getString("Title");
                                arrayList_title.add(title);

                   //             Log.i("Description", storyJsonObj.getString("Description"));
                                tmpObjStr.description = storyJsonObj.getString("Description");
                                des=storyJsonObj.getString("Description");
                                arrayList_des.add(des);


               //                 Log.i("advertising", storyJsonObj.getString("advertising"));
                                tmpObjStr.advertising = storyJsonObj.getString("advertising");
                                try{
                                advertising=storyJsonObj.getString("advertising");
                                if(advertising.equalsIgnoreCase("null"))
                                        arrayList_advertising.add(advertising);
                                else
                                {
                                    JSONObject tmpAd = storyJsonObj.optJSONObject("advertising");
                                    AdvertiseData adData = new AdvertiseData();
                                    adData.title = tmpAd.getString("Title");
                                    adData.desc = tmpAd.getString("Description");
                                    adData.targeturl = tmpAd.getString("TargetUrl");
                                    adData.imageurl = tmpAd.getString("ImageUrl");                                      
                                    tmpObjStr.adData = adData;                                  
                                }                                
                           }catch(Exception e){
                            // TODO: handle exception
                        }
                                JSONArray imagesURLJsonArr = storyJsonObj.getJSONArray("images");                            


                                ArrayList<ImagesData> tempimagarr = new ArrayList<ImagesData>();

                                for (int j = 0; j < imagesURLJsonArr.length(); j++) {

                                    ImagesData tmpimgdata = new ImagesData();
                                    JSONObject imageObject = imagesURLJsonArr.getJSONObject(j);

                 //                   Log.i("Caption", imageObject.getString("Caption"));
                                    tmpimgdata.caption = imageObject.getString("Caption");

                 //                   Log.i("iPhoneSmallImageURL", imageObject .getString("iPhoneSmallImageURL"));
                                    tmpimgdata.smallurl = imageObject.getString("iPhoneSmallImageURL");
                                    image=imageObject.getString("iPhoneSmallImageURL");
                                    arrayList_image.add(image);

                   //                 Log.i("iPhoneBigImageURL", imageObject .getString("iPhoneBigImageURL"));
                                    tmpimgdata.bigurl = imageObject.getString("iPhoneBigImageURL");
                                    big_image=imageObject.getString("iPhoneBigImageURL");
                                    arrayList_big_image.add(big_image);

                //                    Log.i("Height", imageObject.getInt("Height") + "");
                                    tmpimgdata.height = imageObject.getInt("Height");

              //                      Log.i("Width", imageObject.getInt("Width") + "");
                                    tmpimgdata.width = imageObject.getInt("Width");

               //                     Log.i("MimeType", imageObject.getString("MimeType"));
                                    tmpimgdata.mimetype = imageObject.getString("MimeType");
                                    tempimagarr.add(tmpimgdata);
                                }
                                tmpObjStr.imageArr = tempimagarr;
                                tempStoryArr.add(tmpObjStr);
                            }

                            Log.i("CategoryDisplay", mainJsonObj.getString("CategoryDisplay"));
                            mainData.catDisplay = mainJsonObj.getString("CategoryDisplay");
                            mainData.storyArr = tempStoryArr;
                            TotalDataArray.add(mainData);

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("=================== Connection TimeOut11111111", "======");

                }
            }
        }
        catch (ConnectTimeoutException e)
        {
            e.printStackTrace();
            runOnUiThread(new Runnable()
            {
              public void run()
              {
                        // Your Alert Code
                     progressDialog.dismiss();
                        AlertDialog connection = new AlertDialog.Builder(
                                NewsScreenActivity.this)
                                .setTitle("No Network Found")
                                .setMessage(
                                        "Internet Connection Reqired To Use this Application,please try again latter")
                                .setPositiveButton("Ok",
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog,
                                                    int whichButton) {


                                            }
                                        }).create();

                        connection.show();

              }
            });
            Log.i("=================== Connection TimeOut222222", "======");
         }
        catch (SocketTimeoutException e){
               e.printStackTrace();
               runOnUiThread(new Runnable()
               {
                 public void run()
                 {
                           // Your Alert Code
                        progressDialog.dismiss();
                           AlertDialog connection = new AlertDialog.Builder(
                                   NewsScreenActivity.this)
                                   .setTitle("No Network Found")
                                   .setMessage(
                                           "Internet Connection Reqired To Use this Application,please try again latter")
                                   .setPositiveButton("Ok",
                                           new DialogInterface.OnClickListener() {

                                               public void onClick(DialogInterface dialog,
                                                       int whichButton) {

                                           //        progressDialog.dismiss();
                                               }
                                           }).create();

                           connection.show();

                 }
               });
               Log.i("=================== Connection TimeOut33333333333", "======");
           }
         catch (UnknownHostException e) {
               e.printStackTrace();
               runOnUiThread(new Runnable()
                   {
                     public void run()
                     {
                               // Your Alert Code
                            progressDialog.dismiss();
                               AlertDialog connection = new AlertDialog.Builder(
                                       NewsScreenActivity.this)
                                       .setTitle("No Network Found")
                                       .setMessage(
                                               "Internet Connection Reqired To Use this Application,please try again latter")
                                       .setPositiveButton("Ok",
                                               new DialogInterface.OnClickListener() {

                                                   public void onClick(DialogInterface dialog,
                                                           int whichButton) {

                                               //        progressDialog.dismiss();
                                                   }
                                               }).create();

                               connection.show();

                     }
                   });


               Log.i("=================== UnknownHostException", "======");

         }catch (Exception e){                

            e.printStackTrace();          
            runOnUiThread(new Runnable()
                   {
                     public void run()
                     {
                    // Your Alert Code
                    progressDialog.dismiss();
                    AlertDialog connection = new AlertDialog.Builder(
                            NewsScreenActivity.this)
                            .setTitle("No Network Found")
                            .setMessage(
                                    "Internet Connection Reqired To Use this Application,please try again latter")
                            .setPositiveButton("Ok",
                                    new DialogInterface.OnClickListener() {

                                        public void onClick(
                                                DialogInterface dialog,
                                                int whichButton) {


                                        }
                                    }).create();

                    connection.show();

                }
            });

            Log.i("=================== Connection TimeOut4444444444", "======");
        }
    }

    private void runDialog(final int seconds){

            new Thread(new Runnable(){
                public void run(){
                    try {
                            Thread.sleep(seconds * 1000);
                            progressDialog.dismiss();
                           connection1 = new AlertDialog.Builder(
                                    NewsScreenActivity.this)
                                    .setTitle("neel alert")
                                    .setMessage(
                                            "Internet Connection Reqired To Use this Application,please try again latter")
                                    .setPositiveButton("Ok",
                                            new DialogInterface.OnClickListener() {

                                                public void onClick(DialogInterface dialog,
                                                        int whichButton) {


                                                }
                                            }).create();

                        //    connection1.show();               
                         }catch (InterruptedException e) {

                        e.printStackTrace();
                    }
                }
            }).start();
    }

如果没有从 Web 服务获得响应,我想打开警报。我已经完成了这个功能,但它对我不起作用。当我启动应用程序时,显示的进度对话框,当时我断开了互联网。该对话框不会在 30 秒内关闭。如何解决?

4

1 回答 1

0

如果您设置了 Timeout,那么如果 web 服务调用未在您预定义的时间间隔(例如,30 秒)内执行,它肯定会引发 TimeoutException。

所以尝试在catch块内显示对话框。

于 2012-10-12T10:34:38.127 回答