打开Json fed Listview时的进度对话框

时间:2012-03-12 16:44:16

标签: android json listview progressdialog

我有一个应用程序,可以将json提要中的信息加载到列表视图中。这需要一点时间加载,所以我想设置一个进度条让用户知道应用程序正在做什么。我是否必须实现AsyncTask,或者是否有一种简单的方法可以在加载列表时显示旋转进度图标?我假设我需要将progressdialog代码放在我正在加载的任务中。这是我的listview的代码。

public class Schedule extends ListActivity {

protected EditText searchText;
protected SQLiteDatabase db;
protected Cursor cursor;
protected TextView textView;
protected ImageView imageView;
protected ArrayList<HashMap<String, String>> myList;

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

    View layout = findViewById(R.id.gradiant);

    GradientDrawable gd = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM, new int[] {
                    0xFF95B9C7, 0xFF06357A });
    gd.setCornerRadius(2f);

    layout.setBackgroundDrawable(gd);

    myList = new ArrayList<HashMap<String, String>>();

    JSONObject jsonObjSend = new JSONObject();
    JSONObject json = JSONfunctions
            .getJSONfromURL("myAPIURL");

    try {

        JSONArray current = json.getJSONArray("d");

        for (int i = 0; i < current.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject e = current.getJSONObject(i);

            map.put("id", String.valueOf(i));
            map.put("showid", "" + Html.fromHtml(e.getString("ShowID")));
            map.put("name", "" + Html.fromHtml(e.getString("Title")));
            map.put("showvenue", "" + e.getString("ShowVenue"));
            map.put("subtitle", "" + Html.fromHtml(e.getString("SubTitle")));
            map.put("venueid", "" + e.getString("VenueID"));

            String showDate = e.getString("ShowDate");
            long epoch = Long.parseLong(showDate);
            Date showDatePresent = new Date(epoch * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("E, MMMM d");
            String dateOfShow = sdf.format(showDatePresent);
            map.put("showdate", "" + dateOfShow);

            String showStart = e.getString("ShowStart");
            long epoch2 = Long.parseLong(showStart);
            Date showTimePresent = new Date(epoch2 * 1000);
            SimpleDateFormat sdf2 = new SimpleDateFormat("h:mm a");
            String timeOfShow = sdf2.format(showTimePresent);
            map.put("showstart", "" + timeOfShow);

            String showEnd = e.getString("ShowEnd");
            long epoch3 = Long.parseLong(showEnd);
            Date showEndPresent = new Date(epoch3 * 1000);
            SimpleDateFormat sdf3 = new SimpleDateFormat("h:mm a");
            String endOfShow = sdf3.format(showEndPresent);
            map.put("showend", "" + endOfShow);

            String gatesOpen = e.getString("GatesOpen");
            long epoch4 = Long.parseLong(gatesOpen);
            Date gatesOpenPresent = new Date(epoch4 * 1000);
            SimpleDateFormat sdf4 = new SimpleDateFormat(
                    "'Gates open: 'h:mm a");
            String gatesAreOpen = sdf4.format(gatesOpenPresent);
            map.put("gatesopen", "" + gatesAreOpen);

            map.put("aboutartist", "" + e.getString("AboutArtist"));
            map.put("program", "" + Html.fromHtml(e.getString("Program")));
            map.put("programnotes",
                    "" + Html.fromHtml(e.getString("ProgramNotes")));
            map.put("pricing", "" + Html.fromHtml(e.getString("Pricing")));
            map.put("featuring", "" + e.getString("Featuring"));
            map.put("parkdetails", "" + e.getString("ParkDetails"));
            map.put("starred", "" + e.getString("Starred"));

            map.put("image500", "" + e.getString("Image500"));

            map.put("image250", "" + e.getString("Image250"));

            map.put("aboutartist",
                    "" + Html.fromHtml(e.getString("AboutArtist")));
            myList.add(map);
        }

    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());

    }

    ListAdapter adapter = new SimpleAdapter(this, myList,
            R.layout.line_item, new String[] { "name", "showdate",
                    "showstart", "showvenue" }, new int[] { R.id.title,
                    R.id.showdate, R.id.showstart, R.id.showvenue });
    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);
    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            HashMap<String, String> hashMap = myList.get(position);
            // hashMap.put("map", hashMap);
            Intent intent = new Intent(getApplicationContext(),
                    ArtistDetails.class);
            intent.putExtra("map", hashMap);
            startActivity(intent);
        }

    });

}

public void featured(View view) {
    startActivity(new Intent(getApplicationContext(), Featured.class));
}

public void schedule(View view) {
    startActivity(new Intent(getApplicationContext(), Schedule.class));
}

public void venue(View view) {
    startActivity(new Intent(getApplicationContext(), Venues.class));
}

public void share(View view) {
    startActivity(new Intent(getApplicationContext(), Friends.class));
}

public void myravinia(View view) {
    startActivity(new Intent(getApplicationContext(), Account.class));
}

希望我的问题很明确,如果您需要我显示任何其他详细信息,请与我联系。

4 个答案:

答案 0 :(得分:0)

执行您要完成的任务的最佳方法是确保该任务是异步任务。因此,当您获得JSON提要时,它需要是一个异步任务,因为您希望同时运行另一个任务,这将是您的进度对话框。如果你没有使它异步,那么进度对话框似乎被冻结,可能会崩溃正在运行的同步任务,这是你的JSON提要。我会考虑让你的JSON feed任务异步。

答案 1 :(得分:0)

你可以这样做:

final Handler handler = new Handler();

dialog = ProgressDialog.show(Events.this, "Wait", "Please wait...", false);

new Thread()
{
    public void run()
    {
        // Do a lot of funny things with json here in background
        handler.post(new Runnable()
        {
            public void run()
            {
                if(dialog != null)
                    dialog.dismiss();
            }
        }
    }
}

答案 2 :(得分:0)

您可以使用asynctask

尝试此方法
protected class ParsingTask extends AsyncTask<Context, String, ArrayList<Items>>   {

     private ProgressDialog loadingDialog = new ProgressDialog(JsonParserActivity.this);



     protected void onPreExecute() {
         loadingDialog.setMessage("loading app store..");
         loadingDialog.show();
     }
        //items is a list of model class item 
    @Override
    protected ArrayList<Items> doInBackground( Context... params )  {

        String source = getJsonString(url);


        try {
            // do ur parsing here with the above source.
           }

         catch (Throwable e) {
            e.printStackTrace();
        }
        return result;
     }      
 catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        if (source != null) {
      }
        if (!this.isCancelled()) {
        }

        return result;
    }

    @Override
    protected void onProgressUpdate(String... s)   {
        super.onProgressUpdate(s);
        Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPostExecute( ArrayList<Items> response )  {
            // st ur list view here
                mListView.setAdapter(new JsonListAdapter(JsonParserActivity.this));
            loadingDialog.dismiss();

    }

    @Override
    protected void onCancelled() {
        super.onCancelled();

        Toast.makeText(getApplicationContext(), "The operation was cancelled", 1).show();
    }


private String getJsonString(String url) {
        DefaultHttpClient client = new DefaultHttpClient(); 
        HttpGet getRequest;
        try {
            getRequest = new HttpGet(url);
            HttpResponse getResponse = client.execute(getRequest);
            HttpEntity getResponseEntity = getResponse.getEntity();
            return EntityUtils.toString(getResponseEntity);
        } catch (Exception e) {
            Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
            return null;
        }
    }

}

答案 3 :(得分:0)

谢谢大家的帮助。从中我就能够提出一个解决方案。这里有比以前更多的代码,但这里有用。

public class Schedule extends ListActivity {

protected EditText searchText;
protected SQLiteDatabase db;
protected Cursor cursor;
protected TextView textView;
protected ImageView imageView;
protected ArrayList<HashMap<String, String>> myList;
protected ImageLoader imageLoader;

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

    View layout = findViewById(R.id.gradiant);

    GradientDrawable gd = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM, new int[] {
                    0xFF95B9C7, 0xFF06357A });
    gd.setCornerRadius(2f);

    layout.setBackgroundDrawable(gd);

    new GetEventsTask().execute("blah");

}

public void featured(View view) {
    startActivity(new Intent(getApplicationContext(), Featured.class));
}

public void schedule(View view) {

}

public void venue(View view) {
    startActivity(new Intent(getApplicationContext(), Venues.class));
}

public void share(View view) {
    startActivity(new Intent(getApplicationContext(), Friends.class));
}

public void myravinia(View view) {
    startActivity(new Intent(getApplicationContext(), Account.class));
}

protected class GetEventsTask extends
        AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {

    protected ArrayList<HashMap<String, String>> threadList;

    private final ProgressDialog dialog = new ProgressDialog(Schedule.this);

    protected void onPreExecute() {
        this.dialog.setMessage("Loading...");
        this.dialog.setCancelable(false);
        this.dialog.show();
    }



    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            String... params) {

        Log.v("Yup", "The thread is running");
        threadList = new ArrayList<HashMap<String, String>>();

        JSONObject json = JSONfunctions
                .getJSONfromURL("my.json.feed.url");

        try {


            JSONArray current = json.getJSONArray("d");

            for (int i = 0; i < current.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = current.getJSONObject(i);

                map.put("id", String.valueOf(i));
                map.put("showid", "" + Html.fromHtml(e.getString("ShowID")));
                map.put("name", "" + Html.fromHtml(e.getString("Title")));
                map.put("showvenue", "" + e.getString("ShowVenue"));
                map.put("subtitle",
                        "" + Html.fromHtml(e.getString("SubTitle")));
                map.put("venueid", "" + e.getString("VenueID"));

                String showDate = e.getString("ShowDate");
                long epoch = Long.parseLong(showDate);
                Date showDatePresent = new Date(epoch * 1000);
                SimpleDateFormat sdf = new SimpleDateFormat("E, MMMM d");
                String dateOfShow = sdf.format(showDatePresent);
                map.put("showdate", "" + dateOfShow);

                String showStart = e.getString("ShowStart");
                long epoch2 = Long.parseLong(showStart);
                Date showTimePresent = new Date(epoch2 * 1000);
                SimpleDateFormat sdf2 = new SimpleDateFormat("h:mm a");
                String timeOfShow = sdf2.format(showTimePresent);
                map.put("showstart", "" + timeOfShow);

                String showEnd = e.getString("ShowEnd");
                long epoch3 = Long.parseLong(showEnd);
                Date showEndPresent = new Date(epoch3 * 1000);
                SimpleDateFormat sdf3 = new SimpleDateFormat("h:mm a");
                String endOfShow = sdf3.format(showEndPresent);
                map.put("showend", "" + endOfShow);

                String gatesOpen = e.getString("GatesOpen");
                long epoch4 = Long.parseLong(gatesOpen);
                Date gatesOpenPresent = new Date(epoch4 * 1000);
                SimpleDateFormat sdf4 = new SimpleDateFormat(
                        "'Gates open: 'h:mm a");
                String gatesAreOpen = sdf4.format(gatesOpenPresent);
                map.put("gatesopen", "" + gatesAreOpen);

                map.put("aboutartist", "" + e.getString("AboutArtist"));
                map.put("program",
                        "" + Html.fromHtml(e.getString("Program")));
                map.put("programnotes",
                        "" + Html.fromHtml(e.getString("ProgramNotes")));
                map.put("pricing",
                        "" + Html.fromHtml(e.getString("Pricing")));
                map.put("featuring", "" + e.getString("Featuring"));
                map.put("parkdetails", "" + e.getString("ParkDetails"));
                map.put("starred", "" + e.getString("Starred"));

                map.put("image500", "" + e.getString("Image500"));

                map.put("image250", "" + e.getString("Image250"));

                map.put("aboutartist",
                        "" + Html.fromHtml(e.getString("AboutArtist")));
                threadList.add(map);
            }

        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());

        }

        return threadList;


    }


    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {

        myList = new ArrayList<HashMap<String, String>>();
        myList = result;

        LazyAdapter adapter = new LazyAdapter(Schedule.this, myList);
        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                HashMap<String, String> hashMap = myList.get(position);
                // hashMap.put("map", hashMap);
                Intent intent = new Intent(getApplicationContext(),
                        ArtistDetails.class);
                intent.putExtra("map", hashMap);

                startActivity(intent);

            }

        });

        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }
    }

}
 }