我正在尝试将 JSON 提要中包含的值读入一维数组 - 数组元素将 ShowProgress、Orange、Blue 和 Target 的值存储到 Progress 类数组中。然后我想用这些来更新进度条(见第三个代码部分)。我无法提取这些值(也许它们没有被设置?):
这是提要的样子(它通过 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;
}
}