Android的异步 - 更新对话框中的消息循环 [英] android Async - Update Dialog Message in loop
问题描述
我想更新我的提醒对话框中的消息。我想要的对话框显示图完成更新%左右。
请稍候...
这些图加载...
0%已完成
我想通了,如何让每次循环迭代的百分比,我有一个很难更新对话框,正确的百分比。在此先感谢!!!!
//我的XML对象的TextView
<的TextView
机器人:ID =@ + ID / percentloaded
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:文本=这些图表载入中... \\ N0%完成
机器人:layout_gravity =右
机器人:知名度=隐形
机器人:文字颜色=#FFFFFF/>
//我怎么称呼异步我在创建函数中
新MyAsync()执行();
//我的onCreate()
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState); 的setContentView(R.layout.activity_network_showcharts);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//有趣的小片段,从截屏prevents用户
//在ICS +设备:-)
getWindow()。setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
//Toast.makeText(NetworkAllInformation_ShowChart.this,请等待图形完成加载,Toast.LENGTH_SHORT).show(); progressDialog =新ProgressDialog(NetworkAllInformation_ShowChart.this);
cycleDate =(的TextView)findViewById(R.id.CycleDateAnswer);
cycleDay =(的TextView)findViewById(R.id.CycleDayAnswer);
cycleDailyUsage =(的TextView)findViewById(R.id.CycleUsageAnswer);
cycleOverallUsage =(的TextView)findViewById(R.id.TotalUsageAnswer);
percentLoaded =(的TextView)findViewById(R.id.percentloaded);
stringofZero =0; 剧情=(XYPlot)findViewById(R.id.mySimpleXYPlot); alertDialogBuilder =新AlertDialog.Builder(本); 最终日历日历= Calendar.getInstance();
年= calendar.get(Calendar.YEAR);
月= calendar.get(的Calendar.MONTH);
天= calendar.get(Calendar.DAY_OF_MONTH); 的currentdate =(月+ 1)+ - +日+ - +年;
theNumberOfDaysToCompare =日; intObj =新的整数(theNumberOfDaysToCompare); intNumberOfMaxGBsAccepted = 0;
numObj =(数字)intObj; series1Numbers =新号码[(整数)numObj]
series2Numbers =新号码[(整数)numObj]
series3Numbers =新号码[(整数)numObj] 处理器=新的处理程序();
ParseQuery<&的parseObject GT; query0 = ParseQuery.getQuery(ClientCompanyInfo);
query0.whereEqualTo(SITEID,ShowSatellitesActivity.IDchosen);
query0.addAscendingOrder(SITEID);
query0.setLimit(1000);
query0.selectKeys(Arrays.asList(UsagePlan)); 清单<&的parseObject GT; results0 = NULL;
尝试{
results0 = query0.find();
}赶上(ParseException的E1){
// TODO自动生成catch块
e1.printStackTrace();
}
的System.out.println(query0尺寸:+ results0.size());
对于(的parseObject数据:results0){
//这不需要一个网络访问。 的Integer.parseInt(data.getString(UsagePlan));
的System.out.println(使用计划为:+的Integer.parseInt(data.getString(UsagePlan))); 如果(的Integer.parseInt(data.getString(UsagePlan))> = 1)
{
的System.out.println(使用计划是一组数字);
intNumberOfMaxGBsAccepted =的Integer.parseInt(data.getString(UsagePlan)); } //如果结束 } // for循环结束 新MyAsync()执行(); 总和= 0;} //上创建结束
//我的异步任务
私有静态类MyAsync扩展的AsyncTask<无效,整数,字符串> { @覆盖
在preExecute保护无效(){ super.on preExecute(); //设置标题
alertDialogBuilder.setTitle(请稍候...); alertDialogBuilder.setCancelable(假);
//设置对话框消息
alertDialogBuilder.setMessage(percentLoaded.getText()); //创建警报对话框
alertDialog = alertDialogBuilder.create(); // 展示下
alertDialog.show(); }
保护静态无效onProgressUpdate(整数进度){
alertDialog.setMessage(以下简称图加载... \\ n+进步[0] +%完成);
alertDialog.dismiss();
的System.out.println(onProgressUpdate:+进步[0]);
} 保护无效onPostExecute(字符串结果){ 的System.out.println(onPostExecute:+结果); alertDialog.setMessage(以下简称图加载... \\ n+结果+%完成); } @覆盖
保护字符串doInBackground(虚空...... PARAMS){
// TODO自动生成方法存根 增量器= 0;
的for(int i = 0; I<日,我++){ //取得有关用户的信息
ParseQuery<&的parseObject GT;查询= ParseQuery.getQuery(UsageCalculator);
query.whereEqualTo(SITEID,ShowSatellitesActivity.IDchosen);
query.addAscendingOrder(SITEID);
query.setLimit(1000);
query.getFirstInBackground(新GetCallback<&的parseObject GT;(){ 公共无效做过(的parseObject dailyUsage,ParseException的E){ 如果(E == NULL){ dayString =(1 +增量器);
的System.out.println(天数:+ Integer.toString(dayString)); getThePercent = Integer.toString((INT)((100 /(浮点)天)* dayString));
的System.out.println(getThePercent);
整数percentInt = Integer.valueOf((100 /天)* dayString); 尝试{ publishProgress(percentInt);
视频下载(1000);
}赶上(例外E1){
e1.printStackTrace();
}
//开始
ParseQuery<&的parseObject GT; QUERY2 = ParseQuery.getQuery(UsageCalculator);
query2.whereEqualTo(monthString,将String.valueOf(月+ 1)); //这个月
query2.whereEqualTo(SITEID,dailyUsage.getString(SITEID)); //选择ID
query2.whereEqualTo(yearString,将String.valueOf(年)); //今年
query2.whereEqualTo(dayString,Integer.toString(dayString)); //递增通过对每天都有
query2.addAscendingOrder(SITEID);
query2.setLimit(1000);
query2.selectKeys(Arrays.asList(dataUsedString,usageDate)); //带出的信息的日期和使用列
清单<&的parseObject GT;结果= NULL; 尝试{
结果= query2.find(); }赶上(ParseException的E1){
// TODO自动生成catch块
e1.printStackTrace();
}
的System.out.println(query8尺寸:+ results.size());
对于(的parseObject数据:结果){
//这不需要一个网络访问。 myArray.add(data.getString(dataUsedString));
} //最后一天达到
如果(myArray.size()==天-1){
alertDialog.dismiss();
plot.clear(); //删除旧的情节
updateGraphValues(); //获取图形值
updateGraphBackground(); //设置的值的图
plot.redraw(); //重绘正确值的积
}
增量器++; } //如果异常处理程序为null 其他{
Log.d(showChart,错误:+ e.getMessage()); //如果他们的却是一个例外
} } //结束DONE
}); //结束查询 } //结束for循环
返回;
} }
//其他函数调用
私有静态无效updateGraphValues(){ 的for(int i = 0; I< myArray.size();我++){ usageValue = Double.parseDouble(myArray.get(I)); //日常使用数组
series2Numbers [I] = usageValue;
//总用量Sumation公司阵
series1Numbers [I] =(usageValue + increasingSum);
//最大值
series3Numbers [I] = intNumberOfMaxGBsAccepted;
vector.add((双)一);
vector.add(Math.sin(I)); //保持运行总和
如果(usageValue!= 0){increasingSum = increasingSum + usageValue; }
} increasingSum = 0;} //结束更新图形函数值私有静态无效updateGraphBackground(){ //开启上面的阵列到XYSeries:
系列1 =新SimpleXYSeries(
Arrays.asList(series1Numbers),// SimpleXYSeries需要的列表,以便把我们的数组列表
SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,// Y_VALS_ONLY意味着使用元素索引的x值
总); //设置一系列的显示标题 //与上述相同
系列2 =新SimpleXYSeries(Arrays.asList(series2Numbers),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,人民日报);
系列3 =新SimpleXYSeries(Arrays.asList(series3Numbers),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,麦克斯);
series1Format =新LineAndPointFormatter(Color.rgb(51,51,255),0,Color.rgb(51,153,255),NULL);
。series1Format.getFillPaint()setStrokeJoin(Paint.Join.ROUND);
series1Format.getFillPaint()setStrokeCap(Paint.Cap.ROUND)。
series1Format.getFillPaint()setPathEffect(新CornerPathEffect(10))。
series1Format.getFillPaint()setAntiAlias(真)。
series1Format.getFillPaint()setStrokeWidth(8)。
//与上面相同:
//每日果岭
series2Format =新LineAndPointFormatter(Color.rgb(51,255,153),0,Color.rgb(153,255,204),NULL); 。series2Format.getFillPaint()setStrokeJoin(Paint.Join.ROUND);
series2Format.getFillPaint()setStrokeCap(Paint.Cap.ROUND)。
series2Format.getFillPaint()setPathEffect(新CornerPathEffect(10))。
series2Format.getFillPaint()setAntiAlias(真)。
series2Format.getFillPaint()setStrokeWidth(8)。 series3Format =新LineAndPointFormatter(Color.rgb(255,51,51),0,0,NULL); 。series3Format.getFillPaint()setStrokeJoin(Paint.Join.ROUND);
series3Format.getFillPaint()setStrokeCap(Paint.Cap.ROUND)。
series3Format.getFillPaint()setPathEffect(新CornerPathEffect(10))。
series3Format.getFillPaint()setAntiAlias(真)。
series3Format.getFillPaint()setStrokeWidth(8)。
//添加一个新的系列到xyplot:
plot.addSeries(系列1,series1Format); //这一个人必须首先该域和范围,可以发现本系列
plot.addSeries(系列2,series2Format);
plot.addSeries(系列3,series3Format); //减少范围的标签数
plot.setTicksPerRangeLabel(1);
。plot.getGraphWidget()setDomainLabelOrientation(45); plot.calculateMinMaxVals();
minXy =新的PointF(plot.getCalculatedMinX()的floatValue(),plot.getCalculatedMinY()的floatValue());
maxXY =新的PointF(plot.getCalculatedMaxX()的floatValue(),plot.getCalculatedMaxY()的floatValue()); // plot.setClickable(真); //注意有关XYPlotZoomPan:当OnTouchListener设置,缩放将被禁用。子类,以避免它。
plot.setOnTouchListener(新View.OnTouchListener(){ 公共布尔onTouch(视图V,MotionEvent我){
//将开始寻找触摸的点,然后绘制两条线和标签的线条
touchX = me.getX();
敏感= me.getY();
插件= plot.getGraphWidget();
gridRect = widget.getGridRect();
如果(gridRect.contains(touchX,敏感)){//检查触摸事件是在网格
XYSeries xyData = plot.getSeriesSet()迭代器的next()();
长targetValX = Math.round(widget.getXVal(touchX));
的System.out.println(+ touchX +,+敏感+。目标VAL X:在触摸+ targetValX); 如果(plot.getSeriesSet()大小()→1){
的System.out.println(多个系列的情节只使用第一个。);
}
的for(int i = 0; I< xyData.size(); ++ I){
长currValX = xyData.getX(I).longValue();
长currValY = xyData.getY(I).longValue(); //计算最近的域值的范围值(假定xyData在升序排序X排序)
如果(currValX> = targetValX){
长currDiff = currValX - targetValX;
如果(prevValX = NULL&放大器;&安培;!(targetValX - prevValX)LT; currDiff){
targetValY = xyData.getY(I-1).longValue();
}其他{
targetValY = currValY;
}
打破;
}
prevValX = currValX;
}
如果(targetValY!= NULL){
长maxValY = plot.getCalculatedMaxY()的longValue()。
长minValY = plot.getCalculatedMinY()的longValue()。
的System.out.println(目标Y值+ targetValY);
浮pixelPosY = gridRect.top + ValPixConverter.valToPix((双)targetValY,(双)minValY,(双)maxValY,(浮点)gridRect.height(),TRUE);
的System.out.println(像素位置Y:+ pixelPosY); 数numberForDaily = series2Numbers [(int)的targetValX]; widget.setDomainCursorPosition(touchX);
的System.out.println(触摸X:+ touchX); plot.getGraphWidget()的setSize(新SizeMetrics(
0,SizeLayoutType.FILL,
0,SizeLayoutType.FILL) );
涂料paintForText =新的油漆();
paintForText.setColor(Color.BLACK); 涂料paintForTextBackroud =新的油漆();
paintForTextBackroud.setColor(Color.WHITE);
widget.setCursorLabelPaint(paintForText);
widget.setCursorLabelBackgroundPaint(paintForTextBackroud);
widget.getDomainLabelPaint()setTextSize(20)。
widget.getRangeLabelPaint()setTextSize(20)。
widget.getCursorLabelPaint()setTextSize(25)。 的System.out.println(游标是=+ targetValX ++ targetValY); getTheStartDate(); 日历CAL =新的GregorianCalendar(年,月+ 1日);
整数theNumberOfTheStartDay = cal.get(GregorianCalendar.DAY_OF_YEAR); //偏移
整数addingTheDates =(theNumberOfTheStartDay +(INT)targetValX); //数字转换到可读的日期
GregorianCalendar的gcDate =新的GregorianCalendar();
gcDate.set(GregorianCalendar.DAY_OF_YEAR,addingTheDates);
//如果该月的天小于10
//添加一个零到它的前面,使该字符串可订购
如果(gcDate.get(GregorianCalendar.DAY_OF_MONTH)小于10){
StringBuilder的SB =新的StringBuilder();
sb.append(0);
sb.append(gcDate.get(GregorianCalendar.DAY_OF_MONTH));
fixZeroInDate = sb.toString();
}其他{
fixZeroInDate =将String.valueOf(gcDate.get(GregorianCalendar.DAY_OF_MONTH));
}
字符串stringOfFinalCycleDate =
(gcDate.get((GregorianCalendar.MONTH)))+/+
fixZeroInDate +/+
gcDate.get(GregorianCalendar.YEAR); //更新TEXTVIEWS基于BUTTON TAP
cycleDate.setText(stringOfFinalCycleDate); //循环日期 cycleDay.setText(Long.toString(targetValX)); //周期天 cycleDailyUsage.setText(numberForDaily.toString());单周期一天//使用 的System.out.println(现在就开始时间);
//做数学题,以获得运行总使用量
findtheUsageSum(stringOfFinalCycleDate);
DecimalFormat的DF =新的DecimalFormat(#0.00);
cycleOverallUsage.setText(将String.valueOf(df.format(usageSumOnClick))); //由循环白天总体使用
的System.out.println(多少时间已经过去了?); }其他{
的System.out.println(无法找到最近的范围内选定域坐标);
} plot.invalidate();
}其他{
的System.out.println(感动的情节外网格);
} 返回false;
} 私人无效findtheUsageSum(字符串stringOfFinalCycleDate){ ParseQuery<&的parseObject GT; QUERY3 = ParseQuery.getQuery(UsageCalculator);
query3.whereEqualTo(SITEID,ShowSatellitesActivity.IDchosen);
query3.addAscendingOrder(SITEID);
query3.setLimit(10000);
query3.whereLessThanOrEqualTo(usageDate,stringOfFinalCycleDate);
query3.selectKeys(Arrays.asList(dataUsedString,usageDate));
清单<&的parseObject GT;结果1 = NULL;
尝试{
结果1 = query3.find();
}赶上(ParseException的E1){
// TODO自动生成catch块
e1.printStackTrace();
} usageSumOnClick = 0;
的System.out.println(QUERY3尺寸:+ results1.size());
对于(的parseObject数据:结果:1){
//循环所有的日期和使用 的System.out.println(数据使用:+ data.getString(dataUsedString));
的System.out.println(关于日期:+ data.getString(usageDate));
usageSumOnClick = usageSumOnClick + Double.parseDouble(data.getString(dataUsedString)); } // for循环结束
} //结束发现使用功能 私人无效getTheStartDate(){
最终日历日历= Calendar.getInstance(); 年= calendar.get(Calendar.YEAR);
月= calendar.get(的Calendar.MONTH);
天= 1; 的startDate =(月+ 1)+ - +日+ - +年; }
});
}
重写 onProgressUpdate
方法,即AsyncTask的为您提供,不要创建你自己的。
另外,不要叫 onProgressUpdate
自己!这是由系统使用,为您提供一个回调到你的UI线程的回调方法。如果你直接称呼它,code将后台线程,在那里你可以不更新UI内运行。相反,使用 publishProgress
。
编辑:要能传递一个合适的值到 publishProgress
,你还需要在延长的AsyncTask指定泛型类型(第二个泛型类型是一个用于进度)。
尝试这样的:
私有静态类MyAsync扩展的AsyncTask<无效,整数,字符串> {
....@覆盖
保护无效onProgressUpdate(整数...进度){
alertDialog.setMessage(以下简称图加载... \\ n+进步[0] +%完成);
}@覆盖
保护字符串doInBackground(虚空...... PARAMS){
增量器= 0;
的for(int i = 0; I<日,我++){
publishProgress(getThePercent);
....
I am trying to update the message in my alert dialog. I want the dialog show the updated percent of graph completion.
Please wait... The graphs are loading ...
0% completed
I figured out how to get the percent of each loop iteration, I am having a hard time updating the dialog to the correct percent. Thanks in advance!!!!
//my xml textview object
<TextView
android:id="@+id/percentloaded"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="The graphs are loading...\n0% Completed"
android:layout_gravity="right"
android:visibility="invisible"
android:textColor="#FFFFFF" />
//how I call the async inside of my in create function
new MyAsync().execute();
//my onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_showcharts);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// fun little snippet that prevents users from taking screenshots
// on ICS+ devices :-)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
//Toast.makeText(NetworkAllInformation_ShowChart.this, "Please wait for graphs to finish loading", Toast.LENGTH_SHORT).show();
progressDialog = new ProgressDialog(NetworkAllInformation_ShowChart.this);
cycleDate = (TextView) findViewById(R.id.CycleDateAnswer);
cycleDay = (TextView) findViewById(R.id.CycleDayAnswer);
cycleDailyUsage = (TextView) findViewById(R.id.CycleUsageAnswer);
cycleOverallUsage = (TextView) findViewById(R.id.TotalUsageAnswer);
percentLoaded = (TextView) findViewById(R.id.percentloaded);
stringofZero = "0";
plot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
alertDialogBuilder = new AlertDialog.Builder(this);
final Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
currentDate = (month+1) +"-" +day+ "-"+ year;
theNumberOfDaysToCompare = day;
intObj = new Integer(theNumberOfDaysToCompare);
intNumberOfMaxGBsAccepted = 0;
numObj = (Number)intObj;
series1Numbers = new Number[(Integer) numObj];
series2Numbers = new Number[(Integer) numObj];
series3Numbers = new Number[(Integer) numObj];
handler = new Handler();
ParseQuery<ParseObject> query0 = ParseQuery.getQuery("ClientCompanyInfo");
query0.whereEqualTo("SiteID", ShowSatellitesActivity.IDchosen);
query0.addAscendingOrder("SiteID");
query0.setLimit(1000);
query0.selectKeys(Arrays.asList("UsagePlan"));
List<ParseObject> results0 = null;
try {
results0 = query0.find();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("query0 size: "+results0.size());
for (ParseObject data : results0) {
// This does not require a network access.
Integer.parseInt(data.getString("UsagePlan"));
System.out.println("the usage plan is: "+Integer.parseInt(data.getString("UsagePlan")) );
if(Integer.parseInt(data.getString("UsagePlan")) >=1 )
{
System.out.println("The usage plan is a set number");
intNumberOfMaxGBsAccepted = Integer.parseInt(data.getString("UsagePlan"));
} //ends if
}//ends for loop
new MyAsync().execute();
sum = 0;
} //ends on create
//my Async Task
private static class MyAsync extends AsyncTask <Void, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// set title
alertDialogBuilder.setTitle("Please wait...");
alertDialogBuilder.setCancelable(false);
// set dialog message
alertDialogBuilder.setMessage(percentLoaded.getText());
// create alert dialog
alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
protected static void onProgressUpdate(Integer progress) {
alertDialog.setMessage("The graphs are loading...\n"+progress[0]+"% Completed");
alertDialog.dismiss();
System.out.println("onProgressUpdate: "+progress[0]);
}
protected void onPostExecute(String result) {
System.out.println("onPostExecute: "+result);
alertDialog.setMessage("The graphs are loading...\n"+result+"% Completed");
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
incrementor = 0;
for ( int i = 0; i<day; i++){
//get information about the user
ParseQuery<ParseObject> query = ParseQuery.getQuery("UsageCalculator");
query.whereEqualTo("SiteID", ShowSatellitesActivity.IDchosen);
query.addAscendingOrder("SiteID");
query.setLimit(1000);
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject dailyUsage, ParseException e) {
if (e == null) {
dayString = (1+incrementor);
System.out.println("Day number: "+Integer.toString(dayString));
getThePercent = Integer.toString((int) ((100 / (float) day) * dayString));
System.out.println(getThePercent);
Integer percentInt = Integer.valueOf((100 /day) * dayString);
try{
publishProgress(percentInt);
Thread.sleep(1000);
} catch(Exception e1){
e1.printStackTrace();
}
//start
ParseQuery<ParseObject> query2 = ParseQuery.getQuery("UsageCalculator");
query2.whereEqualTo("monthString", String.valueOf(month+1)); //current month
query2.whereEqualTo("SiteID", dailyUsage.getString("SiteID")); //the selected ID
query2.whereEqualTo("yearString", String.valueOf(year)); //current year
query2.whereEqualTo("dayString", Integer.toString(dayString)); //incremented through to have every day
query2.addAscendingOrder("SiteID");
query2.setLimit(1000);
query2.selectKeys(Arrays.asList("dataUsedString", "usageDate")); //take the information out of the date and usage columns
List<ParseObject> results = null;
try {
results = query2.find();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("query8 size: "+results.size());
for (ParseObject data : results) {
// This does not require a network access.
myArray.add(data.getString("dataUsedString"));
}
//the last day reached
if(myArray.size() == day-1){
alertDialog.dismiss();
plot.clear(); //erase the old plot
updateGraphValues(); //get values of graph
updateGraphBackground(); //set the values to the graph
plot.redraw(); //redraw the plot with the correct values
}
incrementor++;
} //if the exception handler is null
else {
Log.d("showChart", "Error: " + e.getMessage()); //if their is an exception
}
} //ends the done
}); //ends the query
} //ends the for loop
return "";
}
}
//other function calls
private static void updateGraphValues() {
for (int i = 0; i<myArray.size(); i++){
usageValue = Double.parseDouble(myArray.get(i));
//daily usage array
series2Numbers[i] = usageValue;
//total usage sumation array
series1Numbers[i] = (usageValue+increasingSum);
//the max value
series3Numbers[i] = intNumberOfMaxGBsAccepted;
vector.add((double) i);
vector.add(Math.sin(i));
//keeping a running sum
if(usageValue!=0) { increasingSum= increasingSum+usageValue; }
}
increasingSum = 0;
} // ends updating the graph value function
private static void updateGraphBackground() {
// Turn the above arrays into XYSeries':
series1 = new SimpleXYSeries(
Arrays.asList(series1Numbers), // SimpleXYSeries takes a List so turn our array into a List
SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // Y_VALS_ONLY means use the element index as the x value
"Total"); // Set the display title of the series
// same as above
series2 = new SimpleXYSeries(Arrays.asList(series2Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Daily");
series3 = new SimpleXYSeries(Arrays.asList(series3Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Max");
series1Format = new LineAndPointFormatter(Color.rgb(51, 51, 255), 0, Color.rgb(51, 153, 255), null);
series1Format.getFillPaint().setStrokeJoin(Paint.Join.ROUND);
series1Format.getFillPaint().setStrokeCap(Paint.Cap.ROUND);
series1Format.getFillPaint().setPathEffect(new CornerPathEffect(10) );
series1Format.getFillPaint().setAntiAlias(true);
series1Format.getFillPaint().setStrokeWidth(8);
// same as above:
//daily green
series2Format = new LineAndPointFormatter(Color.rgb(51, 255, 153), 0, Color.rgb(153, 255, 204), null);
series2Format.getFillPaint().setStrokeJoin(Paint.Join.ROUND);
series2Format.getFillPaint().setStrokeCap(Paint.Cap.ROUND);
series2Format.getFillPaint().setPathEffect(new CornerPathEffect(10) );
series2Format.getFillPaint().setAntiAlias(true);
series2Format.getFillPaint().setStrokeWidth(8);
series3Format = new LineAndPointFormatter(Color.rgb(255, 51, 51), 0, 0, null);
series3Format.getFillPaint().setStrokeJoin(Paint.Join.ROUND);
series3Format.getFillPaint().setStrokeCap(Paint.Cap.ROUND);
series3Format.getFillPaint().setPathEffect(new CornerPathEffect(10) );
series3Format.getFillPaint().setAntiAlias(true);
series3Format.getFillPaint().setStrokeWidth(8);
// add a new series' to the xyplot:
plot.addSeries(series1, series1Format); //this one has to be first to that the domain and range can be found for this series
plot.addSeries(series2, series2Format);
plot.addSeries(series3, series3Format);
// reduce the number of range labels
plot.setTicksPerRangeLabel(1);
plot.getGraphWidget().setDomainLabelOrientation(45);
plot.calculateMinMaxVals();
minXy=new PointF(plot.getCalculatedMinX().floatValue(),plot.getCalculatedMinY().floatValue());
maxXY=new PointF(plot.getCalculatedMaxX().floatValue(),plot.getCalculatedMaxY().floatValue());
// plot.setClickable(true);
//NOTE about XYPlotZoomPan: when an OnTouchListener is set, zooming is disabled. Subclass to avoid it.
plot.setOnTouchListener(new View.OnTouchListener(){
public boolean onTouch(View v, MotionEvent me) {
//the begin of finding a point touched, then drawing two lines, and labeling the lines
touchX = me.getX();
touchY = me.getY();
widget = plot.getGraphWidget();
gridRect = widget.getGridRect();
if(gridRect.contains(touchX, touchY)){ //Check the touch event is in the grid
XYSeries xyData = plot.getSeriesSet().iterator().next();
long targetValX = Math.round(widget.getXVal(touchX));
System.out.println("Touched at " + touchX + ", " + touchY + ". Target val X: " + targetValX);
if(plot.getSeriesSet().size() > 1){
System.out.println("More than one series in plot. Using only the first one");
}
for(int i = 0; i < xyData.size(); ++i){
long currValX = xyData.getX(i).longValue();
long currValY = xyData.getY(i).longValue();
//Calculate the range value of the closest domain value (assumes xyData is sorted in ascending X order)
if(currValX >= targetValX){
long currDiff = currValX - targetValX;
if(prevValX != null && (targetValX - prevValX) < currDiff){
targetValY = xyData.getY(i-1).longValue();
}else{
targetValY = currValY;
}
break;
}
prevValX = currValX;
}
if(targetValY != null){
long maxValY = plot.getCalculatedMaxY().longValue();
long minValY = plot.getCalculatedMinY().longValue();
System.out.println("Target Y Value"+targetValY);
float pixelPosY = gridRect.top + ValPixConverter.valToPix((double)targetValY, (double)minValY, (double)maxValY, (float)gridRect.height(), true);
System.out.println("Pixel Pos Y: "+pixelPosY);
Number numberForDaily = series2Numbers[ (int)targetValX];
widget.setDomainCursorPosition(touchX);
System.out.println("Touch X: "+touchX);
plot.getGraphWidget().setSize(new SizeMetrics(
0, SizeLayoutType.FILL,
0, SizeLayoutType.FILL)
);
Paint paintForText = new Paint();
paintForText.setColor(Color.BLACK);
Paint paintForTextBackroud = new Paint();
paintForTextBackroud.setColor(Color.WHITE);
widget.setCursorLabelPaint(paintForText);
widget.setCursorLabelBackgroundPaint(paintForTextBackroud);
widget.getDomainLabelPaint().setTextSize(20);
widget.getRangeLabelPaint().setTextSize(20);
widget.getCursorLabelPaint().setTextSize(25);
System.out.println("Cursor is at = "+ targetValX + " " + targetValY);
getTheStartDate();
Calendar cal = new GregorianCalendar(year, month + 1, day);
Integer theNumberOfTheStartDay = cal.get(GregorianCalendar.DAY_OF_YEAR);
//the offset
Integer addingTheDates = (theNumberOfTheStartDay + (int)targetValX);
//convert number to a date which is readable
GregorianCalendar gcDate = new GregorianCalendar();
gcDate.set(GregorianCalendar.DAY_OF_YEAR, addingTheDates);
//if the day of the month is less than 10
//add a zero to the front of it so that the string can be ordered
if(gcDate.get(GregorianCalendar.DAY_OF_MONTH)<10){
StringBuilder sb = new StringBuilder();
sb.append("0");
sb.append(gcDate.get(GregorianCalendar.DAY_OF_MONTH));
fixZeroInDate = sb.toString();
}else{
fixZeroInDate= String.valueOf(gcDate.get(GregorianCalendar.DAY_OF_MONTH));
}
String stringOfFinalCycleDate=
(gcDate.get((GregorianCalendar.MONTH)))+"/"+
fixZeroInDate+"/"+
gcDate.get(GregorianCalendar.YEAR);
//UPDATING THE TEXTVIEWS BASED ON BUTTON TAP
cycleDate.setText(stringOfFinalCycleDate); //cycle date
cycleDay.setText(Long.toString(targetValX)); //cycle day
cycleDailyUsage.setText( numberForDaily.toString());//usage of single cycle day
System.out.println("Start time now");
//do math to get the running total of usage
findtheUsageSum(stringOfFinalCycleDate);
DecimalFormat df = new DecimalFormat("#0.00");
cycleOverallUsage.setText(String.valueOf(df.format(usageSumOnClick))); //overall usage by the cycle day
System.out.println("How much time has passed?");
}else{
System.out.println("Couldn't find the closest range to the selected domain coordinate");
}
plot.invalidate();
}else{
System.out.println("Touched outside the plot grid");
}
return false;
}
private void findtheUsageSum(String stringOfFinalCycleDate) {
ParseQuery<ParseObject> query3 = ParseQuery.getQuery("UsageCalculator");
query3.whereEqualTo("SiteID", ShowSatellitesActivity.IDchosen);
query3.addAscendingOrder("SiteID");
query3.setLimit(10000);
query3.whereLessThanOrEqualTo("usageDate", stringOfFinalCycleDate);
query3.selectKeys(Arrays.asList("dataUsedString", "usageDate"));
List<ParseObject> results1 = null;
try {
results1 = query3.find();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
usageSumOnClick = 0;
System.out.println("query3 size: "+results1.size());
for (ParseObject data : results1) {
// looping for all the dates and usage
System.out.println("data used: "+data.getString("dataUsedString"));
System.out.println("on date: "+data.getString("usageDate"));
usageSumOnClick = usageSumOnClick + Double.parseDouble(data.getString("dataUsedString"));
} //ends for loop
} //ends find the usage function
private void getTheStartDate() {
final Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = 1;
startDate = (month+1) +"-" +day+ "-"+ year;
}
});
}
Override the onProgressUpdate
method, that the AsyncTask provides you, don't create your own.
Also, don't call onProgressUpdate
yourself! This is a callback method that is used by the system to provide you a callback to your UI Thread. If you call it directly, the code will run inside the background Thread, where you can't update the UI. Instead, use publishProgress
.
Edit: to be able to pass a proper value into publishProgress
, you also need to specify the generic type on extending AsyncTask (the second generic type is the one for the progress).
Try it like this:
private static class MyAsync extends AsyncTask <Void, Integer, String> {
....
@Override
protected void onProgressUpdate(Integer... progress) {
alertDialog.setMessage("The graphs are loading...\n"+progress[0]+"% Completed");
}
@Override
protected String doInBackground(Void... params) {
incrementor = 0;
for ( int i = 0; i<day; i++){
publishProgress(getThePercent);
....
这篇关于Android的异步 - 更新对话框中的消息循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!