如何读取JSON源以填充单维数组?

时间:2012-10-21 21:46:51

标签: android json arraylist

我试图将JSON提要中包含的值读入一维数组 - 数组元素将ShowProgress,Orange,Blue和Target的值存储到Progress类的数组中。然后我想用这些来更新进度条(参见第三个代码部分)。我无法提取这些值(也许它们没有被设置?):

以下是Feed的样子(它传递JSONlint):

{
"ShowProgress": {
"ShowProgress": "TRUE",
"Orange": "0",
"Blue": "0",
"Target": "18"
 }
 }

这个例程是我无法正确读取数组值的地方,rem语句表明我怀疑的地方:

public class FetchProgress extends AsyncTask<OpportunityActivity, Void, ArrayList<String>> {
private OpportunityActivity opportunityActivity;

@Override
protected ArrayList doInBackground(OpportunityActivity... activity) {

    // This may be incorrect - I don't want a two dimensional
    // just a one dimensional array
opportunityActivity = activity[0];

    ArrayList<Progress> progresses = new ArrayList<Progress>();
    String readFeed = readFeed();

    try {           
    JSONObject json = new JSONObject(readFeed);            
    JSONArray jsonArray = new JSONArray(json.optString("ShowProgress"));              
Progress progress = new Progress();                    
progress.setTarget(jsonArray.optInt("Target"));            
    } catch (Exception e) {
      e.printStackTrace();
    }

此例程读取JSON:

 public String readFeed() {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();      

    SharedPreferences settings =     
    PreferenceManager.getDefaultSharedPreferences(opportunityActivity);        
    HttpGet httpGet = new HttpGet("https://www.webfeedurl.com/stuff.php");
    try 
 {
      HttpResponse response = client.execute(httpGet);
      StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
      if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;

        int a=0;
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        a++;
        }
      } else {
        Log.e(MainActivity.class.toString(), "Failed to download file");
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e)
 {
      e.printStackTrace();
    }
    return builder.toString();
  }

最后回到OpportunityActivity我想使用数组中的值来设置我的ProgressBar:

public void updateProgress(ArrayList<Progress> progress) {
    ProgressBar progressHours  = (ProgressBar)findViewById(R.id.progressHours);      
    // How do I get the array list variables out to set my progress bar....
    // The next line is wrong 
    progressHours.setProgress(progress.getTarget());
}

这是类文件:(我尝试读取的变量多于目标,因此我使用的是数组)。

public class Progress {

private int target;

public int getTarget() {
    return target;
}

public void setTarget(int target) {
    this.target = target;
}

}

0 个答案:

没有答案