2012-03-12 58 views
1

我有一个应用程序,它将JSON订阅源的信息加载到列表视图中。这需要一些时间来加载,所以我想设置一个进度条,让用户知道应用程序正在做些什么。我是否必须实现一个AsyncTask,或者有一种简单的方法来让旋转进度图标在列表加载时出现?我假设我需要将进度对话代码放入我加载的任务中。这是我的listview的代码。打开Json进度列表视图时的进度对话框

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)); 
} 

希望我的问题很明确,让我知道你是否需要我显示任何其他细节。

+0

即使您不想实现进度对话框,仍应设置异步任务。从UI线程获取和处理JSONP将锁定用户界面 - 这不仅会导致糟糕的用户体验,还会导致您的应用被Android强制关闭。 – xbonez 2012-03-12 17:22:20

+0

这是很好的知道。获取进度图标作为ListView加载后,我需要将图像包含到来自url字符串的每个行项目中。你知道用json feed解释AsyncTask有什么好处吗? – KSol 2012-03-12 17:41:36

+0

Android有一些关于异步任务的可靠文档:http://developer.android.com/reference/android/os/AsyncTask.html。 – xbonez 2012-03-12 17:44:13

回答

0

最好的方法来做你想要完成的是确保任务是一个异步任务。所以当你得到JSON提要时,它需要是一个异步任务,因为你需要另一个任务同时运行,这将是你的进度对话框。如果您没有将其设置为异步,则进度对话框将显示为冻结状态,并且可能会导致正在运行的同步任务崩溃,这是您的JSON订阅源。我会考虑让你的JSON feed任务异步。

+0

感谢您的快速响应。异步任务是否会在同一个java文件中,或者它会是它自己的java文件并被上面的内容引用?你知道一个很好的教程吗? – KSol 2012-03-12 17:12:31

+0

是的,@PKeidel建议。您应该使用一个处理程序,其中有关于如何在android开发人员站点上使用它的文档。祝你好运! – Eli 2012-03-12 19:17:42

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(); 
      } 
     } 
    } 
} 
+0

为Handler,你使用java.util.loggin或android.os? – KSol 2012-03-12 17:38:48

+0

android.os.Handler => http://developer.android.com/reference/android/os/Handler.html – PKeidel 2012-03-12 17:45:11

0

嗨尝试使用asyntask

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; 
     } 
    } 

}

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(); 
     } 
    } 

} 
}