我还是Android开发新手。我想问一下AsyncTask。
我正在使用Fragments,AChartEngine和AsyncTask开发Android应用程序来解析服务器上的JSON文件。如果连接稳定并且运行良好,一切都很好。 Fragment将根据我选择的URL解析JSON文件。
但是,当连接不稳定时,我遇到了问题。这就是我产生问题的方法。
这是我如何生成片段。
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new BackboneFragment();
break;
case 2:
fragment = new MinyakFragment();
break;
case 3:
fragment = new GasFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
这是我的片段类
public class GasFragment extends Fragment {
//Development URL
private static String url = "http://192.168.0.100/jsontraining/flash_data_url_gas_die.json";
//Y-Values
private static ArrayList<HashMap<String, ArrayList<Long>>> jsonlist = new ArrayList<HashMap<String, ArrayList<Long>>>();
private static HashMap<String, ArrayList<Long>> mapValues = new HashMap<String, ArrayList<Long>>();
//Legends
private static ArrayList<HashMap<String, String>> jsonListString = new ArrayList<HashMap<String, String>>();
private static HashMap<String, String> mapValuesText = new HashMap<String,String>();
private static ArrayList<String> dateStringArray = new ArrayList<String>();
private GraphicalView chartView;
public GasFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gas, container, false);
new JSONParse().execute();
return rootView;
}
@SuppressWarnings("unchecked")
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
jsonlist.clear();
mapValues.clear();
}
private class JSONParse extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}//End of onPreExecute
@Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}//End of doInBackground
@Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
try
{
//Fetching Array of Elements
JSONArray jsonArray = json.getJSONArray("elements");
//Fetching for TextView
//Fetching for Pertamina EP
JSONObject jsonYAxis = json.getJSONObject("y_axis");
Long yAxisMin = jsonYAxis.getLong("min");
Long yAxisMax = jsonYAxis.getLong("max");
JSONObject jsonYLegend = json.getJSONObject("y_legend");
String y_legend = jsonYLegend.getString("text");
JSONObject jsonXLegend = json.getJSONObject("x_legend");
String x_legend = jsonXLegend.getString("text");
TextView uid;
JSONObject jsonTitle= json.getJSONObject("title");
String title = jsonTitle.getString("text");
uid = (TextView) getActivity().findViewById(R.id.txtLabel_gas);
uid.setText(title);
//Fetching for Date
JSONObject jsonObjectXAxis = json.getJSONObject("x_axis");
JSONObject jsonObjectXAxisLabels = jsonObjectXAxis.getJSONObject("labels");
JSONArray jsonArrayXAxisLabels = jsonObjectXAxisLabels.getJSONArray("labels");
for(int i=0;i<jsonArrayXAxisLabels.length();i++)
{
dateStringArray.add((String) jsonArrayXAxisLabels.getString(i));
}
for (int i=0;i<jsonArray.length();i++)
{
ArrayList<Long> list = new ArrayList<Long>();
HashMap<String, ArrayList<Long>> mapValues = new HashMap<String, ArrayList<Long>>();
HashMap<String, String> mapValuesText = new HashMap<String,String>();
JSONObject elementNo = (JSONObject) jsonArray.get(i);
JSONArray valuesGraph = (JSONArray) elementNo.get("values");
String texts = elementNo.getString("text");
String colours = elementNo.getString("colour");
int len = valuesGraph.length();
for (int x=0;x<len;x++)
{
if(!valuesGraph.isNull(x))
{
Long nilai = (Long)valuesGraph.getLong(x);
list.add(nilai);
}
}
mapValues.put("Values", list);
mapValuesText.put("Text", texts);
mapValuesText.put("Colour", colours);
jsonlist.add(mapValues);
jsonListString.add(mapValuesText);
}
//Line Graph
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.rgb(254, 254, 254));
mRenderer.setMarginsColor(Color.rgb(254, 254, 254));
int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
for(int start=0; start<jsonlist.size(); start++)
{
//start++;
mapValuesText = jsonListString.get(start);
TimeSeries series = new TimeSeries(mapValuesText.get("Text").trim()+"");
//start--;
mapValues = jsonlist.get(start);
int jumlahValues = mapValues.get("Values").size();
for(int i=0; i<jumlahValues; i++)
{
series.add(x[i], mapValues.get("Values").get(i));
}
dataset.addSeries(series);
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setShowLegendItem(true);
renderer.setChartValuesTextSize(24);
renderer.setColor(Color.parseColor(mapValuesText.get("Colour").toString()));
renderer.setLineWidth(3);
renderer.setPointStyle(PointStyle.CIRCLE);
renderer.setFillPoints(true);
//renderer.setDisplayChartValues(true);
mRenderer.addSeriesRenderer(renderer);
}
//XY Titles
mRenderer.setYTitle(y_legend);
//mRenderer.setXTitle(x_legend);
mRenderer.setChartTitle(x_legend);
mRenderer.setChartTitleTextSize(30);
mRenderer.setAxisTitleTextSize(22);
mRenderer.setLabelsTextSize(22);
mRenderer.setXLabelsColor(Color.BLACK);
mRenderer.setYLabelsColor(0, Color.BLACK);
mRenderer.setShowLabels(true);
mRenderer.setXLabels(dateStringArray.size());
//Legends
//Legends
mRenderer.setShowLegend(true);
//mRenderer.setFitLegend(true);
mRenderer.setLegendTextSize(20);
mRenderer.setXLabelsPadding(20);
mRenderer.setYLabelsAlign(Align.RIGHT, 0);
mRenderer.setYLabelsPadding(7);
mRenderer.setYLabelsVerticalPadding(-5);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
for (int i = 0; i < jsonArrayXAxisLabels.length();)
{
String xChartDates = jsonArrayXAxisLabels.getString(i);
mRenderer.addTextLabel(i+1, xChartDates);
if(mapValues.get("Values").size()<9)
{
i=i+1;
}
else
{
i=i+4;
}
}
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setXLabels(0);
} else {
for (int i = 0; i < jsonArrayXAxisLabels.length(); i++)
{
String xChartDates = jsonArrayXAxisLabels.getString(i);
mRenderer.addTextLabel(i+1, xChartDates);
}
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setXLabels(0);
}
mRenderer.setAxesColor(Color.BLACK);
mRenderer.setLabelsColor(Color.BLACK);
mRenderer.setMargins(new int[]{ 10, 110, 10, 10});
mRenderer.setYAxisMax(yAxisMax);
mRenderer.setYAxisMin(yAxisMin);
mRenderer.setPointSize(9.5f);
//mRenderer.setPanLimits(new double[]{0, (jsonArrayXAxisLabels.length())*1.1, yAxisMin, yAxisMax});
mRenderer.setInScroll(true);
mRenderer.setClickEnabled(true);
//Grid
mRenderer.setShowGrid(true);
//mRenderer.setShowGridX(true);
//mRenderer.setShowGridY(true);
mRenderer.setShowCustomTextGrid(true);
mRenderer.setGridColor(Color.rgb(162,172,186));
if(chartView!=null)
{
chartView.repaint();
}
else{
chartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer);
//chartView.repaint();
//layout.addView(chartView, new LayoutParams(960,LayoutParams.FILL_PARENT));
}
chartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = chartView.getCurrentSeriesAndPoint();
double[] xy = chartView.toRealPoint(0);
if (seriesSelection == null)
{
//Toast.makeText(getActivity(), "No chart element was clicked", Toast.LENGTH_SHORT).show();
} else {
Long values = (long) seriesSelection.getValue();
mapValuesText = jsonListString.get(seriesSelection.getSeriesIndex());
int xValue = (int)seriesSelection.getXValue()-1;
Toast.makeText(getActivity(), ""+mapValuesText.get("Text").trim()+". \n"+NumberFormat.getNumberInstance(Locale.GERMAN).format(values)
+" BBLs pada Hari ke-"+dateStringArray.get(xValue)+""
, Toast.LENGTH_LONG).show();
}
}
});
LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.dashboard_chart_layout_gas);
layout.removeAllViews();
layout.addView(chartView);
} catch (JSONException e)
{
e.printStackTrace();
}
}//End of doInBackground
}}
这是另一个片段类
public class HomeFragment extends Fragment {
//Development URL
private static String url = "http://192.168.0.100/jsontraining/production.json";
//Y-Values
private static ArrayList<HashMap<String, ArrayList<Long>>> jsonlist = new ArrayList<HashMap<String, ArrayList<Long>>>();
private static HashMap<String, ArrayList<Long>> mapValues = new HashMap<String, ArrayList<Long>>();
//Legends
private static ArrayList<HashMap<String, String>> jsonListString = new ArrayList<HashMap<String, String>>();
private static HashMap<String, String> mapValuesText = new HashMap<String,String>();
private static ArrayList<String> dateStringArray = new ArrayList<String>();
private GraphicalView chartView;
private XYMultipleSeriesRenderer mRenderer;
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
//setRetainInstance(true);
new JSONParse().execute();
return rootView;
}
@SuppressWarnings("unchecked")
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onResume()
{
super.onResume();
jsonlist.clear();
mapValues.clear();
jsonListString.clear();
mapValuesText.clear();
}
private class JSONParse extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}//End of onPreExecute
@Override
protected JSONObject doInBackground(String... args)
{
while(!isCancelled())
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
return null;
}//End of doInBackground
@Override
protected void onCancelled(JSONObject json) {
Toast.makeText(getActivity(), "Cancelled. Cannot retrieve data at this time. Please try again later.", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
try
{
//Fetching Array of Elements
JSONArray jsonArray = json.getJSONArray("elements");
//Fetching for TextView
//Fetching for Pertamina EP
TextView uid;
uid = (TextView) getActivity().findViewById(R.id.txtLabel);
JSONObject jsonElementsText = jsonArray.getJSONObject(jsonArray.length()-1);
String text = jsonElementsText.getString("text");
//Fetching for Date
JSONObject jsonObjectXAxis = json.getJSONObject("x_axis");
JSONObject jsonObjectXAxisLabels = jsonObjectXAxis.getJSONObject("labels");
JSONArray jsonArrayXAxisLabels = jsonObjectXAxisLabels.getJSONArray("labels");
for(int i=0;i<jsonArrayXAxisLabels.length();i++)
{
dateStringArray.add((String) jsonArrayXAxisLabels.getString(i));
}
String jsonArrayStringXAxisLabels = (String) jsonArrayXAxisLabels.getString(jsonArrayXAxisLabels.length()-1);
//JSON String to Date Format
char[] dateChar = jsonArrayStringXAxisLabels.toCharArray();
String day = ""+dateChar[0]+""+dateChar[1]+"";
String monthNo = ""+dateChar[3]+""+dateChar[4]+"";
if(monthNo.matches("01"))
{
monthNo="January";
}
if(monthNo.matches("01"))
{
monthNo="January";
}
if(monthNo.matches("02"))
{
monthNo="February";
}
if(monthNo.matches("03"))
{
monthNo="March";
}
if(monthNo.matches("04"))
{
monthNo="April";
}
if(monthNo.matches("05"))
{
monthNo="May";
}
if(monthNo.matches("06"))
{
monthNo="June";
}
if(monthNo.matches("07"))
{
monthNo="July";
}
if(monthNo.matches("08"))
{
monthNo="August";
}
if(monthNo.matches("09"))
{
monthNo="September";
}
if(monthNo.matches("10"))
{
monthNo="October";
}
if(monthNo.matches("11"))
{
monthNo="November";
}
if(monthNo.matches("12"))
{
monthNo="December";
}
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
int year = today.year;
//Fetching for Number
JSONArray jsonArrayValues = jsonElementsText.getJSONArray("values");
Long arrayValuesMax = jsonArrayValues.getLong(jsonArrayValues.length()-1);
//Fetching to Text View
//uid.setText("Total produksi minyak "+text+", "+day+" "+monthNo+" "+year+" = "+arrayValuesMax+" BBLs");
uid.setText(Html.fromHtml("Total produksi minyak <b>"+text+"</b>, "+day+" "+monthNo+" "+year+" = <b>"+NumberFormat.getNumberInstance(Locale.GERMAN).format(arrayValuesMax)+"</b> BBLs"));
JSONObject jsonYAxis = json.getJSONObject("y_axis");
Long yAxisMin = jsonYAxis.getLong("min");
Long yAxisMax = jsonYAxis.getLong("max");
for (int i=0;i<jsonArray.length();i++)
{
ArrayList<Long> list = new ArrayList<Long>();
HashMap<String, ArrayList<Long>> mapValues = new HashMap<String, ArrayList<Long>>();
JSONObject elementNo = (JSONObject) jsonArray.get(i);
JSONArray valuesGraph = (JSONArray) elementNo.get("values");
String texts = elementNo.getString("text");
int len = valuesGraph.length();
for (int x=0;x<len;x++)
{
if(!valuesGraph.isNull(x))
{
Long nilai = (Long)valuesGraph.getLong(x);
list.add(nilai);
}
}
mapValues.put("Values", list);
mapValuesText.put("Text", texts);
jsonlist.add(mapValues);
jsonListString.add(mapValuesText);
}
//Line Graph
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer();
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.rgb(254, 254, 254));
mRenderer.setMarginsColor(Color.rgb(254, 254, 254));
int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
for(int start=0; start<jsonlist.size(); start++)
{
start++;
mapValuesText = jsonListString.get(start-1);
TimeSeries series = new TimeSeries(mapValuesText.get("Text").trim());
start--;
mapValues = jsonlist.get(start);
int jumlahValues = mapValues.get("Values").size();
for(int i=0; i<jumlahValues; i++)
{
series.add(x[i], mapValues.get("Values").get(i));
}
dataset.addSeries(series);
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setShowLegendItem(true);
renderer.setChartValuesTextSize(24);
renderer.setColor(Color.rgb(0,108,183));
renderer.setLineWidth(3);
renderer.setPointStyle(PointStyle.CIRCLE);
renderer.setFillPoints(true);
//renderer.setDisplayChartValues(true);
mRenderer.addSeriesRenderer(renderer);
}
//XY Titles
mRenderer.setYTitle("Production");
//mRenderer.setXTitle("Date");
mRenderer.setAxisTitleTextSize(22);
mRenderer.setLabelsTextSize(22);
mRenderer.setXLabelsColor(Color.BLACK);
mRenderer.setYLabelsColor(0, Color.BLACK);
mRenderer.setShowLabels(true);
//Legends
mRenderer.setShowLegend(true);
//mRenderer.setFitLegend(true);
mRenderer.setLegendTextSize(20);
mRenderer.setXLabelsPadding(20);
mRenderer.setYLabelsAlign(Align.RIGHT, 0);
mRenderer.setYLabelsPadding(7);
mRenderer.setYLabelsVerticalPadding(-5);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
for (int i = 0; i < jsonArrayXAxisLabels.length();)
{
String xChartDates = jsonArrayXAxisLabels.getString(i);
mRenderer.addTextLabel(i+1, xChartDates);
if(mapValues.get("Values").size()<9)
{
i=i+1;
}
else
{
i=i+4;
}
}
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setXLabels(0);
} else {
for (int i = 0; i < jsonArrayXAxisLabels.length(); i++)
{
String xChartDates = jsonArrayXAxisLabels.getString(i);
mRenderer.addTextLabel(i+1, xChartDates);
}
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setXLabels(0);
}
mRenderer.setAxesColor(Color.BLACK);
mRenderer.setLabelsColor(Color.BLACK);
mRenderer.setMargins(new int[]{ 10, 110, 10, 10});
mRenderer.setYAxisMax(yAxisMax);
mRenderer.setYAxisMin(yAxisMin);
mRenderer.setXAxisMin(0);
mRenderer.setXAxisMax(jsonArrayXAxisLabels.length());
mRenderer.setPointSize(9.5f);
//mRenderer.setPanLimits(new double[]{0, (jsonArrayXAxisLabels.length())*1.1, yAxisMin, yAxisMax});
mRenderer.setInScroll(true);
mRenderer.setClickEnabled(true);
mRenderer.setPanEnabled(true);
mRenderer.setZoomEnabled(true);
mRenderer.setZoomLimits(new double[]{0, (jsonArrayXAxisLabels.length())*1.1, yAxisMin, yAxisMax});
//Grid
mRenderer.setShowGrid(true);
mRenderer.setShowCustomTextGrid(true);
mRenderer.setGridColor(Color.rgb(162,172,186));
if(chartView!=null)
{
chartView.repaint();
}
else{
chartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer);
}
chartView.addZoomListener(new ZoomListener() {
@Override
public void zoomReset() {
// TODO Auto-generated method stub
}
@Override
public void zoomApplied(ZoomEvent arg0) {
// TODO Auto-generated method stub
}
}, true, true);
chartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = chartView.getCurrentSeriesAndPoint();
if (seriesSelection == null)
{
chartView.repaint();
} else {
Long values = (long) seriesSelection.getValue();
mapValuesText = jsonListString.get(seriesSelection.getSeriesIndex());
int xValue = (int)seriesSelection.getXValue()-1;
Toast.makeText(getActivity(), "Total produksi minyak "+mapValuesText.get("Text")+", "+dateStringArray.get(xValue)+" = "
+NumberFormat.getNumberInstance(Locale.GERMAN).format(values)
+" BBLs", Toast.LENGTH_LONG).show();
}
}
});
LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.dashboard_chart_layout);
layout.removeAllViews();
layout.addView(chartView);
TextView failedText;
failedText = (TextView) getActivity().findViewById(R.id.txtFailedLabel_home);
failedText.setVisibility(View.GONE);
} catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getActivity(), "JSONException. Cannot retrieve data at this time. Please try again later.", Toast.LENGTH_SHORT).show();
TextView failedText;
failedText = (TextView) getActivity().findViewById(R.id.txtFailedLabel_home);
failedText.setText("Please Retry");
}
catch(Exception e){
e.printStackTrace();
Toast.makeText(getActivity(), "Exception. Cannot retrieve data at this time. Please try again later.", Toast.LENGTH_SHORT).show();
TextView failedText;
failedText = (TextView) getActivity().findViewById(R.id.txtFailedLabel_home);
failedText.setText("Please Retry");
}
}//End of doInBackground
}}